Programs & Examples On #Django mssql

django-mssql is a SQL Server 2005/2008 backend for Django running on Windows.

ImportError: No module named pythoncom

You should be using pip to install packages, since it gives you uninstall capabilities.

Also, look into virtualenv. It works well with pip and gives you a sandbox so you can explore new stuff without accidentally hosing your system-wide install.

What is ViewModel in MVC?

If you want to study code how to setup a "Baseline" web application with ViewModels I can advise to download this code on GitHub: https://github.com/ajsaulsberry/BlipAjax. I developed large enterprise applications. When you do this its problematic to setup a good architecture that handles all this "ViewModel" functionality. I think with BlipAjax you will have a very Good "baseline" to start with. Its just a simple website, but great in its simplicity. I like the way they used the English language to point at whats really needed in the application.

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

random.sample() also works on text

example:

> text = open("textfile.txt").read() 

> random.sample(text, 5)

> ['f', 's', 'y', 'v', '\n']

\n is also seen as a character so that can also be returned

you could use random.sample() to return random words from a text file if you first use the split method

example:

> words = text.split()

> random.sample(words, 5)

> ['the', 'and', 'a', 'her', 'of']

Manually map column names with class properties

Note that Dapper object mapping isn't case sensitive, so you can name your properties like this:

public class Person 
{
    public int Person_Id { get; set; }
    public string First_Name { get; set; }
    public string Last_Name { get; set; }
}

Or keep the Person class and use a PersonMap:

  public class PersonMap 
        {
            public int Person_Id { get; set; }
            public string First_Name { get; set; }
            public string Last_Name { get; set; }
            public Person Map(){
              return new Person{
                PersonId = Person_Id,
                FirstName = First_Name,
                LastName = Last_Name
               }               
            }
        }

And then, in the query result:

var person = conn.Query<PersonMap>(sql).Select(x=>x.Map()).ToList();

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

Generate the access token from Github and save it, as it will not appear again.

git -c http.sslVerify=false clone https://<username>:<token>@github.com/repo.git

or,

git config --global http.sslVerify false
git clone https://github.com/repo.git

Init method in Spring Controller (annotation version)

public class InitHelloWorld implements BeanPostProcessor {

   public Object postProcessBeforeInitialization(Object bean,
             String beanName) throws BeansException {
       System.out.println("BeforeInitialization : " + beanName);
       return bean;  // you can return any other object as well
   }

   public Object postProcessAfterInitialization(Object bean,
             String beanName) throws BeansException {
       System.out.println("AfterInitialization : " + beanName);
       return bean;  // you can return any other object as well
   }

}

How to properly highlight selected item on RecyclerView?

This is much simple way to do it.

Have a private int selectedPos = RecyclerView.NO_POSITION; in the RecyclerView Adapter class, and under onBindViewHolder method try:

@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {   
    viewHolder.itemView.setSelected(selectedPos == position);

}

And in your OnClick event modify:

@Override
public void onClick(View view) {
     notifyItemChanged(selectedPos);
     selectedPos = getLayoutPosition();
     notifyItemChanged(selectedPos); 
}

Works like a charm for Navigtional Drawer and other RecyclerView Item Adapters.

Note: Be sure to use a background color in your layout using a selector like colabug clarified:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@color/pressed_color" android:state_pressed="true"/>
  <item android:drawable="@color/selected_color" android:state_selected="true"/>
  <item android:drawable="@color/focused_color" android:state_focused="true"/>
</selector>

Otherwise setSelected(..) will do nothing, rendering this solution useless.

Pip freeze vs. pip list

To answer the second part of this question, the two packages shown in pip list but not pip freeze are setuptools (which is easy_install) and pip itself.

It looks like pip freeze just doesn't list packages that pip itself depends on. You may use the --all flag to show also those packages.

From the documentation:

--all

Do not skip these packages in the output: pip, setuptools, distribute, wheel

Accessing bash command line args $@ vs $*

$*

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.

$@

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

Source: Bash man

how to iterate through dictionary in a dictionary in django template?

If you pass a variable data (dictionary type) as context to a template, then you code should be:

{% for key, value in data.items %}
    <p>{{ key }} : {{ value }}</p> 
{% endfor %}

Git command to show which specific files are ignored by .gitignore

Notes:


Also interesting (mentioned in qwertymk's answer), you can also use the git check-ignore -v command, at least on Unix (doesn't work in a CMD Windows session)

git check-ignore *
git check-ignore -v *

The second one displays the actual rule of the .gitignore which makes a file to be ignored in your git repo.
On Unix, using "What expands to all files in current directory recursively?" and a bash4+:

git check-ignore **/*

(or a find -exec command)

Note: https://stackoverflow.com/users/351947/Rafi B. suggests in the comments to avoid the (risky) globstar:

git check-ignore -v $(find . -type f -print)

Make sure to exclude the files from the .git/ subfolder though.


Original answer 42009)

git ls-files -i

should work, except its source code indicates:

if (show_ignored && !exc_given) {
                fprintf(stderr, "%s: --ignored needs some exclude pattern\n",
                        argv[0]);

exc_given ?

It turns out it need one more parameter after the -i to actually list anything:

Try:

git ls-files -i --exclude-from=[Path_To_Your_Global].gitignore

(but that would only list your cached (non-ignored) object, with a filter, so that is not quite what you want)


Example:

$ cat .git/ignore
# ignore objects and archives, anywhere in the tree.
*.[oa]
$ cat Documentation/.gitignore
# ignore generated html files,
*.html
# except foo.html which is maintained by hand
!foo.html
$ git ls-files --ignored \
    --exclude='Documentation/*.[0-9]' \
    --exclude-from=.git/ignore \
    --exclude-per-directory=.gitignore

Actually, in my 'gitignore' file (called 'exclude'), I find a command line that could help you:

F:\prog\git\test\.git\info>type exclude
# git ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
# *.[oa]
# *~

So....

git ls-files --ignored --exclude-from=.git/info/exclude
git ls-files -i --exclude-from=.git/info/exclude

git ls-files --others --ignored --exclude-standard
git ls-files -o -i --exclude-standard

should do the trick.

(Thanks to honzajde pointing out in the comments that git ls-files -o -i --exclude-from... does not include cached files: only git ls-files -i --exclude-from... (without -o) does.)

As mentioned in the ls-files man page, --others is the important part, in order to show you non-cached, non-committed, normally-ignored files.

--exclude_standard is not just a shortcut, but a way to include all standard "ignored patterns" settings.

exclude-standard
Add the standard git exclusions: .git/info/exclude, .gitignore in each directory, and the user's global exclusion file.

Height of status bar in Android

Kotlin version that combines two best solutions

fun getStatusBarHeight(): Int {
    val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
    return if (resourceId > 0) resources.getDimensionPixelSize(resourceId)
    else Rect().apply { window.decorView.getWindowVisibleDisplayFrame(this) }.top
}
  1. Takes status_bar_height value if present
  2. If status_bar_height is not present, calculates the status bar height from Window decor

How to solve "java.io.IOException: error=12, Cannot allocate memory" calling Runtime#exec()?

This is the solution but you have to set:

echo 1 > /proc/sys/vm/overcommit_memory

What's wrong with using == to compare floats in Java?

First of all, are they float or Float? If one of them is a Float, you should use the equals() method. Also, probably best to use the static Float.compare method.

Compare two List<T> objects for equality, ignoring order

This is a slightly difficult problem, which I think reduces to: "Test if two lists are permutations of each other."

I believe the solutions provided by others only indicate whether the 2 lists contain the same unique elements. This is a necessary but insufficient test, for example {1, 1, 2, 3} is not a permutation of {3, 3, 1, 2} although their counts are equal and they contain the same distinct elements.

I believe this should work though, although it's not the most efficient:

static bool ArePermutations<T>(IList<T> list1, IList<T> list2)
{
   if(list1.Count != list2.Count)
         return false;

   var l1 = list1.ToLookup(t => t);
   var l2 = list2.ToLookup(t => t);

   return l1.Count == l2.Count 
       && l1.All(group => l2.Contains(group.Key) && l2[group.Key].Count() == group.Count()); 
}

Angular 6: How to set response type as text while making http call

Use like below:

  yourFunc(input: any):Observable<string> {
var requestHeader = { headers: new HttpHeaders({ 'Content-Type': 'text/plain', 'No-Auth': 'False' })};
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.post<string>(this.yourBaseApi+ '/do-api', input, { headers, responseType: 'text' as 'json'  });

}

How to set index.html as root file in Nginx?

The answer is to place the root dir to the location directives:

root   /srv/www/ducklington.org/public_html;

How do you embed binary data in XML?

Maybe encode them into a known set - something like base 64 is a popular choice.

Android REST client, Sample?

EDIT 2 (October 2017):

It is 2017. Just use Retrofit. There is almost no reason to use anything else.

EDIT:

The original answer is more than a year and a half old at the time of this edit. Although the concepts presented in original answer still hold, as other answers point out, there are now libraries out there that make this task easier for you. More importantly, some of these libraries handle device configuration changes for you.

The original answer is retained below for reference. But please also take the time to examine some of the Rest client libraries for Android to see if they fit your use cases. The following is a list of some of the libraries I've evaluated. It is by no means intended to be an exhaustive list.


Original Answer:

Presenting my approach to having REST clients on Android. I do not claim it is the best though :) Also, note that this is what I came up with in response to my requirement. You might need to have more layers/add more complexity if your use case demands it. For example, I do not have local storage at all; because my app can tolerate loss of a few REST responses.

My approach uses just AsyncTasks under the covers. In my case, I "call" these Tasks from my Activity instance; but to fully account for cases like screen rotation, you might choose to call them from a Service or such.

I consciously chose my REST client itself to be an API. This means, that the app which uses my REST client need not even be aware of the actual REST URL's and the data format used.

The client would have 2 layers:

  1. Top layer: The purpose of this layer is to provide methods which mirror the functionality of the REST API. For example, you could have one Java method corresponding to every URL in your REST API (or even two - one for GETs and one for POSTs).
    This is the entry point into the REST client API. This is the layer the app would use normally. It could be a singleton, but not necessarily.
    The response of the REST call is parsed by this layer into a POJO and returned to the app.

  2. This is the lower level AsyncTask layer, which uses HTTP client methods to actually go out and make that REST call.

In addition, I chose to use a Callback mechanism to communicate the result of the AsyncTasks back to the app.

Enough of text. Let's see some code now. Lets take a hypothetical REST API URL - http://myhypotheticalapi.com/user/profile

The top layer might look like this:

   /**
 * Entry point into the API.
 */
public class HypotheticalApi{   
    public static HypotheticalApi getInstance(){
        //Choose an appropriate creation strategy.
    }
    
    /**
     * Request a User Profile from the REST server.
     * @param userName The user name for which the profile is to be requested.
     * @param callback Callback to execute when the profile is available.
     */
    public void getUserProfile(String userName, final GetResponseCallback callback){
        String restUrl = Utils.constructRestUrlForProfile(userName);
        new GetTask(restUrl, new RestTaskCallback (){
            @Override
            public void onTaskComplete(String response){
                Profile profile = Utils.parseResponseAsProfile(response);
                callback.onDataReceived(profile);
            }
        }).execute();
    }
    
    /**
     * Submit a user profile to the server.
     * @param profile The profile to submit
     * @param callback The callback to execute when submission status is available.
     */
    public void postUserProfile(Profile profile, final PostCallback callback){
        String restUrl = Utils.constructRestUrlForProfile(profile);
        String requestBody = Utils.serializeProfileAsString(profile);
        new PostTask(restUrl, requestBody, new RestTaskCallback(){
            public void onTaskComplete(String response){
                callback.onPostSuccess();
            }
        }).execute();
    }
}


/**
 * Class definition for a callback to be invoked when the response data for the
 * GET call is available.
 */
public abstract class GetResponseCallback{
    
    /**
     * Called when the response data for the REST call is ready. <br/>
     * This method is guaranteed to execute on the UI thread.
     * 
     * @param profile The {@code Profile} that was received from the server.
     */
    abstract void onDataReceived(Profile profile);
    
    /*
     * Additional methods like onPreGet() or onFailure() can be added with default implementations.
     * This is why this has been made and abstract class rather than Interface.
     */
}

/**
 * 
 * Class definition for a callback to be invoked when the response for the data 
 * submission is available.
 * 
 */
public abstract class PostCallback{
    /**
     * Called when a POST success response is received. <br/>
     * This method is guaranteed to execute on the UI thread.
     */
    public abstract void onPostSuccess();

}

Note that the app doesn't use the JSON or XML (or whatever other format) returned by the REST API directly. Instead, the app only sees the bean Profile.

Then, the lower layer (AsyncTask layer) might look like this:

/**
 * An AsyncTask implementation for performing GETs on the Hypothetical REST APIs.
 */
public class GetTask extends AsyncTask<String, String, String>{
    
    private String mRestUrl;
    private RestTaskCallback mCallback;
    
    /**
     * Creates a new instance of GetTask with the specified URL and callback.
     * 
     * @param restUrl The URL for the REST API.
     * @param callback The callback to be invoked when the HTTP request
     *            completes.
     * 
     */
    public GetTask(String restUrl, RestTaskCallback callback){
        this.mRestUrl = restUrl;
        this.mCallback = callback;
    }
    
    @Override
    protected String doInBackground(String... params) {
        String response = null;
        //Use HTTP Client APIs to make the call.
        //Return the HTTP Response body here.
        return response;
    }
    
    @Override
    protected void onPostExecute(String result) {
        mCallback.onTaskComplete(result);
        super.onPostExecute(result);
    }
}

    /**
     * An AsyncTask implementation for performing POSTs on the Hypothetical REST APIs.
     */
    public class PostTask extends AsyncTask<String, String, String>{
        private String mRestUrl;
        private RestTaskCallback mCallback;
        private String mRequestBody;
        
        /**
         * Creates a new instance of PostTask with the specified URL, callback, and
         * request body.
         * 
         * @param restUrl The URL for the REST API.
         * @param callback The callback to be invoked when the HTTP request
         *            completes.
         * @param requestBody The body of the POST request.
         * 
         */
        public PostTask(String restUrl, String requestBody, RestTaskCallback callback){
            this.mRestUrl = restUrl;
            this.mRequestBody = requestBody;
            this.mCallback = callback;
        }
        
        @Override
        protected String doInBackground(String... arg0) {
            //Use HTTP client API's to do the POST
            //Return response.
        }
        
        @Override
        protected void onPostExecute(String result) {
            mCallback.onTaskComplete(result);
            super.onPostExecute(result);
        }
    }
    
    /**
     * Class definition for a callback to be invoked when the HTTP request
     * representing the REST API Call completes.
     */
    public abstract class RestTaskCallback{
        /**
         * Called when the HTTP request completes.
         * 
         * @param result The result of the HTTP request.
         */
        public abstract void onTaskComplete(String result);
    }

Here's how an app might use the API (in an Activity or Service):

HypotheticalApi myApi = HypotheticalApi.getInstance();
        myApi.getUserProfile("techie.curious", new GetResponseCallback() {

            @Override
            void onDataReceived(Profile profile) {
                //Use the profile to display it on screen, etc.
            }
            
        });
        
        Profile newProfile = new Profile();
        myApi.postUserProfile(newProfile, new PostCallback() {
            
            @Override
            public void onPostSuccess() {
                //Display Success
            }
        });

I hope the comments are sufficient to explain the design; but I'd be glad to provide more info.

What is the difference between substr and substring?

The difference is in the second argument. The second argument to substring is the index to stop at (but not include), but the second argument to substr is the maximum length to return.

Links?

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

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

Pass variable to function in jquery AJAX success callback

I'm doing it this way:

    function f(data,d){
    console.log(d);
    console.log(data);
}
$.ajax({
    url:u,
    success:function(data){ f(data,d);  }
});

Is there a developers api for craigslist.org

Craigslist does have a "bulk posting interface" which allows for multiple posts to happen at once through HTTPS POST. See:

http://www.craigslist.org/about/bulk_posting_interface

Anonymous method in Invoke call

I had problems with the other suggestions because I want to sometimes return values from my methods. If you try to use MethodInvoker with return values it doesn't seem to like it. So the solution I use is like this (very happy to hear a way to make this more succinct - I'm using c#.net 2.0):

    // Create delegates for the different return types needed.
    private delegate void VoidDelegate();
    private delegate Boolean ReturnBooleanDelegate();
    private delegate Hashtable ReturnHashtableDelegate();

    // Now use the delegates and the delegate() keyword to create 
    // an anonymous method as required

    // Here a case where there's no value returned:
    public void SetTitle(string title)
    {
        myWindow.Invoke(new VoidDelegate(delegate()
        {
            myWindow.Text = title;
        }));
    }

    // Here's an example of a value being returned
    public Hashtable CurrentlyLoadedDocs()
    {
        return (Hashtable)myWindow.Invoke(new ReturnHashtableDelegate(delegate()
        {
            return myWindow.CurrentlyLoadedDocs;
        }));
    }

Python, HTTPS GET with basic authentication

Use the power of Python and lean on one of the best libraries around: requests

import requests

r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
print(r.text)

Variable r (requests response) has a lot more parameters that you can use. Best thing is to pop into the interactive interpreter and play around with it, and/or read requests docs.

ubuntu@hostname:/home/ubuntu$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
>>> dir(r)
['__attrs__', '__bool__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'iter_content', 'iter_lines', 'json', 'links', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']
>>> r.content
b'{"battery_status":0,"margin_status":0,"timestamp_status":null,"req_status":0}'
>>> r.text
'{"battery_status":0,"margin_status":0,"timestamp_status":null,"req_status":0}'
>>> r.status_code
200
>>> r.headers
CaseInsensitiveDict({'x-powered-by': 'Express', 'content-length': '77', 'date': 'Fri, 20 May 2016 02:06:18 GMT', 'server': 'nginx/1.6.3', 'connection': 'keep-alive', 'content-type': 'application/json; charset=utf-8'})

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

After finding this StackOverflow question/answer

Complex type is getting null in a ApiController parameter

the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.

How does the keyword "use" work in PHP and can I import classes with it?

Don’t overthink what a Namespace is.

Namespace is basically just a Class prefix (like directory in Operating System) to ensure the Class path uniqueness.

Also just to make things clear, the use statement is not doing anything only aliasing your Namespaces so you can use shortcuts or include Classes with the same name but different Namespace in the same file.

E.g:

// You can do this at the top of your Class
use Symfony\Component\Debug\Debug;

if ($_SERVER['APP_DEBUG']) {
    // So you can utilize the Debug class it in an elegant way
    Debug::enable();
    // Instead of this ugly one
    // \Symfony\Component\Debug\Debug::enable();
}

If you want to know how PHP Namespaces and autoloading (the old way as well as the new way with Composer) works, you can read the blog post I just wrote on this topic: https://enterprise-level-php.com/2017/12/25/the-magic-behind-autoloading-php-files-using-composer.html

Determining if Swift dictionary contains key and obtaining any of its values

Why not simply check for dict.keys.contains(key)? Checking for dict[key] != nil will not work in cases where the value is nil. As with a dictionary [String: String?] for example.

What is the LDF file in SQL Server?

The LDF stand for 'Log database file' and it is the transaction log. It keeps a record of everything done to the database for rollback purposes, you can restore a database even you lost .msf file because it contain all control information plus transaction information .

How to do multiline shell script in Ansible

Adding a space before the EOF delimiter allows to avoid cmd:

- shell: |
    cat <<' EOF'
    This is a test.
    EOF

How to insert a file in MySQL database?

The BLOB datatype is best for storing files.

How to add image for button in android?

You should try something like this

    <Button
    android:id="@+id/imageButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/qrcode"/>

the android:background="@drawable/qrcode" will do it

Better way to cast object to int

Use Int32.TryParse as follows.

  int test;
  bool result = Int32.TryParse(value, out test);
  if (result)
  {
     Console.WriteLine("Sucess");         
  }
  else
  {
     if (value == null) value = ""; 
     Console.WriteLine("Failure");
  }

Free Rest API to retrieve current datetime as string (timezone irrelevant)

If you're using Rails, you can just make an empty file in the public folder and use ajax to get that. Then parse the headers for the Date header. Files in the Public folder bypass the Rails stack, and so have lower latency.

How to set Spinner Default by its Value instead of Position?

You can do it easily like this.

String cls=student.getStudentClass();
class_spinner.setSelection(classArray.indexOf(cls),true);

.mp4 file not playing in chrome

This started out as an attempt to cast video from my pc to a tv (with subtitles) eventually using Chromecast. And I ended up in this "does not play mp4" situation. However I seemed to have proved that Chrome will play (exactly the same) mp4 as long as it isn't wrapped in html(5) So here is what I have constructed. I have made a webpage under localhost and in there is a default.htm which contains:-

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video  controls >
 <source src="sample.mp4" type="video/mp4">
 <track kind="subtitles" src="sample.vtt" label="gcsubs" srclang="eng">
</video>
</body>
</html>

the video and subtitle files are stored in the same folder as default.htm

I have the very latest version of Chrome (just updated this morning)

When I type the appropriate localhost... into my Chrome browser a black square appears with a "GO" arrow and an elapsed time bar, a mute button and an icon which says "CC". If I hit the go arrow, nothing happens (it doesn't change to "pause", the elapsed time doesn't move, and the timer sticks at 0:00. There are no error messages - nothing!

(note that if I input localhost.. to IE11 the video plays!!!!

In Chrome if I enter the disc address of sample.mp4 (i.e. C:\webstore\sample.mp4 then Chrome will play the video fine?.

This last bit is probably a working solution for Chromecast except that I cannot see any subtitles. I really want a solution with working subtitles. I just don't understand what is different in Chrome between the two methods of playing mp4

Can we update primary key values of a table?

Short answer: yes you can. Of course you'll have to make sure that the new value doesn't match any existing value and other constraints are satisfied (duh).

What exactly are you trying to do?

How to know function return type and argument types?

Yes, you should use docstrings to make your classes and functions more friendly to other programmers:

More: http://www.python.org/dev/peps/pep-0257/#what-is-a-docstring

Some editors allow you to see docstrings while typing, so it really makes work easier.

Hive: Filtering Data between Specified Dates when Date is a String

Hive has a lot of good date parsing UDFs: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

Just doing the string comparison as Nigel Tufnel suggests is probably the easiest solution, although technically it's unsafe. But you probably don't need to worry about that unless your tables have historical data about the medieval ages (dates with only 3 year digits) or dates from scifi novels (dates with more than 4 year digits).

Anyway, if you ever find yourself in a situation where you would want to do fancier date comparisons, or if your date format is not in a "biggest to smallest" order, e.g. the American convention of "mm/dd/yyyy", then you could use unix_timestamp with two arguments:

select *
from your_table
where unix_timestamp(your_date_column, 'yyyy-MM-dd') >= unix_timestamp('2010-09-01', 'yyyy-MM-dd')
and unix_timestamp(your_date_column, 'yyyy-MM-dd') <= unix_timestamp('2013-08-31', 'yyyy-MM-dd')

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

There are Following Steps to solve this issue.


1. Go to C:\Users\ ~User Name~ \.gradle\wrapper\dists.
2. Delete all the files and folders from dists folder.
3. If Android Studio is Opened then Close any opened project and Reopen the project. The Android Studio Will automatic download all the required files.


(The required time is as per your Internet Speed (Download Size will be about "89 MB"). To see the progress of the downloading Go to C:\Users\ ~User Name~ \.gradle\wrapper\dists folder and check the size of the folder.)

jQuery - how to write 'if not equal to' (opposite of ==)

!=

For example,

if ("apple" != "orange")
  // true, the string "apple" is not equal to the string "orange"

Means not. See also the logical operators list. Also, when you see triple characters, it's a type sensitive comparison. (e.g. if (1 === '1') [not equal])

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

I was getting these errors when trying to load my test environment (via rake test or autotest) and the IRB suggestions didn't help. I ended up wrapping my entire test/test_helper.rb in a begin/rescue block and that fixed things up.

begin
  class ActiveSupport::TestCase
    #awesome stuff
  end
rescue => e
  puts e.backtrace
end

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

Create table in SQLite only if it doesn't exist already

From http://www.sqlite.org/lang_createtable.html:

CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);

Escape quotes in JavaScript

Please find in the below code which escapes the single quotes as part of the entered string using a regular expression. It validates if the user-entered string is comma-separated and at the same time it even escapes any single quote(s) entered as part of the string.

In order to escape single quotes, just enter a backward slash followed by a single quote like: \’ as part of the string. I used jQuery validator for this example, and you can use as per your convenience.

Valid String Examples:

'Hello'

'Hello', 'World'

'Hello','World'

'Hello','World',' '

'It\'s my world', 'Can\'t enjoy this without me.', 'Welcome, Guest'

HTML:

<tr>
    <td>
        <label class="control-label">
            String Field:
        </label>
        <div class="inner-addon right-addon">
            <input type="text" id="stringField"
                   name="stringField"
                   class="form-control"
                   autocomplete="off"
                   data-rule-required="true"
                   data-msg-required="Cannot be blank."
                   data-rule-commaSeparatedText="true"
                   data-msg-commaSeparatedText="Invalid comma separated value(s).">
        </div>
    </td>

JavaScript:

     /**
 *
 * @param {type} param1
 * @param {type} param2
 * @param {type} param3
 */
jQuery.validator.addMethod('commaSeparatedText', function(value, element) {

    if (value.length === 0) {
        return true;
    }
    var expression = new RegExp("^((')([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.\\-_\\[\\]\\)\\(]+([^\'\\\\]*(?:\\\\.[^\'\\\\])*)('))(((,)|(,\\s))(')([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.\\-_\\[\\]\\)\\(]+([^\'\\\\]*(?:\\\\.[^\'\\\\])*)('))*$");
    return expression.test(value);
}, 'Invalid comma separated string values.');

Can I escape a double quote in a verbatim string literal?

There is a proposal open in GitHub for the C# language about having better support for raw string literals. One valid answer, is to encourage the C# team to add a new feature to the language (such as triple quote - like Python).

see https://github.com/dotnet/csharplang/discussions/89#discussioncomment-257343

Convert row to column header for Pandas DataFrame,

You can specify the row index in the read_csv or read_html constructors via the header parameter which represents Row number(s) to use as the column names, and the start of the data. This has the advantage of automatically dropping all the preceding rows which supposedly are junk.

import pandas as pd
from io import StringIO

In[1]
    csv = '''junk1, junk2, junk3, junk4, junk5
    junk1, junk2, junk3, junk4, junk5
    pears, apples, lemons, plums, other
    40, 50, 61, 72, 85
    '''

    df = pd.read_csv(StringIO(csv), header=2)
    print(df)

Out[1]
       pears   apples   lemons   plums   other
    0     40       50       61      72      85

Git Remote: Error: fatal: protocol error: bad line length character: Unab

After loading the SSH private key in Git Extensions, this issue gets resolved.

How to view method information in Android Studio?

Android Studio 2.x.x
Moved under Editor -> General

enter image description here

Older Versions
Using windows 7 and Android Studio 1.0.x it took me a while to figure out the steps provided in the answer.
To help further visitors save some time, here is the way I did it:
Go to File -> Settings or press CTRL+ALT+S.
The following window will open and check Show quick doc on mouse move under IDE Settings -> Editor.

Show quick doc

Or just press CTRL and hover your move over your method, class ...

How to pass ArrayList of Objects from one to another activity using Intent in android?

You can use parcelable for object passing which is more efficient than Serializable .

Kindly refer the link which i am share contains complete parcelable sample. Click download ParcelableSample.zip

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

I got the same error in a project I was working with in VB.NET. Checking the "Enable application framework" on the properties page solved it for me.

Can a relative sitemap url be used in a robots.txt?

According to the official documentation on sitemaps.org it needs to be a full URL:

You can specify the location of the Sitemap using a robots.txt file. To do this, simply add the following line including the full URL to the sitemap:

Sitemap: http://www.example.com/sitemap.xml

How do I turn a python datetime into a string, with readable format date?

Here is how you can accomplish the same using python's general formatting function...

>>>from datetime import datetime
>>>"{:%B %d, %Y}".format(datetime.now())

The formatting characters used here are the same as those used by strftime. Don't miss the leading : in the format specifier.

Using format() instead of strftime() in most cases can make the code more readable, easier to write and consistent with the way formatted output is generated...

>>>"{} today's date is: {:%B %d, %Y}".format("Andre", datetime.now())

Compare the above with the following strftime() alternative...

>>>"{} today's date is {}".format("Andre", datetime.now().strftime("%B %d, %Y"))

Moreover, the following is not going to work...

>>>datetime.now().strftime("%s %B %d, %Y" % "Andre")
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    datetime.now().strftime("%s %B %d, %Y" % "Andre")
TypeError: not enough arguments for format string

And so on...

Get the list of stored procedures created and / or modified on a particular date?

SELECT name
FROM sys.objects
WHERE type = 'P'
AND (DATEDIFF(D,modify_date, GETDATE()) < 7
     OR DATEDIFF(D,create_date, GETDATE()) < 7)

Python datetime strptime() and strftime(): how to preserve the timezone information

Here is my answer in Python 2.7

Print current time with timezone

from datetime import datetime
import tzlocal  # pip install tzlocal

print datetime.now(tzlocal.get_localzone()).strftime("%Y-%m-%d %H:%M:%S %z")

Print current time with specific timezone

from datetime import datetime
import pytz # pip install pytz

print datetime.now(pytz.timezone('Asia/Taipei')).strftime("%Y-%m-%d %H:%M:%S %z")

It will print something like

2017-08-10 20:46:24 +0800

Get the content of a sharepoint folder with Excel VBA

Drive mapping to sharepoint (also https)

Getting sharepoint contents worked for me via the mapped drive iterating it as a filesystem object; trick is how to set up the mapping: from sharepoint, open as explorer Then copy path (line with http*) (see below)

address in explorer

Use this path in Map drive from explorer or command (i.e. net use N: https:://thepathyoujustcopied) Note: https works ok with windows7/8, not with XP.

That may work for you, but I prefer a different approach as drive letters are different on each pc. The trick here is to start from sharepoint (and not from a VBA script accessing sharepoint as a web server).

Set up a data connection to excel sheet

  • in sharepoint, browse to the view you want to monitor
  • export view to excel (in 2010: library tools; libarry | export to Excel) export to excel
  • when viewing this excel, you'll find a datasource set up (tab: data, connections, properties, definition)

connection tab

You can either include this query in vba, or maintain the database link in your speadsheet, iterating over the table by VBA. Please note: the image above does not show the actual database connection (command text), which would tell you how to access my sharepoint.

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

Solution for Visual Studio 2017:

Step 1: open Visual Studio cmd in administrator mode (see start menu item: Developer Command Prompt for VS 2017 - Be sure to use: Run as administrator)

Step 2: change directory to the folder where Visual Studio 2017 is installed, for example:

cd C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise

(You can copy/paste this command to your cmd prompt. For Visual Studio Professional, the folder will be called "Professional" instead of "Enterprise", etc.)

Step 3: copy/paste the below command

gacutil -if Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.Shell.Interop.8.0.dll

Hit Enter...

It will resolve the issue...

Otherwise, you can also add the following to the GAC as above:

Microsoft.VisualStudio.Shell.Interop.9.0.dll

Microsoft.VisualStudio.Shell.Interop.10.0.dll

Microsoft.VisualStudio.Shell.Interop.11.0.dll

Java: Replace all ' in a string with \'

Use replace()

 s = s.replace("'", "\\'"); 

output:

You\'ll be totally awesome, I\'m really terrible

M_PI works with math.h but not with cmath in Visual Studio

As suggested by user7860670, right-click on the project, select properties, navigate to C/C++ -> Preprocessor and add _USE_MATH_DEFINES to the Preprocessor Definitions.

That's what worked for me.

How to use ImageBackground to set background image for screen in react-native

I faced same problem with background image and its child components including logo images. After wasting few hours, I found the correct way to solve this problem. This is surely helped to you.

var {View, Text, Image, ImageBackground} = require('react-native');
import Images from '@assets';

export default class Welcome extends Component {
    render() {
        return (
            <ImageBackground source={Images.main_bg} style={styles.container}>
                <View style={styles.markWrap}>
                    <Image source={Images.main_logo} 
                    style={styles.mark} resizeMode="contain" />
                </View>
                <View style={[styles.wrapper]}>
                    {//Here put your other components}
                </View>              
                
            </ImageBackground>
        );
    }
}

var styles = StyleSheet.create({
    container:{
        flex: 1,
    },
    markWrap: {
        flex: 1,
        marginTop: 83,
        borderWidth:1, borderColor: "green"
      },
    mark: {
        width: null,
        height: null,
        flex: 1,
    },
    wrapper:{
        borderWidth:1, borderColor: "green",///for debug
        flex: 1,
        position:"relative",
    },
}

Logo on background Image

(PS: I put on the dummy image on this screen instead of real company logo.)

Get first word of string

This code should get you the first word,

var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');

 //Now i want to get the first word of every split-ed sting parts:

 for (var i=0;i<str1.length;i++)
 {
     //What to do here to get the first word :(
     var words = str1[i].split(" ");
     console.log(words[0]);
 }

Allowed characters in filename

Here is the code to clean file name in python.

import unicodedata

def clean_name(name, replace_space_with=None):
    """
    Remove invalid file name chars from the specified name

    :param name: the file name
    :param replace_space_with: if not none replace space with this string
    :return: a valid name for Win/Mac/Linux
    """

    # ref: https://en.wikipedia.org/wiki/Filename
    # ref: https://stackoverflow.com/questions/4814040/allowed-characters-in-filename
    # No control chars, no: /, \, ?, %, *, :, |, ", <, >

    # remove control chars
    name = ''.join(ch for ch in name if unicodedata.category(ch)[0] != 'C')

    cleaned_name = re.sub(r'[/\\?%*:|"<>]', '', name)
    if replace_space_with is not None:
        return cleaned_name.replace(' ', replace_space_with)
    return cleaned_name

hadoop copy a local file system folder to HDFS

If you copy a folder from local then it will copy folder with all its sub folders to HDFS.

For copying a folder from local to hdfs, you can use

hadoop fs -put localpath

or

hadoop fs -copyFromLocal localpath

or

hadoop fs -put localpath hdfspath

or

hadoop fs -copyFromLocal localpath hdfspath

Note:

If you are not specified hdfs path then folder copy will be copy to hdfs with the same name of that folder.

To copy from hdfs to local

 hadoop fs -get hdfspath localpath

Replace text inside td using jQuery having td containing other elements

Using text nodes in jquery is a particularly delicate endeavour and most operations are made to skip them altogether.

Instead of going through the trouble of carefully avoiding the wrong nodes, why not just wrap whatever you need to replace inside a <span> for instance:

<td><span class="replaceme">8: Tap on APN and Enter <B>www</B>.</span></td>

Then:

$('.replaceme').html('Whatever <b>HTML</b> you want here.');

jQuery ajax call to REST service

You are running your HTML from a different host than the host you are requesting. Because of this, you are getting blocked by the same origin policy.

One way around this is to use JSONP. This allows cross-site requests.

In JSON, you are returned:

{a: 5, b: 6}

In JSONP, the JSON is wrapped in a function call, so it becomes a script, and not an object.

callback({a: 5, b: 6})

You need to edit your REST service to accept a parameter called callback, and then to use the value of that parameter as the function name. You should also change the content-type to application/javascript.

For example: http://localhost:8080/restws/json/product/get?callback=process should output:

process({a: 5, b: 6})

In your JavaScript, you will need to tell jQuery to use JSONP. To do this, you need to append ?callback=? to the URL.

$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
   function(data) {
     alert(data);         
   });

If you use $.ajax, it will auto append the ?callback=? if you tell it to use jsonp.

$.ajax({ 
   type: "GET",
   dataType: "jsonp",
   url: "http://localhost:8080/restws/json/product/get",
   success: function(data){        
     alert(data);
   }
});

Select n random rows from SQL Server table

Try this:

SELECT TOP 10 Field1, ..., FieldN
FROM Table1
ORDER BY NEWID()

Listing all permutations of a string/integer

Here is an easy to understand permutaion function for both string and integer as input. With this you can even set your output length(which in normal case it is equal to input length)

String

    static ICollection<string> result;

    public static ICollection<string> GetAllPermutations(string str, int outputLength)
    {
        result = new List<string>();
        MakePermutations(str.ToCharArray(), string.Empty, outputLength);
        return result;
    }

    private static void MakePermutations(
       char[] possibleArray,//all chars extracted from input
       string permutation,
       int outputLength//the length of output)
    {
         if (permutation.Length < outputLength)
         {
             for (int i = 0; i < possibleArray.Length; i++)
             {
                 var tempList = possibleArray.ToList<char>();
                 tempList.RemoveAt(i);
                 MakePermutations(tempList.ToArray(), 
                      string.Concat(permutation, possibleArray[i]), outputLength);
             }
         }
         else if (!result.Contains(permutation))
            result.Add(permutation);
    }

and for Integer just change the caller method and MakePermutations() remains untouched:

    public static ICollection<int> GetAllPermutations(int input, int outputLength)
    {
        result = new List<string>();
        MakePermutations(input.ToString().ToCharArray(), string.Empty, outputLength);
        return result.Select(m => int.Parse(m)).ToList<int>();
    }

example 1: GetAllPermutations("abc",3); "abc" "acb" "bac" "bca" "cab" "cba"

example 2: GetAllPermutations("abcd",2); "ab" "ac" "ad" "ba" "bc" "bd" "ca" "cb" "cd" "da" "db" "dc"

example 3: GetAllPermutations(486,2); 48 46 84 86 64 68

How to add jQuery code into HTML Page

1) Best practice is to make new javascript file like my.js. Make this file into your js folder in root directory -> js/my.js . 2) In my.js file add your code inside of $(document).ready(function(){}) scope.

$(document).ready(function(){
    $(".icon-bg").click(function () {
        $(".btn").toggleClass("active");
        $(".icon-bg").toggleClass("active");
        $(".container").toggleClass("active");
        $(".box-upload").toggleClass("active");
        $(".box-caption").toggleClass("active");
        $(".box-tags").toggleClass("active");
        $(".private").toggleClass("active");
        $(".set-time-limit").toggleClass("active");
        $(".button").toggleClass("active");
    });

    $(".button").click(function () {
        $(".button-overlay").toggleClass("active");
    });

    $(".iconmelon").click(function () {
        $(".box-upload-ing").toggleClass("active");
        $(".iconmelon-loaded").toggleClass("active");
    });

    $(".private").click(function () {
        $(".private-overlay").addClass("active");
        $(".private-overlay-wave").addClass("active");
    });
});

3) add your new js file into your html

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="/js/my.js"></script>
</head>

How to enable GZIP compression in IIS 7.5

If anyone runs across this and is looking for a bit more up-to-date answer or copy-paste answer or answer targeting multiple versions than JC Raja's post, here's what I've found:

Google's got a pretty solid, easy-to-understand introduction to how this works and what is advantageous and not. https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/optimize-encoding-and-transfer They recommend the HTML5 Boilerplate project, which has solutions for different versions of IIS:

  • .NET version 3
  • .NET version 4
  • .NET version 4.5 / MVC 5

Available here: https://github.com/h5bp/server-configs-iis They have web.configs that you can copy and paste changes from theirs to yours and see the changes, much easier than digging through a bunch of blog posts.

Here's the web.config settings for .NET version 4.5: https://github.com/h5bp/server-configs-iis/blob/master/dotnet%204.5/MVC5/Web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <!--
            Set compilation debug="true" to insert debugging
            symbols into the compiled page. Because this
            affects performance, set this value to true only
            during development.
    -->
    <compilation debug="true" targetFramework="4.5" />

    <!-- Security through obscurity, removes  X-AspNet-Version HTTP header from the response -->
    <!-- Allow zombie DOS names to be captured by ASP.NET (/con, /com1, /lpt1, /aux, /prt, /nul, etc) -->
    <httpRuntime targetFramework="4.5" requestValidationMode="2.0" requestPathInvalidCharacters="" enableVersionHeader="false" relaxedUrlToFileSystemMapping="true" />

    <!-- httpCookies httpOnlyCookies setting defines whether cookies 
             should be exposed to client side scripts
             false (Default): client side code can access cookies
             true: client side code cannot access cookies
             Require SSL is situational, you can also define the 
             domain of cookies with optional "domain" property -->
    <httpCookies httpOnlyCookies="true" requireSSL="false" />

    <trace writeToDiagnosticsTrace="false" enabled="false" pageOutput="false" localOnly="true" />
  </system.web>


  <system.webServer>
    <!-- GZip static file content.  Overrides the server default which only compresses static files over 2700 bytes -->
    <httpCompression directory="%SystemDrive%\websites\_compressed" minFileSizeForComp="1024">
      <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
      <staticTypes>
        <add mimeType="text/*" enabled="true" />
        <add mimeType="message/*" enabled="true" />
        <add mimeType="application/javascript" enabled="true" />
        <add mimeType="application/json" enabled="true" />
        <add mimeType="*/*" enabled="false" />
      </staticTypes>
    </httpCompression>

    <httpErrors existingResponse="PassThrough" errorMode="Custom">
      <!-- Catch IIS 404 error due to paths that exist but shouldn't be served (e.g. /controllers, /global.asax) or IIS request filtering (e.g. bin, web.config, app_code, app_globalresources, app_localresources, app_webreferences, app_data, app_browsers) -->
      <remove statusCode="404" subStatusCode="-1" />
      <error statusCode="404" subStatusCode="-1" path="/notfound" responseMode="ExecuteURL" />
      <remove statusCode="500" subStatusCode="-1" />
      <error statusCode="500" subStatusCode="-1" path="/error" responseMode="ExecuteURL" />
    </httpErrors>

    <directoryBrowse enabled="false" />
    <validation validateIntegratedModeConfiguration="false" />

    <!-- Microsoft sets runAllManagedModulesForAllRequests to true by default
             You should handle this according to need but consider the performance hit.
             Good source of reference on this matter: http://www.west-wind.com/weblog/posts/2012/Oct/25/Caveats-with-the-runAllManagedModulesForAllRequests-in-IIS-78
        -->
    <modules runAllManagedModulesForAllRequests="false" />

    <urlCompression doStaticCompression="true" doDynamicCompression="true" />
    <staticContent>
      <!-- Set expire headers to 30 days for static content-->
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
      <!-- use utf-8 encoding for anything served text/plain or text/html -->
      <remove fileExtension=".css" />
      <mimeMap fileExtension=".css" mimeType="text/css" />
      <remove fileExtension=".js" />
      <mimeMap fileExtension=".js" mimeType="text/javascript" />
      <remove fileExtension=".json" />
      <mimeMap fileExtension=".json" mimeType="application/json" />
      <remove fileExtension=".rss" />
      <mimeMap fileExtension=".rss" mimeType="application/rss+xml; charset=UTF-8" />
      <remove fileExtension=".html" />
      <mimeMap fileExtension=".html" mimeType="text/html; charset=UTF-8" />
      <remove fileExtension=".xml" />
      <mimeMap fileExtension=".xml" mimeType="application/xml; charset=UTF-8" />
      <!-- HTML5 Audio/Video mime types-->
      <remove fileExtension=".mp3" />
      <mimeMap fileExtension=".mp3" mimeType="audio/mpeg" />
      <remove fileExtension=".mp4" />
      <mimeMap fileExtension=".mp4" mimeType="video/mp4" />
      <remove fileExtension=".ogg" />
      <mimeMap fileExtension=".ogg" mimeType="audio/ogg" />
      <remove fileExtension=".ogv" />
      <mimeMap fileExtension=".ogv" mimeType="video/ogg" />
      <remove fileExtension=".webm" />
      <mimeMap fileExtension=".webm" mimeType="video/webm" />
      <!-- Proper svg serving. Required for svg webfonts on iPad -->
      <remove fileExtension=".svg" />
      <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
      <remove fileExtension=".svgz" />
      <mimeMap fileExtension=".svgz" mimeType="image/svg+xml" />
      <!-- HTML4 Web font mime types -->
      <!-- Remove default IIS mime type for .eot which is application/octet-stream -->
      <remove fileExtension=".eot" />
      <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
      <remove fileExtension=".ttf" />
      <mimeMap fileExtension=".ttf" mimeType="application/x-font-ttf" />
      <remove fileExtension=".ttc" />
      <mimeMap fileExtension=".ttc" mimeType="application/x-font-ttf" />
      <remove fileExtension=".otf" />
      <mimeMap fileExtension=".otf" mimeType="font/opentype" />
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
      <remove fileExtension=".crx" />
      <mimeMap fileExtension=".crx" mimeType="application/x-chrome-extension" />
      <remove fileExtension=".xpi" />
      <mimeMap fileExtension=".xpi" mimeType="application/x-xpinstall" />
      <remove fileExtension=".safariextz" />
      <mimeMap fileExtension=".safariextz" mimeType="application/octet-stream" />
      <!-- Flash Video mime types-->
      <remove fileExtension=".flv" />
      <mimeMap fileExtension=".flv" mimeType="video/x-flv" />
      <remove fileExtension=".f4v" />
      <mimeMap fileExtension=".f4v" mimeType="video/mp4" />
      <!-- Assorted types -->
      <remove fileExtension=".ico" />
      <mimeMap fileExtension=".ico" mimeType="image/x-icon" />
      <remove fileExtension=".webp" />
      <mimeMap fileExtension=".webp" mimeType="image/webp" />
      <remove fileExtension=".htc" />
      <mimeMap fileExtension=".htc" mimeType="text/x-component" />
      <remove fileExtension=".vcf" />
      <mimeMap fileExtension=".vcf" mimeType="text/x-vcard" />
      <remove fileExtension=".torrent" />
      <mimeMap fileExtension=".torrent" mimeType="application/x-bittorrent" />
      <remove fileExtension=".cur" />
      <mimeMap fileExtension=".cur" mimeType="image/x-icon" />
      <remove fileExtension=".webapp" />
      <mimeMap fileExtension=".webapp" mimeType="application/x-web-app-manifest+json; charset=UTF-8" />
    </staticContent>
    <httpProtocol>
      <customHeaders>

        <!--#### SECURITY Related Headers ###
            More information: https://www.owasp.org/index.php/List_of_useful_HTTP_headers
        -->
        <!--
                # Access-Control-Allow-Origin
                The 'Access Control Allow Origin' HTTP header is used to control which
                sites are allowed to bypass same-origin policies and send cross-origin requests.

                Secure configuration: Either do not set this header or return the 'Access-Control-Allow-Origin'
                header restricting it to only a trusted set of sites.
                http://enable-cors.org/

                <add name="Access-Control-Allow-Origin" value="*" />
                -->

        <!--
                # Cache-Control
                The 'Cache-Control' response header controls how pages can be cached
                either by proxies or the user's browser.
                This response header can provide enhanced privacy by not caching
                sensitive pages in the user's browser cache.

                <add name="Cache-Control" value="no-store, no-cache"/>
                -->

        <!--
                # Strict-Transport-Security
                The HTTP Strict Transport Security header is used to control
                if the browser is allowed to only access a site over a secure connection
                and how long to remember the server response for, forcing continued usage.
                Note* Currently a draft standard which only Firefox and Chrome support. But is supported by sites like PayPal.
                <add name="Strict-Transport-Security" value="max-age=15768000"/>
                -->

        <!--
                # X-Frame-Options
                The X-Frame-Options header indicates whether a browser should be allowed
                to render a page within a frame or iframe.
                The valid options are DENY (deny allowing the page to exist in a frame)
                or SAMEORIGIN (allow framing but only from the originating host)
                Without this option set, the site is at a higher risk of click-jacking.

                <add name="X-Frame-Options" value="SAMEORIGIN" />
                -->

        <!--
                # X-XSS-Protection
                The X-XSS-Protection header is used by Internet Explorer version 8+
                The header instructs IE to enable its inbuilt anti-cross-site scripting filter.
                If enabled, without 'mode=block', there is an increased risk that
                otherwise, non-exploitable cross-site scripting vulnerabilities may potentially become exploitable

                <add name="X-XSS-Protection" value="1; mode=block"/>
                -->

        <!--    
                # MIME type sniffing security protection
                Enabled by default as there are very few edge cases where you wouldn't want this enabled.
                Theres additional reading below; but the tldr, it reduces the ability of the browser (mostly IE) 
                being tricked into facilitating driveby attacks.
                http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx
                http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
        -->
        <add name="X-Content-Type-Options" value="nosniff" />

        <!-- A little extra security (by obscurity), removings fun but adding your own is better -->
        <remove name="X-Powered-By" />
        <add name="X-Powered-By" value="My Little Pony" />

        <!--
                 With Content Security Policy (CSP) enabled (and a browser that supports it (http://caniuse.com/#feat=contentsecuritypolicy),
         you can tell the browser that it can only download content from the domains you explicitly allow
         CSP can be quite difficult to configure, and cause real issues if you get it wrong
         There is website that helps you generate a policy here http://cspisawesome.com/
         <add name="Content-Security-Policy" "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' https://www.google-analytics.com;" />
                -->

        <!--//#### SECURITY Related Headers ###-->

        <!--
                Force the latest IE version, in various cases when it may fall back to IE7 mode
                github.com/rails/rails/commit/123eb25#commitcomment-118920
                Use ChromeFrame if it's installed for a better experience for the poor IE folk
                -->
        <add name="X-UA-Compatible" value="IE=Edge,chrome=1" />
        <!--
                Allow cookies to be set from iframes (for IE only)
                If needed, uncomment and specify a path or regex in the Location directive

                <add name="P3P" value="policyref=&quot;/w3c/p3p.xml&quot;, CP=&quot;IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT&quot;" />
                -->

      </customHeaders>
    </httpProtocol>

    <!--
        <rewrite>
            <rules>

            Remove/force the WWW from the URL.
            Requires IIS Rewrite module http://learn.iis.net/page.aspx/460/using-the-url-rewrite-module/
            Configuration lifted from http://nayyeri.net/remove-www-prefix-from-urls-with-url-rewrite-module-for-iis-7-0

            NOTE* You need to install the IIS URL Rewriting extension (Install via the Web Platform Installer)
            http://www.microsoft.com/web/downloads/platform.aspx

            ** Important Note
            using a non-www version of a webpage will set cookies for the whole domain making cookieless domains
            (eg. fast CD-like access to static resources like CSS, js, and images) impossible.

            # IMPORTANT: THERE ARE TWO RULES LISTED. NEVER USE BOTH RULES AT THE SAME TIME!

                <rule name="Remove WWW" stopProcessing="true">
                    <match url="^(.*)$" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
                    </conditions>
                    <action type="Redirect" url="http://example.com{PATH_INFO}" redirectType="Permanent" />
                </rule>
                <rule name="Force WWW" stopProcessing="true">
                    <match url=".*" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^example.com$" />
                    </conditions>
                    <action type="Redirect" url="http://www.example.com/{R:0}" redirectType="Permanent" />
                </rule>


                # E-TAGS
                E-Tags are actually quite useful in cache management especially if you have a front-end caching server such as Varnish. http://en.wikipedia.org/wiki/HTTP_ETag / http://developer.yahoo.com/performance/rules.html#etags
                But in load balancing and simply most cases ETags are mishandled in IIS, and it can be advantageous to remove them.
        # removed as in https://stackoverflow.com/questions/7947420/iis-7-5-remove-etag-headers-from-response

        <rewrite>
           <outboundRules>
              <rule name="Remove ETag">
                 <match serverVariable="RESPONSE_ETag" pattern=".+" />
                 <action type="Rewrite" value="" />
              </rule>
           </outboundRules>
        </rewrite>

            -->
    <!--
            ### Built-in filename-based cache busting

            In a managed language such as .net, you should really be using the internal bundler for CSS + js
            or get cassette or similar.

            If you're not using the build script to manage your filename version revving,
            you might want to consider enabling this, which will route requests for
            /css/style.20110203.css to /css/style.css

            To understand why this is important and a better idea than all.css?v1231,
            read: github.com/h5bp/html5-boilerplate/wiki/Version-Control-with-Cachebusting

                <rule name="Cachebusting">
                    <match url="^(.+)\.\d+(\.(js|css|png|jpg|gif)$)" />
                    <action type="Rewrite" url="{R:1}{R:2}" />
                </rule>

            </rules>
        </rewrite>-->

  </system.webServer>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Edit: One update if you need Gzip compression on WebAPI responses. I wasn't aware our WebAPI wasn't returning Gzipped responses until recently and scratched my head for a while because we had dynamic and static compression turned on in web.config. We looked at writing our own compression services and response handlers (still on WebAPI 2 not on .NET Core where it's easier now), but that was too cumbersome for what seemed like something we should just be able to turn on.

(If you're interested here's what we were looking at for our own compression service https://krzysztofjakielaszek.com/2017/03/26/webapi2-response-compression-gzip-brotli-deflate/ EDIT: Link is now offline, but you can view the code/content here: https://web.archive.org/web/20190608161201/https://krzysztofjakielaszek.com/2017/03/26/webapi2-response-compression-gzip-brotli-deflate/ )

Instead, we found this great post by Ben Foster (http://benfoster.io/blog/aspnet-web-api-compression) If you can modify applicationHost.config (running your own servers), you can pop that config file open and add the mimeTypes you want to compress (I pulled the relevant ones based on what our API was returning to clients from our Web.Config). Save that file, IIS will pickup your changes, recycle app pools, and your WebAPI will start returning gzip compressed responses to clients who request it.

If you don't see gzipped responses, check the response content type with Fiddler or Chrome/Firefox Dev Tools, and ensure it matches what you added. I had to change the view mode (use large request rows) in Chrome Dev Tools to ensure it showed the total size vs transferred size. If everything validates, try rebooting the server once to just ensure it was properly applied. I did have one syntax error where when I opened up the site in IIS, IIS poppped open a message about a parsing error that I had to fix in the config file.

<httpCompression directory="%TEMP%\iisexpress\IIS Temporary Compressed Files">
    <scheme name="gzip" dll="%IIS_BIN%\gzip.dll" />
    <dynamicTypes>
        ...

        <!-- compress JSON responses from Web API -->           
        <add mimeType="application/json" enabled="true" /> 

        ...
    </dynamicTypes>
    <staticTypes>
        ...
    </staticTypes>
</httpCompression>

How can I selectively escape percent (%) in Python strings?

You can't selectively escape %, as % always has a special meaning depending on the following character.

In the documentation of Python, at the bottem of the second table in that section, it states:

'%'        No argument is converted, results in a '%' character in the result.

Therefore you should use:

selectiveEscape = "Print percent %% in sentence and not %s" % (test, )

(please note the expicit change to tuple as argument to %)

Without knowing about the above, I would have done:

selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)

with the knowledge you obviously already had.

How to set a cookie to expire in 1 hour in Javascript?

You can write this in a more compact way:

var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000);
document.cookie = "name=value; expires=" + now.toUTCString() + "; path=/";

And for someone like me, who wasted an hour trying to figure out why the cookie with expiration is not set up (but without expiration can be set up) in Chrome, here is in answer:

For some strange reason Chrome team decided to ignore cookies from local pages. So if you do this on localhost, you will not be able to see your cookie in Chrome. So either upload it on the server or use another browser.

How do I add a submodule to a sub-directory?

For those of you who share my weird fondness of manually editing config files, adding (or modifying) the following would also do the trick.

.git/config (personal config)

[submodule "cookbooks/apt"]
    url = https://github.com/opscode-cookbooks/apt

.gitmodules (committed shared config)

[submodule "cookbooks/apt"]
    path = cookbooks/apt
    url = https://github.com/opscode-cookbooks/apt

See this as well - difference between .gitmodules and specifying submodules in .git/config?

Capitalize or change case of an NSString in Objective-C

In case anyone needed the above in swift :

SWIFT 3.0 and above :

this will capitalize your string, make the first letter capital :

viewNoteDateMonth.text  = yourString.capitalized

this will uppercase your string, make all the string upper case :

viewNoteDateMonth.text  = yourString.uppercased()

How to comment in Vim's config files: ".vimrc"?

A double quote to the left of the text you want to comment.

Example: " this is how a comment looks like in ~/.vimrc

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

This Proxy will expose the buffer as any of the TypedArrays, without any copy. :

https://www.npmjs.com/package/node-buffer-as-typedarray

It only works on LE, but can be easily ported to BE. Also, never got to actually test how efficient this is.

Using $setValidity inside a Controller

A better and optimised solution to display multiple validation messages for a single element would be like this.

<div ng-messages="myForm.file.$error" ng-show="myForm.file.$touched">
 <span class="error" ng-message="required"> <your message> </span>
 <span class="error" ng-message="size"> <your message> </span>
 <span class="error" ng-message="filetype"> <your message> </span>
</div>

Controller Code should be the one suggested by @ Ben Lesh

Fuzzy matching using T-SQL

Pasting RedFilter code in two parts ,so as to avoid link rot

References:
https://github.com/mb16/geocoderNet/blob/master/build/sql/doubleMetaphone.sql Part1:

--WEB LISTING 1: Double Metaphone Script

-------------------------------------
IF OBJECT_ID('fnIsVowel') IS NOT NULL BEGIN DROP FUNCTION fnIsVowel END
GO;
CREATE FUNCTION fnIsVowel( @c char(1) )
RETURNS bit
AS
BEGIN
    IF (@c = 'A') OR (@c = 'E') OR (@c = 'I') OR (@c = 'O') OR (@c = 'U') OR (@c = 'Y') 
    BEGIN
        RETURN 1
    END
    --'ELSE' would worry SQL Server, it wants RETURN last in a scalar function
    RETURN 0
END
GO;
-----------------------------------------------
IF OBJECT_ID('fnSlavoGermanic') IS NOT NULL BEGIN DROP FUNCTION fnSlavoGermanic 
END
GO;
CREATE FUNCTION fnSlavoGermanic( @Word char(50) )
RETURNS bit
AS
BEGIN
    --Catch NULL also...
    IF (CHARINDEX('W',@Word) > 0) OR (CHARINDEX('K',@Word) > 0) OR 
(CHARINDEX('CZ',@Word) > 0)
    --'WITZ' test is in original Lawrence Philips C++ code, but appears to be a subset of the first test for 'W'
    -- OR (CHARINDEX('WITZ',@Word) > 0)
    BEGIN
        RETURN 1
    END
    --ELSE
        RETURN 0
END
GO;
---------------------------------------------------------------------------------------------------------------------------------
----------------------
--Lawrence Philips calls for a length argument, but this has two drawbacks:
--1. All target strings must be of the same length
--2. It presents an opportunity for subtle bugs, ie fnStringAt( 1, 7, 'Search me please', 'Search' ) returns 0 (no matter what is in the searched string)
--So I've eliminated the argument and fnStringAt checks the length of each target as it executes

--DEFAULTS suck with UDFs. Have to specify DEFAULT in caller - why bother?
IF OBJECT_ID('fnStringAtDef') IS NOT NULL BEGIN DROP FUNCTION fnStringAtDef END
GO;
CREATE FUNCTION fnStringAtDef( @Start int, @StringToSearch varchar(50), 
    @Target1 varchar(50), 
    @Target2 varchar(50) = NULL,
    @Target3 varchar(50) = NULL,
    @Target4 varchar(50) = NULL,
    @Target5 varchar(50) = NULL,
    @Target6 varchar(50) = NULL )
RETURNS bit
AS
BEGIN
    IF CHARINDEX(@Target1,@StringToSearch,@Start) > 0 RETURN 1
    --2 Styles, test each optional argument for NULL, nesting further tests
    --or just take advantage of CHARINDEX behavior with a NULL arg (unless 65 compatibility - code check before CREATE FUNCTION?
    --Style 1:
    --IF @Target2 IS NOT NULL
    --BEGIN
    --  IF CHARINDEX(@Target2,@StringToSearch,@Start) > 0 RETURN 1
    -- (etc.)
    --END
    --Style 2:
    IF CHARINDEX(@Target2,@StringToSearch,@Start) > 0 RETURN 1
    IF CHARINDEX(@Target3,@StringToSearch,@Start) > 0 RETURN 1
    IF CHARINDEX(@Target4,@StringToSearch,@Start) > 0 RETURN 1
    IF CHARINDEX(@Target5,@StringToSearch,@Start) > 0 RETURN 1
    IF CHARINDEX(@Target6,@StringToSearch,@Start) > 0 RETURN 1
    RETURN 0
END
GO;
-------------------------------------------------------------------------------------------------
IF OBJECT_ID('fnStringAt') IS NOT NULL BEGIN DROP FUNCTION fnStringAt END
GO;
CREATE FUNCTION fnStringAt( @Start int, @StringToSearch varchar(50), @TargetStrings 
varchar(2000) )
RETURNS bit
AS
BEGIN
    DECLARE @SingleTarget varchar(50)
    DECLARE @CurrentStart int
    DECLARE @CurrentLength int

    --Eliminate special cases
    --Trailing space is needed to check for end of word in some cases, so always append comma
    --loop tests should fairly quickly ignore ',,' termination
    SET @TargetStrings = @TargetStrings + ','

    SET @CurrentStart = 1
    --Include terminating comma so spaces don't get truncated
    SET @CurrentLength = (CHARINDEX(',',@TargetStrings,@CurrentStart) - 
@CurrentStart) + 1
    SET @SingleTarget = SUBSTRING(@TargetStrings,@CurrentStart,@CurrentLength)
    WHILE LEN(@SingleTarget) > 1
    BEGIN
        IF SUBSTRING(@StringToSearch,@Start,LEN(@SingleTarget)-1) = 
LEFT(@SingleTarget,LEN(@SingleTarget)-1)
        BEGIN
            RETURN 1
        END
        SET @CurrentStart = (@CurrentStart + @CurrentLength)
        SET @CurrentLength = (CHARINDEX(',',@TargetStrings,@CurrentStart) - 
@CurrentStart) + 1
        IF NOT @CurrentLength > 1 --getting trailing comma 
        BEGIN
            BREAK
        END
        SET @SingleTarget = 
SUBSTRING(@TargetStrings,@CurrentStart,@CurrentLength)
    END
    RETURN 0
END
GO;
------------------------------------------------------------------------
IF OBJECT_ID('fnDoubleMetaphoneTable') IS NOT NULL BEGIN DROP FUNCTION 
fnDoubleMetaphoneTable END
GO;
CREATE FUNCTION fnDoubleMetaphoneTable( @Word varchar(50) )
RETURNS @DMP TABLE ( Metaphone1 char(4), Metaphone2 char(4) )
AS
BEGIN
    DECLARE @MP1 varchar(4), @MP2 varchar(4)
    SET @MP1 = ''
    SET @MP2 = ''
    DECLARE @CurrentPosition int, @WordLength int, @CurrentChar char(1)
    SET @CurrentPosition = 1
    SET @WordLength = LEN(@Word)

    IF @WordLength < 1 
    BEGIN
        RETURN
    END

    --ensure case insensitivity
    SET @Word = UPPER(@Word)

    IF dbo.fnStringAt(1, @Word, 'GN,KN,PN,WR,PS') = 1 
    BEGIN
        SET @CurrentPosition = @CurrentPosition + 1
    END

    IF 'X' = LEFT(@Word,1)
    BEGIN
        SET @MP1 = @MP1 + 'S'
        SET @MP2 = @MP2 + 'S'
        SET @CurrentPosition = @CurrentPosition + 1
    END

    WHILE (4 > LEN(RTRIM(@MP1))) OR (4 > LEN(RTRIM(@MP2)))
    BEGIN
        IF @CurrentPosition > @WordLength 
        BEGIN
            BREAK
        END

        SET @CurrentChar = SUBSTRING(@Word,@CurrentPosition,1)

        IF @CurrentChar IN('A','E','I','O','U','Y')
        BEGIN
            IF @CurrentPosition = 1 
            BEGIN
                SET @MP1 = @MP1 + 'A'
                SET @MP2 = @MP2 + 'A'
            END
            SET @CurrentPosition = @CurrentPosition + 1
        END
        ELSE IF @CurrentChar = 'B'
        BEGIN
            SET @MP1 = @MP1 + 'P'
            SET @MP2 = @MP2 + 'P'
            IF 'B' = SUBSTRING(@Word,@CurrentPosition + 1,1) 
            BEGIN
                SET @CurrentPosition = @CurrentPosition + 2
            END
            ELSE 
            BEGIN
                SET @CurrentPosition = @CurrentPosition + 1
            END
        END
        ELSE IF @CurrentChar = 'Ç'
        BEGIN
            SET @MP1 = @MP1 + 'S'
            SET @MP2 = @MP2 + 'S'
            SET @CurrentPosition = @CurrentPosition + 1
        END
        ELSE IF @CurrentChar = 'C'
        BEGIN
            --various germanic
            IF (@CurrentPosition > 2) 
               AND (dbo.fnIsVowel(SUBSTRING(@Word,@CurrentPosition-2,1))=0) 
               AND (dbo.fnStringAt(@CurrentPosition-1,@Word,'ACH') = 1) 
               AND ((SUBSTRING(@Word,@CurrentPosition+2,1) <> 'I') 
                AND ((SUBSTRING(@Word,@CurrentPosition+2,1) <> 'E') OR 
(dbo.fnStringAt(@CurrentPosition-2,@Word,'BACHER,MACHER')=1)))
            BEGIN
                SET @MP1 = @MP1 + 'K'
                SET @MP2 = @MP2 + 'K'
                SET @CurrentPosition = @CurrentPosition + 2
            END
            -- 'caesar'
            ELSE IF (@CurrentPosition = 1) AND 
(dbo.fnStringAt(@CurrentPosition,@Word,'CAESAR') = 1)
            BEGIN
                SET @MP1 = @MP1 + 'S'
                SET @MP2 = @MP2 + 'S'
                SET @CurrentPosition = @CurrentPosition + 2
            END
            -- 'chianti'
            ELSE IF dbo.fnStringAt(@CurrentPosition,@Word,'CHIA') = 1
            BEGIN
                SET @MP1 = @MP1 + 'K'
                SET @MP2 = @MP2 + 'K'
                SET @CurrentPosition = @CurrentPosition + 2
            END
            ELSE IF dbo.fnStringAt(@CurrentPosition,@Word,'CH') = 1
            BEGIN
                -- Find 'michael'
                IF (@CurrentPosition > 1) AND 
(dbo.fnStringAt(@CurrentPosition,@Word,'CHAE') = 1)
                BEGIN
                    --First instance of alternate encoding
                    SET @MP1 = @MP1 + 'K'
                    SET @MP2 = @MP2 + 'X'
                    SET @CurrentPosition = @CurrentPosition + 2
                END
                --greek roots e.g. 'chemistry', 'chorus'
                ELSE IF (@CurrentPosition = 1) AND (dbo.fnStringAt(2, @Word, 
'HARAC,HARIS,HOR,HYM,HIA,HEM') = 1) AND (dbo.fnStringAt(1,@Word,'CHORE') = 0)
                BEGIN
                    SET @MP1 = @MP1 + 'K'
                    SET @MP2 = @MP2 + 'K'
                    SET @CurrentPosition = @CurrentPosition + 2
                END
                --germanic, greek, or otherwise 'ch' for 'kh' sound
                ELSE IF ((dbo.fnStringAt(1,@Word,'VAN ,VON ,SCH')=1) OR 
                   (dbo.fnStringAt(@CurrentPosition-
2,@Word,'ORCHES,ARCHIT,ORCHID')=1) OR 
                   (dbo.fnStringAt(@CurrentPosition+2,@Word,'T,S')=1) OR 
                   (((dbo.fnStringAt(@CurrentPosition-1,@Word,'A,O,U,E')=1) 
OR 
                   (@CurrentPosition = 1))  
                   AND 
(dbo.fnStringAt(@CurrentPosition+2,@Word,'L,R,N,M,B,H,F,V,W, ')=1)))
                BEGIN
                    SET @MP1 = @MP1 + 'K'
                    SET @MP2 = @MP2 + 'K'
                    SET @CurrentPosition = @CurrentPosition + 2
                END
                ELSE
                BEGIN
                    --is this a given?
                    IF (@CurrentPosition > 1)   
                    BEGIN
                        IF (dbo.fnStringAt(1,@Word,'MC') = 1)
                        BEGIN
                            --eg McHugh
                            SET @MP1 = @MP1 + 'K'
                            SET @MP2 = @MP2 + 'K'
                        END
                        ELSE
                        BEGIN
                            --Alternate encoding
                            SET @MP1 = @MP1 + 'X'
                            SET @MP2 = @MP2 + 'K'
                        END
                    END
                    ELSE
                    BEGIN
                        SET @MP1 = @MP1 + 'X'
                        SET @MP2 = @MP2 + 'X'
                    END
                    SET @CurrentPosition = @CurrentPosition + 2
                END
            END
                    --e.g, 'czerny'
                    ELSE IF (dbo.fnStringAt(@CurrentPosition,@Word,'CZ')=1) AND 
(dbo.fnStringAt((@CurrentPosition - 2),@Word,'WICZ')=0)
                    BEGIN
                SET @MP1 = @MP1 + 'S'
                SET @MP2 = @MP2 + 'X'
                            SET @CurrentPosition = @CurrentPosition + 2
                    END

                    --e.g., 'focaccia'
                    ELSE IF(dbo.fnStringAt((@CurrentPosition + 1),@Word,'CIA')=1)
                    BEGIN
                SET @MP1 = @MP1 + 'X'
                SET @MP2 = @MP2 + 'X'
                            SET @CurrentPosition = @CurrentPosition + 3
                    END

                    --double 'C', but not if e.g. 'McClellan'
                    ELSE IF(dbo.fnStringAt(@CurrentPosition,@Word,'CC')=1) AND NOT 
((@CurrentPosition = 2) AND (LEFT(@Word,1) = 'M'))
                            --'bellocchio' but not 'bacchus'
                            IF (dbo.fnStringAt((@CurrentPosition + 2),@Word,'I,E,H')=1) AND 
(dbo.fnStringAt((@CurrentPosition + 2),@Word,'HU')=0)
                            BEGIN
                                    --'accident', 'accede' 'succeed'
                                    IF (((@CurrentPosition = 2) AND 
(SUBSTRING(@Word,@CurrentPosition - 1,1) = 'A')) 
                                                    OR (dbo.fnStringAt((@CurrentPosition - 
1),@Word,'UCCEE,UCCES')=1))
                    BEGIN
                        SET @MP1 = @MP1 + 'KS'
                        SET @MP2 = @MP2 + 'KS'
                    END
                                    --'bacci', 'bertucci', other italian
                                    ELSE
                    BEGIN
                        SET @MP1 = @MP1 + 'X'
                        SET @MP2 = @MP2 + 'X'
                    END
                                SET @CurrentPosition = @CurrentPosition + 3
                END
                            --Pierce's rule
                            ELSE 
                BEGIN
                    SET @MP1 = @MP1 + 'K'
                    SET @MP2 = @MP2 + 'K'
                                SET @CurrentPosition = @CurrentPosition + 2
                            END

                    ELSE IF (dbo.fnStringAt(@CurrentPosition,@Word,'CK,CG,CQ')=1)
                    BEGIN
                SET @MP1 = @MP1 + 'K'
                SET @MP2 = @MP2 + 'K'
                            SET @CurrentPosition = @CurrentPosition + 2
                    END

                    ELSE IF (dbo.fnStringAt(@CurrentPosition,@Word,'CI,CE,CY')=1)
                    BEGIN
                            --italian vs. english
                            IF (dbo.fnStringAt(@CurrentPosition,@Word,'CIO,CIE,CIA')=1)
                BEGIN
                    SET @MP1 = @MP1 + 'S'
                    SET @MP2 = @MP2 + 'X'
                END
                            ELSE
                BEGIN
                    SET @MP1 = @MP1 + 'S'
                    SET @MP2 = @MP2 + 'S'
                END
                            SET @CurrentPosition = @CurrentPosition + 2
                    END

                    ELSE
            BEGIN
                SET @MP1 = @MP1 + 'K'
                SET @MP2 = @MP2 + 'K'

                        --name sent in 'mac caffrey', 'mac gregor
                        IF (dbo.fnStringAt((@CurrentPosition + 1),@Word,' C, Q, G')=1)
                BEGIN
                                SET @CurrentPosition = @CurrentPosition + 3
                END
                        ELSE
                BEGIN
                                IF (dbo.fnStringAt((@CurrentPosition + 1),@Word,'C,K,Q')=1)
                                        AND (dbo.fnStringAt((@CurrentPosition + 1), 2, 'CE,CI')=0)
                    BEGIN
                                    SET @CurrentPosition = @CurrentPosition + 2
                    END
                                ELSE
                    BEGIN
                                    SET @CurrentPosition = @CurrentPosition + 1
                    END
                        END
            END

        END
        ELSE IF @CurrentChar = 'D'
        BEGIN
                    IF (dbo.fnStringAt(@CurrentPosition, @Word, 'DG')=1)
            BEGIN
                            IF (dbo.fnStringAt((@CurrentPosition + 2),@Word,'I,E,Y')=1)
                            BEGIN
                                    --e.g. 'edge'
                    SET @MP1 = @MP1 + 'J'
                    SET @MP2 = @MP2 + 'J'
                                SET @CurrentPosition = @CurrentPosition + 3
                            END
                            ELSE
                BEGIN
                                    --e.g. 'edgar'
                    SET @MP1 = @MP1 + 'TK'
                    SET @MP2 = @MP2 + 'TK'
                                SET @CurrentPosition = @CurrentPosition + 2
                            END
            END
                    ELSE IF (dbo.fnStringAt(@CurrentPosition,@Word,'DT,DD')=1)
                    BEGIN
                SET @MP1 = @MP1 + 'T'
                SET @MP2 = @MP2 + 'T'
                            SET @CurrentPosition = @CurrentPosition + 2
                    END
                    ELSE
            BEGIN
                SET @MP1 = @MP1 + 'T'
                SET @MP2 = @MP2 + 'T'
                            SET @CurrentPosition = @CurrentPosition + 1
            END
        END

        ELSE IF @CurrentChar = 'F'
        BEGIN
                    IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'F')
            BEGIN
                            SET @CurrentPosition = @CurrentPosition + 2
            END
                    ELSE
            BEGIN
                            SET @CurrentPosition = @CurrentPosition + 1
            END
            SET @MP1 = @MP1 + 'F'
            SET @MP2 = @MP2 + 'F'
        END

        ELSE IF @CurrentChar = 'G'
        BEGIN
                    IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'H')
                    BEGIN
                            IF (@CurrentPosition > 1) AND 
(dbo.fnIsVowel(SUBSTRING(@Word,@CurrentPosition - 1,1)) = 0)
                            BEGIN
                    SET @MP1 = @MP1 + 'K'
                    SET @MP2 = @MP2 + 'K'
                                SET @CurrentPosition = @CurrentPosition + 2
                            END
                                --'ghislane', ghiradelli
                                ELSE IF (@CurrentPosition = 1)
                                BEGIN 
                                        IF (SUBSTRING(@Word,@CurrentPosition + 2,1) = 'I')
                    BEGIN
                        SET @MP1 = @MP1 + 'J'
                        SET @MP2 = @MP2 + 'J'
                    END
                                        ELSE
                    BEGIN
                        SET @MP1 = @MP1 + 'K'
                        SET @MP2 = @MP2 + 'K'
                    END
                                SET @CurrentPosition = @CurrentPosition + 2
                            END
                            --Parker's rule (with some further refinements) - e.g., 'hugh'
                            ELSE IF (((@CurrentPosition > 2) AND (dbo.fnStringAt((@CurrentPosition 
- 2),@Word,'B,H,D')=1) )
                                    --e.g., 'bough'
                                    OR ((@CurrentPosition > 3) AND (dbo.fnStringAt((@CurrentPosition 
- 3),@Word,'B,H,D')=1) )
                                    --e.g., 'broughton'
                                    OR ((@CurrentPosition > 4) AND (dbo.fnStringAt((@CurrentPosition 
- 4),@Word,'B,H')=1) ) )
                            BEGIN
                                SET @CurrentPosition = @CurrentPosition + 2
                END
                            ELSE
                BEGIN
                                    --e.g., 'laugh', 'McLaughlin', 'cough', 'gough', 'rough', 'tough'
                                    IF ((@CurrentPosition > 3) 
                                            AND (SUBSTRING(@Word,@CurrentPosition - 1,1) = 'U') 
                                            AND (dbo.fnStringAt((@CurrentPosition - 
3),@Word,'C,G,L,R,T')=1) )
                                    BEGIN
                        SET @MP1 = @MP1 + 'F'
                        SET @MP2 = @MP2 + 'F'
                    END
                                    ELSE
                    BEGIN
                                            IF ((@CurrentPosition > 1) AND 
SUBSTRING(@Word,@CurrentPosition - 1,1) <> 'I')
                        BEGIN
                            SET @MP1 = @MP1 + 'K'
                            SET @MP2 = @MP2 + 'K'
                        END
                    END

                                SET @CurrentPosition = @CurrentPosition + 2
                            END
                    END

                    ELSE IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'N')
                    BEGIN
                            IF ((@CurrentPosition = 2) AND (dbo.fnIsVowel(LEFT(@Word,1))=1) AND 
(dbo.fnSlavoGermanic(@Word)=0))
                            BEGIN
                    SET @MP1 = @MP1 + 'KN'
                    SET @MP2 = @MP2 + 'N'
                END
                            ELSE
                BEGIN
                                    --not e.g. 'cagney'
                                    IF ((dbo.fnStringAt((@CurrentPosition + 2),@Word,'EY')=0) 
                                                    AND (SUBSTRING(@Word,@CurrentPosition + 1,1) <> 
'Y') AND (dbo.fnSlavoGermanic(@Word)=0))

Inserting Image Into BLOB Oracle 10g

You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.

If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:

enter image description here

SQL Developer has a similar feature. See the "Load" link below:

enter image description here

If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.

Assuming ACL is complete, you'd pull the image like this:

declare
    l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
    l_http_request   UTL_HTTP.req;
    l_http_response  UTL_HTTP.resp;
    l_raw RAW(2000);
    l_blob BLOB;
begin
   -- Important: setup ACL access list first!

    DBMS_LOB.createtemporary(l_blob, FALSE);

    l_http_request  := UTL_HTTP.begin_request(l_url);
    l_http_response := UTL_HTTP.get_response(l_http_request);

  -- Copy the response into the BLOB.
  BEGIN
    LOOP
      UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
      DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
    END LOOP;
  EXCEPTION
    WHEN UTL_HTTP.end_of_body THEN
      UTL_HTTP.end_response(l_http_response);
  END;

  insert into my_pics (pic_id, pic) values (102, l_blob);
  commit;

  DBMS_LOB.freetemporary(l_blob); 
end;

Hope that helps.

Setting timezone in Python

>>> import os, time
>>> time.strftime('%X %x %Z')
'12:45:20 08/19/09 CDT'
>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()
>>> time.strftime('%X %x %Z')
'18:45:39 08/19/09 BST'

To get the specific values you've listed:

>>> year = time.strftime('%Y')
>>> month = time.strftime('%m')
>>> day = time.strftime('%d')
>>> hour = time.strftime('%H')
>>> minute = time.strftime('%M')

See here for a complete list of directives. Keep in mind that the strftime() function will always return a string, not an integer or other type.

Prevent linebreak after </div>

display:inline;

OR

float:left;

OR

display:inline-block; -- Might not work on all browsers.

What is the purpose of using a div here? I'd suggest a span, as it is an inline-level element, whereas a div is a block-level element.


Do note that each option above will work differently.

display:inline; will turn the div into the equivalent of a span. It will be unaffected by margin-top, margin-bottom, padding-top, padding-bottom, height, etc.

float:left; keeps the div as a block-level element. It will still take up space as if it were a block, however the width will be fitted to the content (assuming width:auto;). It can require a clear:left; for certain effects.

display:inline-block; is the "best of both worlds" option. The div is treated as a block element. It responds to all of the margin, padding, and height rules as expected for a block element. However, it is treated as an inline element for the purpose of placement within other elements.

Read this for more information.

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

This is how use SignarR in order to target a specific user (without using any provider):

 private static ConcurrentDictionary<string, string> clients = new ConcurrentDictionary<string, string>();

 public string Login(string username)
 {
     clients.TryAdd(Context.ConnectionId, username);            
     return username;
 }

// The variable 'contextIdClient' is equal to Context.ConnectionId of the user, 
// once logged in. You have to store that 'id' inside a dictionaty for example.  
Clients.Client(contextIdClient).send("Hello!");

How to change the Text color of Menu item in Android?

Adding this into my styles.xml worked for me

<item name="android:textColorPrimary">?android:attr/textColorPrimaryInverse</item>

Xcode error "Could not find Developer Disk Image"

If you're using old Xcode and want to run onto devices with new version of iOS, then do this trick. This basically make a symbolic link from iOS Device Support in new Xcode to old Xcode

https://gist.github.com/steipete/d9b44d8e9f341e81414e86d7ff8fb62d

For Xcode 9.0 beta and iOS 11.0 beta (name your Xcode9.app for Xcode 9 beta and Xcode.app for Xcode 8)

sudo ln -s "/Applications/Xcode9.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.0\ \(15A5278f\)" "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport"

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

In my case, we had several projects in one solution and had selected a different start project than in the package manager console when running the "Update-Database" Command with Code-First Migrations. Make sure to select the proper start project.

MySQL "NOT IN" query

To use IN, you must have a set, use this syntax instead:

SELECT * FROM Table1 WHERE Table1.principal NOT IN (SELECT principal FROM table2)

How can I show current location on a Google Map on Android Marshmallow?

Sorry but that's just much too much overhead (above), short and quick, if you have the MapFragment, you also have to map, just do the following:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            googleMap.setMyLocationEnabled(true)
} else {
    // Show rationale and request permission.
}

Code is in Kotlin, hope you don't mind.

have fun

Btw I think this one is a duplicate of: Show Current Location inside Google Map Fragment

npm global path prefix

Spent a while on this issue, and the PATH switch wasn't helping. My problem was the Homebrew/node/npm bug found here - https://github.com/npm/npm/issues/3794

If you've already installed node using Homebrew, try ****Note per comments that this might not be safe. It worked for me but could have unintended consequences. It also appears that latest version of Homebrew properly installs npm. So likely I would try brew update, brew doctor, brew upgrade node etc before trying****:

npm update -gf

Or, if you want to install node with Homebrew and have npm work, use:

brew install node --without-npm
curl -L https://npmjs.org/install.sh | sh

Sublime Text 3, convert spaces to tabs

On the bottom right-hand corner of your Sublime Text window, you'll see an indentation indicator that looks a lot like this:

Indentation options menu

Clicking it will open a menu with options to adjust your indentation preferences, and more importantly, Convert Indentation to Tabs/Spaces.

enter image description here

The same menu is listed under View -> Indentation.

CSV new-line character seen in unquoted field error

Alternative and fast solution : I faced the same error. I reopened the "wierd" csv file in GNUMERIC on my lubuntu machine and exported the file as csv file. This corrected the issue.

Datetime current year and month in Python

>>> from datetime import date
>>> date.today().month
2
>>> date.today().year
2020
>>> date.today().day
13

How can I import Swift code to Objective-C?

#import <TargetName-Swift.h>

you will see when you enter from keyboard #import < and after automaticly Xcode will advice to you.

How to undo a SQL Server UPDATE query?

Since you have a FULL backup, you can restore the backup to a different server as a database of the same name or to the same server with a different name.

Then you can just review the contents pre-update and write a SQL script to do the update.

Display Bootstrap Modal using javascript onClick

I was looking for the onClick option to set the title and body of the modal based on the item in a list. T145's answer helped a lot, so I wanted to share how I used it.

Make sure the tag containing the JavaScript function is of type text/javascript to avoid conflicts:

<script type="text/javascript"> function showMyModalSetTitle(myTitle, myBodyHtml) {

   /*
    * '#myModayTitle' and '#myModalBody' refer to the 'id' of the HTML tags in
    * the modal HTML code that hold the title and body respectively. These id's
    * can be named anything, just make sure they are added as necessary.
    *
    */

   $('#myModalTitle').html(myTitle);
   $('#myModalBody').html(myBodyHtml);

   $('#myModal').modal('show');
}</script>

This function can now be called in the onClick method from inside an element such as a button:

<button type="button" onClick="javascript:showMyModalSetTitle('Some Title', 'Some body txt')"> Click Me! </button>

Why does overflow:hidden not work in a <td>?

I'm not familiar with the specific issue, but you could stick a div, etc inside the td and set overflow on that.

Run Command Prompt Commands

with a reference to Microsoft.VisualBasic

Interaction.Shell("copy /b Image1.jpg + Archive.rar Image2.jpg", AppWinStyle.Hide);

Getting a machine's external IP address with Python

In [1]: import stun

stun.get_ip_info()
('Restric NAT', 'xx.xx.xx.xx', 55320)

Convert timestamp to readable date/time PHP

I know that's an old one question, but its high in the search results.

If anyone wants timestamp conversion directly to a DateTime object, there's a simple one-liner:

$timestamp = 1299446702;
$date = DateTime::createFromFormat('U', $timestamp);

Following @sromero comment, timezone parameter (the 3rd param in DateTime::createFromFormat()) is ignored when unix timestamp is passed, so the below code is unnecessary.

$date = DateTime::createFromFormat('U', $timestamp, new DateTimeZone('UTC'); // not needed, 3rd parameter is ignored

You may check PHP's manual for DateTime::createFromFormat for more info and options.

Find a row in dataGridView based on column and value

If you just want to check if that item exists:

IEnumerable<DataGridViewRow> rows = grdPdfs.Rows
            .Cast<DataGridViewRow>()
            .Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue));
if (rows.Count() == 0) 
{
    // Not Found
} 
else 
{
    // Found
}

How to check what user php is running as?

Kind of backward way, but without exec/system:

file_put_contents("testFile", "test");
$user = fileowner("testFile");
unlink("testFile");

If you create a file, the owner will be the PHP user.

This could also likely be run with any of the temporary file functions such as tempnam(), which creates a random file in the temporary directory and returns the name of that file. If there are issues due to something like the permissions, open_basedir or safe mode that prevent writing a file, typically, the temp directory will still be allowed.

Clean out Eclipse workspace metadata

One of the things that you might want to try out is starting eclipse with the -clean option. If you have chosen to have eclipse use the same workspace every time then there is nothing else you need to do after that. With that option in place the workspace should be cleaned out.

However, if you don't have a default workspace chosen, when opening up eclipse you will be prompted to choose the workspace. At this point, choose the workspace you want cleaned up.

See "How to run eclipse in clean mode" and "Keeping Eclipse running clean" for more details.

Determine if string is in list in JavaScript

In addition to indexOf (which other posters have suggested), using prototype's Enumerable.include() can make this more neat and concise:

var list = ['a', 'b', 'c'];
if (list.include(str)) {
  // do stuff
}

Can a normal Class implement multiple interfaces?

public class A implements C,D {...} valid

this is the way to implement multiple inheritence in java

Creating dummy variables in pandas for python

The following code returns dataframe with the 'Category' column replaced by categorical columns:

df_with_dummies = pd.get_dummies(df, prefix='Category_', columns=['Category'])

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html

Concatenating strings doesn't work as expected

std::string a = "Hello ";
a += "World";

How do I correct this Illegal String Offset?

I get the same error in WP when I use php ver 7.1.6 - just take your php version back to 7.0.20 and the error will disappear.

Google Maps v2 - set both my location and zoom in

The simpliest way to do it is to use CancelableCallback. You should check the first action is complete and then call the second:

mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, size.x, height, 0), new CancelableCallback() {

                @Override
                public void onFinish() {
                    CameraUpdate cu_scroll = CameraUpdateFactory.scrollBy(0, 500);
                    mMap.animateCamera(cu_scroll);
                }

                @Override
                public void onCancel() {
                }
            });

Is there a quick change tabs function in Visual Studio Code?

Windows

previous

Ctrl + Shift + Tab

Next

Ctrl + Tab

Mac OS

previous

Shift+ Cmd + [

Next

Shift + Cmd + ]

How to render a DateTime object in a Twig template

you can render in following way

{{ post.published_at|date("m/d/Y") }}

For more details can visit http://twig.sensiolabs.org/doc/filters/date.html

How do I get Flask to run on port 80?

If you use the following to change the port or host:

if __name__ == '__main__':
  app.run(host='0.0.0.0', port=80)

use the following code to start the server (my main entrance for flask is app.py):

python app.py

instead of using:

flask run

How to add a border just on the top side of a UIView

I made some changes to Dan's answer so that I could add borders to multiple edges with one command:

infoView.addBorder(toEdges: [.left, .bottom, .right], color: borderColor, thickness: 1)

Here's the full code:

extension UIView {
    func addBorder(toEdges edges: UIRectEdge, color: UIColor, thickness: CGFloat) {

        func addBorder(toEdge edges: UIRectEdge, color: UIColor, thickness: CGFloat) {
            let border = CALayer()
            border.backgroundColor = color.cgColor

            switch edges {
            case .top:
                border.frame = CGRect(x: 0, y: 0, width: frame.width, height: thickness)
            case .bottom:
                border.frame = CGRect(x: 0, y: frame.height - thickness, width: frame.width, height: thickness)
            case .left:
                border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.height)
            case .right:
                border.frame = CGRect(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)
            default:
                break
            }

            layer.addSublayer(border)
        }

        if edges.contains(.top) || edges.contains(.all) {
            addBorder(toEdge: .top, color: color, thickness: thickness)
        }

        if edges.contains(.bottom) || edges.contains(.all) {
            addBorder(toEdge: .bottom, color: color, thickness: thickness)
        }

        if edges.contains(.left) || edges.contains(.all) {
            addBorder(toEdge: .left, color: color, thickness: thickness)
        }

        if edges.contains(.right) || edges.contains(.all) {
            addBorder(toEdge: .right, color: color, thickness: thickness)
        }
    }
}

How to sum all the values in a dictionary?

Sure there is. Here is a way to sum the values of a dictionary.

>>> d = {'key1':1,'key2':14,'key3':47}
>>> sum(d.values())
62

Drop multiple tables in one shot in MySQL

SET foreign_key_checks = 0;
DROP TABLE IF EXISTS a,b,c;
SET foreign_key_checks = 1;

Then you do not have to worry about dropping them in the correct order, nor whether they actually exist.

N.B. this is for MySQL only (as in the question). Other databases likely have different methods for doing this.

Changing EditText bottom line color with appcompat v7

I was absolutely baffled by this problem. I had tried everything in this thread, and in others, but no matter what I did I could not change the color of the underline to anything other than the default blue.

I finally figured out what was going on. I was (incorrectly) using android.widget.EditText when making a new instance (but the rest of my components were from the appcompat library). I should have used android.support.v7.widget.AppCompatEditText. I replaced new EditText(this) with new AppCompatEditText(this) and the problem was instantly solved. It turns out, if you are actually using AppCompatEditText, it will just respect the accentColor from your theme (as mentioned in several comments above) and no additional configuration is necessary.

Calculate text width with JavaScript

The better of is to detect whether text will fits right before you display the element. So you can use this function which doesn't requires the element to be on screen.

function textWidth(text, fontProp) {
    var tag = document.createElement("div");
    tag.style.position = "absolute";
    tag.style.left = "-999em";
    tag.style.whiteSpace = "nowrap";
    tag.style.font = fontProp;
    tag.innerHTML = text;

    document.body.appendChild(tag);

    var result = tag.clientWidth;

    document.body.removeChild(tag);

    return result;
}

Usage:

if ( textWidth("Text", "bold 13px Verdana") > elementWidth) {
    ...
}

relative path in require_once doesn't work

In my case it doesn't work, even with __DIR__ or getcwd() it keeps picking the wrong path, I solved by defining a costant in every file I need with the absolute base path of the project:

if(!defined('THISBASEPATH')){ define('THISBASEPATH', '/mypath/'); }
require_once THISBASEPATH.'cache/crud.php';
/*every other require_once you need*/

I have MAMP with php 5.4.10 and my folder hierarchy is basilar:

q.php 
w.php 
e.php 
r.php 
cache/a.php 
cache/b.php 
setting/a.php 
setting/b.php

....

How to use underscore.js as a template engine?

Lodash is also the same First write a script as follows:

<script type="text/template" id="genTable">
<table cellspacing='0' cellpadding='0' border='1'>
        <tr>
            <% for(var prop in users[0]){%>
            <th><%= prop %> </th>
            <% }%>
        </tr>
        <%_.forEach(users, function(user) { %>
            <tr>
                 <% for(var prop in user){%>
                    <td><%= user[prop] %> </td>
                <% }%>

            </tr>
        <%})%>
</table>

Now write some simple JS as follows:

var arrOfObjects = [];
for (var s = 0; s < 10; s++) {
    var simpleObject = {};
    simpleObject.Name = "Name_" + s;
    simpleObject.Address = "Address_" + s;
    arrOfObjects[s] = simpleObject;
}
var theObject = { 'users': arrOfObjects }
var compiled = _.template($("#genTable").text());
var sigma = compiled({ 'users': myArr });

$(sigma).appendTo("#popup");

Where popoup is a div where you want to generate the table

Why does make think the target is up to date?

EDIT: This only applies to some versions of make - you should check your man page.

You can also pass the -B flag to make. As per the man page, this does:

-B, --always-make Unconditionally make all targets.

So make -B test would solve your problem if you were in a situation where you don't want to edit the Makefile or change the name of your test folder.

git: Switch branch and ignore any changes without committing

switching to a new branch losing changes:

git checkout -b YOUR_NEW_BRANCH_NAME --force

switching to an existing branch losing changes:

git checkout YOUR_BRANCH --force

Is there any difference between a GUID and a UUID?

One difference between GUID in SQL Server and UUID in PostgreSQL is letter case; SQL Server outputs upper while PostgreSQL outputs lower.

The hexadecimal values "a" through "f" are output as lower case characters and are case insensitive on input. - rfc4122#section-3

How to define constants in Visual C# like #define in C?

In C#, per MSDN library, we have the "const" keyword that does the work of the "#define" keyword in other languages.

"...when the compiler encounters a constant identifier in C# source code (for example, months), it substitutes the literal value directly into the intermediate language (IL) code that it produces." ( https://msdn.microsoft.com/en-us/library/ms173119.aspx )

Initialize constants at time of declaration since there is no changing them.

public const int cMonths = 12;

sass :first-child not working

First of all, there are still browsers out there that don't support those pseudo-elements (ie. :first-child, :last-child), so you have to 'deal' with this issue.

There is a good example how to make that work without using pseudo-elements:

http://www.darowski.com/tracesofinspiration/2010/01/11/this-newbies-first-impressions-of-haml-and-sass/

       -- see the divider pipe example.

I hope that was useful.

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

How to loop through a HashMap in JSP?

Depending on what you want to accomplish within the loop, iterate over one of these instead:

  • countries.keySet()
  • countries.entrySet()
  • countries.values()

In C#, can a class inherit from another class and an interface?

No, not exactly. But it can inherit from a class and implement one or more interfaces.

Clear terminology is important when discussing concepts like this. One of the things that you'll see mark out Jon Skeet's writing, for example, both here and in print, is that he is always precise in the way he decribes things.

Android Studio drawable folders

In Android Studio 1.2.1.1

Just copy the image and paste the image into the app > res > drawable folder and it will shows you "Choose Destination Directory" popup screen as shown below screen

enter image description here

Now you can select option whatever resolution you want to place and if you want to view the those image into the folders then simply right click on the drawable folder > select copy paths option and open it. It will help you.

Interface vs Base class

Well, Josh Bloch said himself in Effective Java 2d:

Prefer interfaces over abstract classes

Some main points:

  • Existing classes can be easily retrofitted to implement a new interface. All you have to do is add the required methods if they don’t yet exist and add an implements clause to the class declaration.

  • Interfaces are ideal for defining mixins. Loosely speaking, a mixin is a type that a class can implement in addition to its “primary type” to declare that it provides some optional behavior. For example, Comparable is a mixin interface that allows a class to declare that its instances are ordered with respect to other mutually comparable objects.

  • Interfaces allow the construction of nonhierarchical type frameworks. Type hierarchies are great for organizing some things, but other things don’t fall neatly into a rigid hierarchy.

  • Interfaces enable safe, powerful functionality enhancements via the wrap- per class idiom. If you use abstract classes to define types, you leave the programmer who wants to add functionality with no alternative but to use inheritance.

Moreover, you can combine the virtues of interfaces and abstract classes by providing an abstract skeletal implementation class to go with each nontrivial interface that you export.

On the other hand, interfaces are very hard to evolve. If you add a method to an interface it'll break all of it's implementations.

PS.: Buy the book. It's a lot more detailed.

Random string generation with upper case letters and digits

Use Numpy's random.choice() function

import numpy as np
import string        

if __name__ == '__main__':
    length = 16
    a = np.random.choice(list(string.ascii_uppercase + string.digits), length)                
    print(''.join(a))

Documentation is here http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.random.choice.html

XPath to select Element by attribute value

As a follow on, you could select "all nodes with a particular attribute" like this:

//*[@id='4']

c# foreach (property in object)... Is there a simple way of doing this?

Give this a try:

foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
   // do stuff here
}

Also please note that Type.GetProperties() has an overload which accepts a set of binding flags so you can filter out properties on a different criteria like accessibility level, see MSDN for more details: Type.GetProperties Method (BindingFlags) Last but not least don't forget to add the "system.Reflection" assembly reference.

For instance to resolve all public properties:

foreach (var propertyInfo in obj.GetType()
                                .GetProperties(
                                        BindingFlags.Public 
                                        | BindingFlags.Instance))
{
   // do stuff here
}

Please let me know whether this works as expected.

Create a circular button in BS3

you can do something like adding a class to add border radius

HTML:

<a href="#" class="btn btn-default btn-circle"><i class="fa fa-user"></i></a>

CSS:

.btn-circle {
  width: 30px;
  height: 30px;
  text-align: center;
  padding: 6px 0;
  font-size: 12px;
  line-height: 1.42;
  border-radius: 15px;
}

in case you wanted to change dimension you need to change the font size or padding accordingly

SQL update trigger only when column is modified

You want to do the following:

ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
   ON [dbo].[SCHEDULE]
   AFTER UPDATE
AS 
BEGIN
SET NOCOUNT ON;

    IF (UPDATE(QtyToRepair))
    BEGIN
        UPDATE SCHEDULE SET modified = GETDATE()
            , ModifiedUser = SUSER_NAME()
            , ModifiedHost = HOST_NAME()
        FROM SCHEDULE S
        INNER JOIN Inserted I ON S.OrderNo = I.OrderNo AND S.PartNumber = I.PartNumber
        WHERE S.QtyToRepair <> I.QtyToRepair
    END
END

Please note that this trigger will fire each time you update the column no matter if the value is the same or not.

Conditional step/stage in Jenkins pipeline

According to other answers I am adding the parallel stages scenario:

pipeline {
    agent any
    stages {
        stage('some parallel stage') {
            parallel {
                stage('parallel stage 1') {
                    when {
                      expression { ENV == "something" }
                    }
                    steps {
                        echo 'something'
                    }
                }
                stage('parallel stage 2') {
                    steps {
                        echo 'something'
                    }
                }
            }
        }
    }
}

Evaluate if list is empty JSTL

There's also the function tags, a bit more flexible:

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">

And here's the tag documentation.

How to switch from POST to GET in PHP CURL

Make sure that you're putting your query string at the end of your URL when doing a GET request.

$qry_str = "?x=10&y=20";
$ch = curl_init();

// Set query data here with the URL
curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php' . $qry_str); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$content = trim(curl_exec($ch));
curl_close($ch);
print $content;
With a POST you pass the data via the CURLOPT_POSTFIELDS option instead 
of passing it in the CURLOPT__URL.
-------------------------------------------------------------------------

$qry_str = "x=10&y=20";
curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php');  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);

// Set request method to POST
curl_setopt($ch, CURLOPT_POST, 1);

// Set query data here with CURLOPT_POSTFIELDS
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry_str);

$content = trim(curl_exec($ch));
curl_close($ch);
print $content;

Note from the curl_setopt() docs for CURLOPT_HTTPGET (emphasis added):

[Set CURLOPT_HTTPGET equal to] TRUE to reset the HTTP request method to GET.
Since GET is the default, this is only necessary if the request method has been changed.

Getting number of elements in an iterator in Python

I like the cardinality package for this, it is very lightweight and tries to use the fastest possible implementation available depending on the iterable.

Usage:

>>> import cardinality
>>> cardinality.count([1, 2, 3])
3
>>> cardinality.count(i for i in range(500))
500
>>> def gen():
...     yield 'hello'
...     yield 'world'
>>> cardinality.count(gen())
2

The actual count() implementation is as follows:

def count(iterable):
    if hasattr(iterable, '__len__'):
        return len(iterable)

    d = collections.deque(enumerate(iterable, 1), maxlen=1)
    return d[0][0] if d else 0

How to change Elasticsearch max memory size

Updated on Nov 24, 2016: Elasticsearch 5 apparently has changed the way to configure the JVM. See this answer here. The answer below still applies to versions < 5.

tirdadc, thank you for pointing this out in your comment below.


I have a pastebin page that I share with others when wondering about memory and ES. It's worked OK for me: http://pastebin.com/mNUGQCLY. I'll paste the contents here as well:

References:

https://github.com/grigorescu/Brownian/wiki/ElasticSearch-Configuration http://www.elasticsearch.org/guide/reference/setup/installation/

Edit the following files to modify memory and file number limits. These instructions assume Ubuntu 10.04, may work on later versions and other distributions/OSes. (Edit: This works for Ubuntu 14.04 as well.)

/etc/security/limits.conf:

elasticsearch - nofile 65535
elasticsearch - memlock unlimited

/etc/default/elasticsearch (on CentOS/RH: /etc/sysconfig/elasticsearch ):

ES_HEAP_SIZE=512m
MAX_OPEN_FILES=65535
MAX_LOCKED_MEMORY=unlimited

/etc/elasticsearch/elasticsearch.yml:

bootstrap.mlockall: true

How to make a movie out of images in python

Here is a minimal example using moviepy. For me this was the easiest solution.

import os
import moviepy.video.io.ImageSequenceClip
image_folder='folder_with_images'
fps=1

image_files = [image_folder+'/'+img for img in os.listdir(image_folder) if img.endswith(".png")]
clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps)
clip.write_videofile('my_video.mp4')

Clear back stack using fragments

Reading the documentation and studying what the fragment id is, it appears to simply be the stack index, so this works:

fragmentManager.popBackStackImmediate(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);

Zero (0) is the the bottom of the stack, so popping up to it inclusive clears the stack.

CAVEAT: Although the above works in my program, I hesitate a bit because the FragmentManager documentation never actually states that the id is the stack index. It makes sense that it would be, and all my debug logs bare out that it is, but perhaps in some special circumstance it would not? Can any one confirm this one way or the other? If it is, then the above is the best solution. If not, this is the alternative:

while(fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStackImmediate(); }

How to sort a Ruby Hash by number value?

Already answered but still. Change your code to:

metrics.sort {|a1,a2| a2[1].to_i <=> a1[1].to_i }

Converted to strings along the way or not, this will do the job.

How to discard uncommitted changes in SourceTree?

On the unstaged file, click on the three dots on the right side. Once you click it, a popover menu will appear where you can then Discard file.

What are the differences between a superkey and a candidate key?

A super key of an entity set is a set of one or more attributes whose values uniquely determine each entity.

A candidate key of an entity set is a minimal super key.

Let's go on with customer, loan and borrower sets that you can find an image from the link == 1

  • Rectangles represent entity sets == 1
  • Diamonds represent relationship set == 1
  • Elipses represent attributes == 1
  • Underline indicates Primary Keys == 1

customer_id is the candidate key of the customer set, loan_number is the candidate key of the loan set.

Although several candidate keys may exist, one of the candidate keys is selected to be the primary key.

Borrower set is formed customer_id and loan_number as a relationship set.

How to quit a java app from within the program

This should do it in the correct way:

mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
mainFrame.addWindowListener(new WindowListener() {

@Override
public void windowClosing(WindowEvent e) {
    if (doQuestion("Really want to exit?")) {
      mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      mainFrame.dispose();
    }
}

scp files from local to remote machine error: no such file or directory

As @Astariul said, path to the file might cause this bug.
In addition, any parent directory which contains non-ASCII character, for example Chinese, will cause this.
In that case, you should rename you parent directory

How to post pictures to instagram using API

There is no API to post photo to instagram using API , But there is a simple way is that install google extension " User Agent " it will covert your browser to android mobile chrome version . Here is the extension link https://chrome.google.com/webstore/detail/user-agent-switcher/clddifkhlkcojbojppdojfeeikdkgiae?utm_source=chrome-ntp-icon

just click on extension icon and choose chrome for android and open Instagram.com

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

@Nickparsa … you have 2 issues:

1). mysql -uroot -p should be typed in bash (also known as your terminal) not in MySQL command-line. You fix this error by typing

exit

in your MySQL command-line. Now you are back in your bash/terminal command-line.

2). You have a syntax error:

mysql -uroot -p; 

the semicolon in front of -p needs to go. The correct syntax is:

mysql -uroot -p

type the correct syntax in your bash commandline. Enter a password if you have one set up; else just hit the enter button. You should get a response that is similar to this: enter image description here

Hope this helps!

ExecuteNonQuery doesn't return results

The ExecuteNonQuery method is used for SQL statements that are not queries, such as INSERT, UPDATE, ... You want to use ExecuteScalar or ExecuteReader if you expect your statement to return results (i.e. a query).

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

Let's start with the explanation of why do you see these warnings in the first place.


Most probably you have not installed TF from source and instead of it used something like pip install tensorflow. That means that you installed pre-built (by someone else) binaries which were not optimized for your architecture. And these warnings tell you exactly this: something is available on your architecture, but it will not be used because the binary was not compiled with it. Here is the part from documentation.

TensorFlow checks on startup whether it has been compiled with the optimizations available on the CPU. If the optimizations are not included, TensorFlow will emit warnings, e.g. AVX, AVX2, and FMA instructions not included.

Good thing is that most probably you just want to learn/experiment with TF so everything will work properly and you should not worry about it


What are SSE4.2 and AVX?

Wikipedia has a good explanation about SSE4.2 and AVX. This knowledge is not required to be good at machine-learning. You may think about them as a set of some additional instructions for a computer to use multiple data points against a single instruction to perform operations which may be naturally parallelized (for example adding two arrays).

Both SSE and AVX are implementation of an abstract idea of SIMD (Single instruction, multiple data), which is

a class of parallel computers in Flynn's taxonomy. It describes computers with multiple processing elements that perform the same operation on multiple data points simultaneously. Thus, such machines exploit data level parallelism, but not concurrency: there are simultaneous (parallel) computations, but only a single process (instruction) at a given moment

This is enough to answer your next question.


How do these SSE4.2 and AVX improve CPU computations for TF tasks

They allow a more efficient computation of various vector (matrix/tensor) operations. You can read more in these slides


How to make Tensorflow compile using the two libraries?

You need to have a binary which was compiled to take advantage of these instructions. The easiest way is to compile it yourself. As Mike and Yaroslav suggested, you can use the following bazel command

bazel build -c opt --copt=-mavx --copt=-mavx2 --copt=-mfma --copt=-mfpmath=both --copt=-msse4.2 --config=cuda -k //tensorflow/tools/pip_package:build_pip_package

How To fix white screen on app Start up?

Below is the link that suggests how to design Splash screen. To avoid white/black background we need to define a theme with splash background and set that theme to splash in manifest file.

https://android.jlelse.eu/right-way-to-create-splash-screen-on-android-e7f1709ba154

splash_background.xml inside res/drawable folder

<?xml version=”1.0" encoding=”utf-8"?>
 <layer-list xmlns:android=”http://schemas.android.com/apk/res/android">

 <item android:drawable=”@color/colorPrimary” />

 <item>
 <bitmap
 android:gravity=”center”
 android:src=”@mipmap/ic_launcher” />
 </item>

</layer-list>

Add below styles

<!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
    <!-- Splash Screen theme. -->
    <style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="android:windowBackground">@drawable/splash_background</item>
    </style>

In Manifest set theme as shown below

<activity
            android:name=".SplashActivity"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
    </activity>

Adding css class through aspx code behind

BtnAdd.CssClass = "BtnCss";

BtnCss should be present in your Css File.

(reference of that Css File name should be added to the aspx if needed)

How to get the python.exe location programmatically?

I think it depends on how you installed python. Note that you can have multiple installs of python, I do on my machine. However, if you install via an msi of a version of python 2.2 or above, I believe it creates a registry key like so:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Python.exe

which gives this value on my machine:

C:\Python25\Python.exe

You just read the registry key to get the location.

However, you can install python via an xcopy like model that you can have in an arbitrary place, and you just have to know where it is installed.

Display Back Arrow on Toolbar

If you don't want to create a custom Toolbar, you can do like this

public class GalleryActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...  
        getSupportActionBar().setTitle("Select Image");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}                     

In you AndroidManifest.xml

<activity
    android:name=".GalleryActivity"
    android:theme="@style/Theme.AppCompat.Light">        
</activity>

you can also put this android:theme="@style/Theme.AppCompat.Light" to <aplication> tag, for apply to all activities

enter image description here

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

Add this code to the beginning:

    Application.ScreenUpdating = False
     With ThisWorkbook
      Dim ws As Worksheet
       For Each ws In Worksheets: ws.Visible = True: Next ws
     End With

Add this code to the end:

    With ThisWorkbook
     Dim ws As Worksheet
      For Each ws In Worksheets: ws.Visible = False: Next ws
    End With
     Application.ScreenUpdating = True

Adjust Code at the end if you want more than the first sheet to be active and visible. Such as the following:

     Dim ws As Worksheet
      For Each ws In Worksheets
       If ws.Name = "_DataRecords" Then

         Else: ws.Visible = False
       End If
      Next ws

To ensure the new sheet is the one renamed, adjust your code similar to the following:

     Sheets(Me.cmbxSheetCopy.value).Copy After:=Sheets(Sheets.Count)
     Sheets(Me.cmbxSheetCopy.value & " (2)").Select
     Sheets(Me.cmbxSheetCopy.value & " (2)").Name = txtbxNewSheetName.value

This code is from my user form that allows me to copy a particular sheet (chosen from a dropdown box) with the formatting and formula's that I want to a new sheet and then rename new sheet with the user Input. Note that every time a sheet is copied it is automatically given the old sheet name with the designation of " (2)". Example "OldSheet" becomes "OldSheet (2)" after the copy and before the renaming. So you must select the Copied sheet with the programs naming before renaming.

How to run Pip commands from CMD

Simple solution that worked for me is, set the path of python in environment variables,it is done as follows

  1. Go to My Computer
  2. Open properties
  3. Open Advanced Settings
  4. Open Environment Variables
  5. Select path
  6. Edit it

In the edit option click add and add following two paths to it one by one:

C:\Python27

C:\Python27\Scripts

and now close cmd and run it as administrator, by that pip will start working.

How to set java_home on Windows 7?

if you have not restarted your computer after installing jdk just restart your computer.

if you want to make a portable java and set path before using java, just make a batch file i explained below.

if you want to run this batch file when your computer start just put your batch file shortcut in startup folder. In windows 7 startup folder is "C:\Users\user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"

make a batch file like this:

set Java_Home=C:\Program Files\Java\jdk1.8.0_11
set PATH=%PATH%;C:\Program Files\Java\jdk1.8.0_11\bin

note: java_home and path are variables. you can make any variable as you wish. for example set amir=good_boy and you can see amir by %amir% or you can see java_home by %java_home%

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

Erm, after understanding your question: are you sure that the signature-method only creates a SHA1 and encrypts it? GPG et al offer to compress/clear sign the data. Maybe this java-signature-alg also creates a detachable/attachable signature.

how to remove new lines and returns from php string?

Something a bit more functional (easy to use anywhere):

function replace_carriage_return($replace, $string)
{
    return str_replace(array("\n\r", "\n", "\r"), $replace, $string);
}

Using PHP_EOL as the search replacement parameter is also a good idea! Kudos.

Android: how to get the current day of the week (Monday, etc...) in the user's language?

//selected date from calender
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); //Date and time
String currentDate = sdf.format(myCalendar.getTime());

//selcted_day name
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE");
String dayofweek=sdf_.format(myCalendar.getTime());
current_date.setText(currentDate);
lbl_current_date.setText(dayofweek);

Log.e("dayname", dayofweek);

jquery stop child triggering parent event

I stumbled upon this question, looking for another answer.

I wanted to prevent all children from triggering the parent.

JavaScript:

document.getElementById("parent").addEventListener("click",  function (e) {
    if (this !== event.target) return;
    // Do something
});

jQuery:

$("#parent").click(function () {
    // Do something
}).children().on("click", function (e) {
    e.stopPropagation();
});

Jenkins - how to build a specific branch

I don't think you can both within the same jenkins job, what you need to do is to configure a new jenkins job which will have access to your github to retrieve branches and then you can choose which one to manually build.

Just mark it as a parameterized build, specify a name, and a parameter configured as git parameter

enter image description here

and now you can configure git options:

enter image description here

Why split the <script> tag when writing it with document.write()?

</script> has to be broken up because otherwise it would end the enclosing <script></script> block too early. Really it should be split between the < and the /, because a script block is supposed (according to SGML) to be terminated by any end-tag open (ETAGO) sequence (i.e. </):

Although the STYLE and SCRIPT elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence "</" (end-tag open delimiter) is treated as terminating the end of the element's content. In valid documents, this would be the end tag for the element.

However in practice browsers only end parsing a CDATA script block on an actual </script> close-tag.

In XHTML there is no such special handling for script blocks, so any < (or &) character inside them must be &escaped; like in any other element. However then browsers that are parsing XHTML as old-school HTML will get confused. There are workarounds involving CDATA blocks, but it's easiest simply to avoid using these characters unescaped. A better way of writing a script element from script that works on either type of parser would be:

<script type="text/javascript">
    document.write('\x3Cscript type="text/javascript" src="foo.js">\x3C/script>');
</script>

Parsing JSON string in Java

you have an extra "}" in each object, you may write the json string like this:

public class ShowActivity {   
    private final static String  jString = "{" 
    + "    \"geodata\": [" 
    + "        {" 
    + "                \"id\": \"1\"," 
    + "                \"name\": \"Julie Sherman\","                  
    + "                \"gender\" : \"female\"," 
    + "                \"latitude\" : \"37.33774833333334\"," 
    + "                \"longitude\" : \"-121.88670166666667\""            
    + "                }" 
    + "        }," 
    + "        {" 
    + "                \"id\": \"2\"," 
    + "                \"name\": \"Johnny Depp\","          
    + "                \"gender\" : \"male\"," 
    + "                \"latitude\" : \"37.336453\"," 
    + "                \"longitude\" : \"-121.884985\""            
    + "                }" 
    + "        }" 
    + "    ]" 
    + "}"; 
}

How to Select Every Row Where Column Value is NOT Distinct

This is significantly faster than the EXISTS way:

SELECT [EmailAddress], [CustomerName] FROM [Customers] WHERE [EmailAddress] IN
  (SELECT [EmailAddress] FROM [Customers] GROUP BY [EmailAddress] HAVING COUNT(*) > 1)

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

You also have to delete the local branch:

git branch -d 6796

Another way is to prune all stale branches from your local repository. This will delete all local branches that already have been removed from the remote:

git remote prune origin --dry-run

C# Switch-case string starting with

If all the cases have the same length you can use
switch (mystring.SubString(0,Math.Min(len, mystring.Length))).
Another option is to have a function that will return categoryId based on the string and switch on the id.

How to read numbers separated by space using scanf

int main()
{
char string[200];
int g,a,i,G[20],A[20],met;

gets(string);
g=convert_input(G,string);

for(i=0;i<=g;i++)
    printf("\n%d>>%d",i,G[i]);
return 0;
}

int convert_input(int K[],char string[200])
{
int j=0,i=0,temp=0;
while(string[i]!='\0')
{
    temp=0;
    while(string[i]!=' ' && string[i]!='\0')
        temp=temp*10 + (string[i++]-'0') ;
    if(string[i]==' ')
        i++;
    K[j++]=temp;
}
return j-1;
}

Using Postman to access OAuth 2.0 Google APIs

I figured out that I was not generating Credentials for the right app type.
If you're using Postman to test Google oAuth 2 APIs, select
Credentials -> Add credentials -> OAuth2.0 client ID -> Web Application.

enter image description here

How to set dropdown arrow in spinner?

If you have a vector icon and not bitmap, you can set it this way.

<item>
    <layer-list>
        <item>
            <shape android:shape="rectangle">
                <gradient android:angle="270" android:centerColor="#65FFFFFF" android:centerY="0.2" android:endColor="#00FFFFFF" android:startColor="@color/light_gray" />
                <stroke android:width="1dp" android:color="@color/darkGray" />
                <corners android:radius="@dimen/edit_text_corner_radius" />
            </shape>
        </item>

        <item
            android:right="5dp"
            android:gravity="center|right"
            android:drawable="@drawable/gardify_spinner_dropdown_icon"/>

    </layer-list>
</item>

cast a List to a Collection

Not knowing your code, it's a bit hard to answer your question, but based on all the info here, I believe the issue is you're trying to use Collections.sort passing in an object defined as Collection, and sort doesn't support that.

First question. Why is client defined so generically? Why isn't it a List, Map, Set or something a little more specific?

If client was defined as a List, Map or Set, you wouldn't have this issue, as then you'd be able to directly use Collections.sort(client).

HTH

SQL Group By with an Order By

In all versions of MySQL, simply alias the aggregate in the SELECT list, and order by the alias:

SELECT COUNT(id) AS theCount, `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY theCount DESC
LIMIT 20

UDP vs TCP, how much faster is it?

People say that the major thing TCP gives you is reliability. But that's not really true. The most important thing TCP gives you is congestion control: you can run 100 TCP connections across a DSL link all going at max speed, and all 100 connections will be productive, because they all "sense" the available bandwidth. Try that with 100 different UDP applications, all pushing packets as fast as they can go, and see how well things work out for you.

On a larger scale, this TCP behavior is what keeps the Internet from locking up into "congestion collapse".

Things that tend to push applications towards UDP:

  • Group delivery semantics: it's possible to do reliable delivery to a group of people much more efficiently than TCP's point-to-point acknowledgement.

  • Out-of-order delivery: in lots of applications, as long as you get all the data, you don't care what order it arrives in; you can reduce app-level latency by accepting an out-of-order block.

  • Unfriendliness: on a LAN party, you may not care if your web browser functions nicely as long as you're blitting updates to the network as fast as you possibly can.

But even if you care about performance, you probably don't want to go with UDP:

  • You're on the hook for reliability now, and a lot of the things you might do to implement reliability can end up being slower than what TCP already does.

  • Now you're network-unfriendly, which can cause problems in shared environments.

  • Most importantly, firewalls will block you.

You can potentially overcome some TCP performance and latency issues by "trunking" multiple TCP connections together; iSCSI does this to get around congestion control on local area networks, but you can also do it to create a low-latency "urgent" message channel (TCP's "URGENT" behavior is totally broken).

Check if a row exists, otherwise insert

Pass updlock, rowlock, holdlock hints when testing for existence of the row.

begin tran /* default read committed isolation level is fine */

if not exists (select * from Table with (updlock, rowlock, holdlock) where ...)
    /* insert */
else
    /* update */

commit /* locks are released here */

The updlock hint forces the query to take an update lock on the row if it already exists, preventing other transactions from modifying it until you commit or roll back.

The holdlock hint forces the query to take a range lock, preventing other transactions from adding a row matching your filter criteria until you commit or roll back.

The rowlock hint forces lock granularity to row level instead of the default page level, so your transaction won't block other transactions trying to update unrelated rows in the same page (but be aware of the trade-off between reduced contention and the increase in locking overhead - you should avoid taking large numbers of row-level locks in a single transaction).

See http://msdn.microsoft.com/en-us/library/ms187373.aspx for more information.

Note that locks are taken as the statements which take them are executed - invoking begin tran doesn't give you immunity against another transaction pinching locks on something before you get to it. You should try and factor your SQL to hold locks for the shortest possible time by committing the transaction as soon as possible (acquire late, release early).

Note that row-level locks may be less effective if your PK is a bigint, as the internal hashing on SQL Server is degenerate for 64-bit values (different key values may hash to the same lock id).

How to get the list of properties of a class?

Here is improved @lucasjones answer. I included improvements mentioned in comment section after his answer. I hope someone will find this useful.

public static string[] GetTypePropertyNames(object classObject,  BindingFlags bindingFlags)
{
    if (classObject == null)
    {
        throw new ArgumentNullException(nameof(classObject));
    }

        var type = classObject.GetType();
        var propertyInfos = type.GetProperties(bindingFlags);

        return propertyInfos.Select(propertyInfo => propertyInfo.Name).ToArray();
 }

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can't solve it. Simply answer1.sum()==0, and you can't perform a division by zero.

This happens because answer1 is the exponential of 2 very large, negative numbers, so that the result is rounded to zero.

nan is returned in this case because of the division by zero.

Now to solve your problem you could:

  • go for a library for high-precision mathematics, like mpmath. But that's less fun.
  • as an alternative to a bigger weapon, do some math manipulation, as detailed below.
  • go for a tailored scipy/numpy function that does exactly what you want! Check out @Warren Weckesser answer.

Here I explain how to do some math manipulation that helps on this problem. We have that for the numerator:

exp(-x)+exp(-y) = exp(log(exp(-x)+exp(-y)))
                = exp(log(exp(-x)*[1+exp(-y+x)]))
                = exp(log(exp(-x) + log(1+exp(-y+x)))
                = exp(-x + log(1+exp(-y+x)))

where above x=3* 1089 and y=3* 1093. Now, the argument of this exponential is

-x + log(1+exp(-y+x)) = -x + 6.1441934777474324e-06

For the denominator you could proceed similarly but obtain that log(1+exp(-z+k)) is already rounded to 0, so that the argument of the exponential function at the denominator is simply rounded to -z=-3000. You then have that your result is

exp(-x + log(1+exp(-y+x)))/exp(-z) = exp(-x+z+log(1+exp(-y+x)) 
                                   = exp(-266.99999385580668)

which is already extremely close to the result that you would get if you were to keep only the 2 leading terms (i.e. the first number 1089 in the numerator and the first number 1000 at the denominator):

exp(3*(1089-1000))=exp(-267)

For the sake of it, let's see how close we are from the solution of Wolfram alpha (link):

Log[(exp[-3*1089]+exp[-3*1093])/([exp[-3*1000]+exp[-3*4443])] -> -266.999993855806522267194565420933791813296828742310997510523

The difference between this number and the exponent above is +1.7053025658242404e-13, so the approximation we made at the denominator was fine.

The final result is

'exp(-266.99999385580668) = 1.1050349147204485e-116

From wolfram alpha is (link)

1.105034914720621496.. × 10^-116 # Wolfram alpha.

and again, it is safe to use numpy here too.

Make an existing Git branch track a remote branch?

In very short

git branch --set-upstream yourLocalBranchName origin/develop

This will make your yourLocalBranchName track the remote branch called develop.

Getting the last element of a list

If your str() or list() objects might end up being empty as so: astr = '' or alist = [], then you might want to use alist[-1:] instead of alist[-1] for object "sameness".

The significance of this is:

alist = []
alist[-1]   # will generate an IndexError exception whereas 
alist[-1:]  # will return an empty list
astr = ''
astr[-1]    # will generate an IndexError exception whereas
astr[-1:]   # will return an empty str

Where the distinction being made is that returning an empty list object or empty str object is more "last element"-like then an exception object.

How to use Ajax.ActionLink?

@Ajax.ActionLink requires jQuery AJAX Unobtrusive library. You can download it via nuget:

Install-Package Microsoft.jQuery.Unobtrusive.Ajax

Then add this code to your View:

@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")

What is use of c_str function In c++

In C/C++ programming there are two types of strings: the C strings and the standard strings. With the <string> header, we can use the standard strings. On the other hand, the C strings are just an array of normal chars. So, in order to convert a standard string to a C string, we use the c_str() function.

for example

// a string to a C-style string conversion//

const char *cstr1 = str1.c_str();
cout<<"Operation: *cstr1 = str1.c_str()"<<endl;
cout<<"The C-style string c_str1 is: "<<cstr1<<endl;
cout<<"\nOperation: strlen(cstr1)"<<endl;
cout<<"The length of C-style string str1 = "<<strlen(cstr1)<<endl;

And the output will be,

Operation: *cstr1 = str1.c_str()
The C-style string c_str1 is: Testing the c_str 
Operation: strlen(cstr1)
The length of C-style string str1 = 17

Formatting MM/DD/YYYY dates in textbox in VBA

I never suggest using Textboxes or Inputboxes to accept dates. So many things can go wrong. I cannot even suggest using the Calendar Control or the Date Picker as for that you need to register the mscal.ocx or mscomct2.ocx and that is very painful as they are not freely distributable files.

Here is what I recommend. You can use this custom made calendar to accept dates from the user

PROS:

  1. You don't have to worry about user inputting wrong info
  2. You don't have to worry user pasting in the textbox
  3. You don't have to worry about writing any major code
  4. Attractive GUI
  5. Can be easily incorporated in your application
  6. Doesn't use any controls for which you need to reference any libraries like mscal.ocx or mscomct2.ocx

CONS:

Ummm...Ummm... Can't think of any...

HOW TO USE IT (File missing from my dropbox. Please refer to the bottom of the post for an upgraded version of the calendar)

  1. Download the Userform1.frm and Userform1.frx from here.
  2. In your VBA, simply import Userform1.frm as shown in the image below.

Importing the form

enter image description here

RUNNING IT

You can call it in any procedure. For example

Sub Sample()
    UserForm1.Show
End Sub

SCREEN SHOTS IN ACTION

enter image description here

NOTE: You may also want to see Taking Calendar to new level

AngularJS access scope from outside js function

The accepted answer is great. I wanted to look at what happens to the Angular scope in the context of ng-repeat. The thing is, Angular will create a sub-scope for each repeated item. When calling into a method defined on the original $scope, that retains its original value (due to javascript closure). However, the this refers the calling scope/object. This works out well, so long as you're clear on when $scope and this are the same and when they are different. hth

Here is a fiddle that illustrates the difference: https://jsfiddle.net/creitzel/oxsxjcyc/

Registering for Push Notifications in Xcode 8/Swift 3.0?

First, listen to user notification status, i.e., registerForRemoteNotifications() to get APNs device token;
Second, request authorization. When being authorized by the user, deviceToken will be sent to the listener, the AppDelegate;
Third, report the device token to your server.

extension AppDelegate {
    /// 1. ?? deviceToken
    UIApplication.shared.registerForRemoteNotifications()

    /// 2. ???????????(????? token)
    static func registerRemoteNotifications() {
        if #available(iOS 10, *) {
            let uc = UNUserNotificationCenter.current()
            uc.delegate = UIApplication.shared.delegate as? AppDelegate
            uc.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
                if let error = error { // ???????,????? aps-certificate,? error ??? nil
                    print("UNUserNotificationCenter ??????, \(error)")
                }
                DispatchQueue.main.async {
                    onAuthorization(granted: granted)
                }
            }
        } else {
            let app = UIApplication.shared
            app.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)) // ??????
        }
    }

    // ? app.registerUserNotificationSettings() ???????????????,????????
    func application(_ app: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
        // ???????,????????
        // a ???????,???app????,?????????
        // b ??????????,??????????,???????,??token,?????
        // c ??badge, alert?sound ?,notificationSettings.types.rawValue ?? 0 ? app.isRegisteredForRemoteNotifications ??,????token,??????(?????????????),???types??????
        // ???????,????????,?? isRegisteredForRemoteNotifications ??? false
       onAuthorization(granted: app.isRegisteredForRemoteNotifications)
    }

    static func onAuthorization(granted: Bool) {
        guard granted else { return }
        // do something
    }
}

extension AppDelegate {
    func application(_ app: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        //
    }

    // ?????? token,??? aps-certificate ??????? token,???????????? token
    func application(_ app: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        //
    }
}

@class vs. #import

Look at the Objective-C Programming Language documentation on ADC

Under the section on Defining a Class | Class Interface it describes why this is done:

The @class directive minimizes the amount of code seen by the compiler and linker, and is therefore the simplest way to give a forward declaration of a class name. Being simple, it avoids potential problems that may come with importing files that import still other files. For example, if one class declares a statically typed instance variable of another class, and their two interface files import each other, neither class may compile correctly.

I hope this helps.

Exception thrown in catch and finally clause

I think you just have to walk the finally blocks:

  1. Print "1".
  2. finally in q print "3".
  3. finally in main print "2".

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

How can I display the current branch and folder path in terminal?

Keep it fast, keep it simple

put this in your ~/.bashrc file.

git_stuff() {
  git_branch=$(git branch --show-current 2> /dev/null)
  if [[ $git_branch == "" ]];then
    echo -e ""
  elif [[ $git_branch == *"Nocommit"* ]];then
    echo -e "No commits"
  else
    echo -e "$git_branch"
  fi
}
prompt() {
  PS1="\e[2m$(date +%H:%M:%S.%3N) \e[4m$(git_stuff)\033[0m\n\w$ "
}
PROMPT_COMMAND=prompt

Then source ~/.bashrc

enter image description here

How to create json by JavaScript for loop?

From what I understand of your request, this should work:

<script>
//  var status  = document.getElementsByID("uniqueID"); // this works too
var status  = document.getElementsByName("status")[0];
var jsonArr = [];

for (var i = 0; i < status.options.length; i++) {
    jsonArr.push({
        id: status.options[i].text,
        optionValue: status.options[i].value
    });
}
</script>

How do I rewrite URLs in a proxy response in NGINX

You may also need the following directive to be set before the first "sub_filter" for backend-servers with data compression:

proxy_set_header Accept-Encoding "";

Otherwise it may not work. For your example it will look like:

location /admin/ {
    proxy_pass http://localhost:8080/;
    proxy_set_header Accept-Encoding "";
    sub_filter "http://your_server/" "http://your_server/admin/";
    sub_filter_once off;
}

How to set focus to a button widget programmatically?

Try this:

btn.requestFocusFromTouch();

How do I get the web page contents from a WebView?

You also need to annotate the method with @JavascriptInterface if your targetSdkVersion is >= 17 - because there is new security requirements in SDK 17, i.e. all javascript methods must be annotated with @JavascriptInterface. Otherwise you will see error like: Uncaught TypeError: Object [object Object] has no method 'processHTML' at null:1

How to limit text width

Try this:

<style> 
p
{
    width:100px; 
    word-wrap:break-word;
}
</style>

<p>Loremipsumdolorsitamet,consecteturadipiscingelit.Fusce non nisl
non ante malesuada mollis quis ut ipsum. Cum sociis natoque penatibus et magnis dis 
parturient montes, nascetur ridiculus mus. Cras ut adipiscing dolor. Nunc congue, 
tellus vehicula mattis porttitor, justo nisi sollicitudin nulla, a rhoncus lectus lacus 
id turpis. Vivamus diam lacus, egestas nec bibendum eu, mattis eget risus</p>

How do I create ColorStateList programmatically?

Unfortunately none of the solutions works for me.

  1. If you don't set pressed state at first it won't detect it.
  2. If you set it, then you need to define empty state to add default color
ColorStateList themeColorStateList = new ColorStateList(
        new int[][]{
                new int[]{android.R.attr.state_pressed},
                new int[]{android.R.attr.state_enabled},
                new int[]{android.R.attr.state_focused, android.R.attr.state_pressed},
                new int[]{-android.R.attr.state_enabled},
                new int[]{} // this should be empty to make default color as we want
        },
        new int[]{
                pressedFontColor,
                defaultFontColor,
                pressedFontColor,
                disabledFontColor,
                defaultFontColor
        }
);

This is constructor from source code:

/**
 * Creates a ColorStateList that returns the specified mapping from
 * states to colors.
 */
public ColorStateList(int[][] states, int[] colors) {
    mStateSpecs = states;
    mColors = colors;

    if (states.length > 0) {
        mDefaultColor = colors[0];

        for (int i = 0; i < states.length; i++) {
            if (states[i].length == 0) {
                mDefaultColor = colors[i];
            }
        }
    }
}

How to overlay image with color in CSS?

You may use negative superthick semi-transparent border...

_x000D_
_x000D_
.red {_x000D_
    outline: 100px solid rgba(255, 0, 0, 0.5) !important;_x000D_
    outline-offset: -100px;_x000D_
    overflow: hidden;_x000D_
    position: relative;_x000D_
    height: 200px;_x000D_
    width: 200px;_x000D_
}
_x000D_
<div class="red">Anything can be red.</div>_x000D_
<h1>Or even image...</h1>_x000D_
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a" class="red"/>
_x000D_
_x000D_
_x000D_

This solution requires you to know exact sizes of covered object.

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

my solution is to use a timeout. Seems to work ok

$('input[type=text]').focus(function() {
    var _this = this;
    setTimeout(function() {
        _this.select();
    }, 10);
});

Can't create handler inside thread that has not called Looper.prepare()

Create Handler outside the Thread

final Handler handler = new Handler();

        new Thread(new Runnable() {
            @Override
            public void run() {
            try{
                 handler.post(new Runnable() {
                        @Override
                        public void run() {
                            showAlertDialog(p.getProviderName(), Token, p.getProviderId(), Amount);
                        }
                    });

                }
            }
            catch (Exception e){
                Log.d("ProvidersNullExp", e.getMessage());
            }
        }
    }).start();

Export to csv/excel from kibana

In Kibana 6.5, you can generate CSV under the Share Tab -> CSV Reports.

The request will be queued. Once the CSV is generated, it will be available for download under Management -> Reporting

Difference between "while" loop and "do while" loop

Probably wdlen starts with a value >=2, so in the second case the loop condition is initially false and the loop is never entered.

In the second case the loop body is executed before the wdlen<2 condition is checked for the first time, so the printf/scanf is executed at least once.

what's the easiest way to put space between 2 side-by-side buttons in asp.net

Try putting the following class on your second button

.div-button
{
    margin-left: 20px;
}

Edit:

If you want your first button to be spaced from the div as well as from the second button, then apply this class to your first button also.

Count number of columns in a table row

<table id="table1">
<tr>
  <td colspan=4><input type="text" value="" /></td>

</tr>
<tr>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>

</tr>
<table>
<script>
    var row=document.getElementById('table1').rows.length;
    for(i=0;i<row;i++){
    console.log('Row '+parseFloat(i+1)+' : '+document.getElementById('table1').rows[i].cells.length +' column');
    }
</script>

Result:

Row 1 : 1 column
Row 2 : 4 column

how to run or install a *.jar file in windows?

To run usually click and it should run, that is if you have java installed. If not get java from here Sorry thought it was more general open a command prompt and type java -jar jbpm-installer-3.2.7.jar