Programs & Examples On #Cffeed

Response::json() - Laravel 5.1

However, the previous answer could still be confusing for some programmers. Most especially beginners who are most probably using an older book or tutorial. Or perhaps you still feel the facade is needed. Sure you can use it. Me for one I still love to use the facade, this is because some times while building my api I forget to use the '\' before the Response.

if you are like me, simply add

   "use Response;"

above your class ...extends contoller. this should do.

with this you can now use:

$response = Response::json($posts, 200);

instead of:

$response = \Response::json($posts, 200);

Why Local Users and Groups is missing in Computer Management on Windows 10 Home?

Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.

You can use User Accounts by pressing Window+R, typing netplwiz and pressing OK as described here.

Remove Fragment Page from ViewPager in Android

The solution by Louth was not enough to get things working for me, as the existing fragments were not getting destroyed. Motivated by this answer, I found that the solution is to override the getItemId(int position) method of FragmentPagerAdapter to give a new unique ID whenever there has been a change in the expected position of a Fragment.

Source Code:

private class MyPagerAdapter extends FragmentPagerAdapter {

    private TextProvider mProvider;
    private long baseId = 0;

    public MyPagerAdapter(FragmentManager fm, TextProvider provider) {
        super(fm);
        this.mProvider = provider;
    }

    @Override
    public Fragment getItem(int position) {
        return MyFragment.newInstance(mProvider.getTextForPosition(position));
    }

    @Override
    public int getCount() {
        return mProvider.getCount();
    }


    //this is called when notifyDataSetChanged() is called
    @Override
    public int getItemPosition(Object object) {
        // refresh all fragments when data set changed
        return PagerAdapter.POSITION_NONE;
    }


    @Override
    public long getItemId(int position) {
        // give an ID different from position when position has been changed
        return baseId + position;
    }

    /**
     * Notify that the position of a fragment has been changed.
     * Create a new ID for each position to force recreation of the fragment
     * @param n number of items which have been changed
     */
    public void notifyChangeInPosition(int n) {
        // shift the ID returned by getItemId outside the range of all previous fragments
        baseId += getCount() + n;
    }
}

Now, for example if you delete a single tab or make some change to the order, you should call notifyChangeInPosition(1) before calling notifyDataSetChanged(), which will ensure that all the Fragments will be recreated.

Why this solution works

Overriding getItemPosition():

When notifyDataSetChanged() is called, the adapter calls the notifyChanged() method of the ViewPager which it is attached to. The ViewPager then checks the value returned by the adapter's getItemPosition() for each item, removing those items which return POSITION_NONE (see the source code) and then repopulating.

Overriding getItemId():

This is necessary to prevent the adapter from reloading the old fragment when the ViewPager is repopulating. You can easily understand why this works by looking at the source code for instantiateItem() in FragmentPagerAdapter.

    final long itemId = getItemId(position);

    // Do we already have this fragment?
    String name = makeFragmentName(container.getId(), itemId);
    Fragment fragment = mFragmentManager.findFragmentByTag(name);
    if (fragment != null) {
        if (DEBUG) Log.v(TAG, "Attaching item #" + itemId + ": f=" + fragment);
        mCurTransaction.attach(fragment);
    } else {
        fragment = getItem(position);
        if (DEBUG) Log.v(TAG, "Adding item #" + itemId + ": f=" + fragment);
        mCurTransaction.add(container.getId(), fragment,
                makeFragmentName(container.getId(), itemId));
    }

As you can see, the getItem() method is only called if the fragment manager finds no existing fragments with the same Id. To me it seems like a bug that the old fragments are still attached even after notifyDataSetChanged() is called, but the documentation for ViewPager does clearly state that:

Note this class is currently under early design and development. The API will likely change in later updates of the compatibility library, requiring changes to the source code of apps when they are compiled against the newer version.

So hopefully the workaround given here will not be necessary in a future version of the support library.

The type WebMvcConfigurerAdapter is deprecated

In Spring every request will go through the DispatcherServlet. To avoid Static file request through DispatcherServlet(Front contoller) we configure MVC Static content.

Spring 3.1. introduced the ResourceHandlerRegistry to configure ResourceHttpRequestHandlers for serving static resources from the classpath, the WAR, or the file system. We can configure the ResourceHandlerRegistry programmatically inside our web context configuration class.

  • we have added the /js/** pattern to the ResourceHandler, lets include the foo.js resource located in the webapp/js/ directory
  • we have added the /resources/static/** pattern to the ResourceHandler, lets include the foo.html resource located in the webapp/resources/ directory
@Configuration
@EnableWebMvc
public class StaticResourceConfiguration implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("WebMvcConfigurer - addResourceHandlers() function get loaded...");
        registry.addResourceHandler("/resources/static/**")
                .addResourceLocations("/resources/");

        registry
            .addResourceHandler("/js/**")
            .addResourceLocations("/js/")
            .setCachePeriod(3600)
            .resourceChain(true)
            .addResolver(new GzipResourceResolver())
            .addResolver(new PathResourceResolver());
    }
}

XML Configuration

<mvc:annotation-driven />
  <mvc:resources mapping="/staticFiles/path/**" location="/staticFilesFolder/js/"
                 cache-period="60"/>

Spring Boot MVC Static Content if the file is located in the WAR’s webapp/resources folder.

spring.mvc.static-path-pattern=/resources/static/**

How to duplicate sys.stdout to a log file?

I wrote a tee() implementation in Python that should work for most cases, and it works on Windows also.

https://github.com/pycontribs/tendo

Also, you can use it in combination with logging module from Python if you want.

Incorrect integer value: '' for column 'id' at row 1

To let MySql generate sequence numbers for an AUTO_INCREMENT field you have three options:

  1. specify list a column list and omit your auto_incremented column from it as njk suggested. That would be the best approach. See comments.
  2. explicitly assign NULL
  3. explicitly assign 0

3.6.9. Using AUTO_INCREMENT:

...No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

These three statements will produce the same result:

$insertQuery = "INSERT INTO workorders (`priority`, `request_type`) VALUES('$priority', '$requestType', ...)";
$insertQuery = "INSERT INTO workorders VALUES(NULL, '$priority', ...)";
$insertQuery = "INSERT INTO workorders VALUES(0, '$priority', ...";

Logical XOR operator in C++?

Here is how I think you write an XOR comparison in C++:

bool a = true;   // Test by changing to true or false
bool b = false;  // Test by changing to true or false
if (a == !b)     // THIS IS YOUR XOR comparison
{
    // do whatever
}

Proof

XOR TABLE
 a   b  XOR
--- --- ---
 T   T   F
 T   F   T
 F   T   T
 F   F   F

a == !b TABLE
 a   b  !b  a == !b
--- --- --- -------
 T   T   F     F
 T   F   T     T
 F   T   F     T
 F   F   T     F

The proof is that an exhaustive study of inputs and outputs shows that in the two tables, for every input set the result is always the identical in the two tables.

Therefore, the original question being how to write:

return (A==5) ^^ (B==5)

The answer would be

return (A==5) == !(B==5);

Or if you like, write

return !(A==5) == (B==5);

How to convert Set to Array?

In my case the solution was:

var testSet = new Set();
var testArray = [];

testSet.add("1");
testSet.add("2");
testSet.add("2"); // duplicate item
testSet.add("3");

var someFunction = function (value1, value2, setItself) {
    testArray.push(value1);
};

testSet.forEach(someFunction);

console.log("testArray: " + testArray);

value1 equals value2 => The value contained in the the current position in the Set. The same value is passed for both arguments

Worked under IE11.

$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST'

You can submit a form by hitting the enter key (i.e. without clicking the submit button) in most browsers but this does not necessarily send submit as a variable - so it is possible to submit an empty form i.e. $_POST will be empty but the form will still have generated a http post request to the php page. In this case if ($_SERVER['REQUEST_METHOD'] == 'POST') is better.

SQL Server : export query as a .txt file

You can use bcp utility.

To copy the result set from a Transact-SQL statement to a data file, use the queryout option. The following example copies the result of a query into the Contacts.txt data file. The example assumes that you are using Windows Authentication and have a trusted connection to the server instance on which you are running the bcp command. At the Windows command prompt, enter:

bcp "<your query here>" queryout Contacts.txt -c -T

You can use BCP by directly calling as operating sytstem command in SQL Agent job.

VB.Net Properties - Public Get, Private Set

If you are using VS2010 or later it is even easier than that

Public Property Name as String

You get the private properties and Get/Set completely for free!

see this blog post: Scott Gu's Blog

How to create a timer using tkinter?

Python3 clock example using the frame.after() rather than the top level application. Also shows updating the label with a StringVar()

#!/usr/bin/env python3

# Display UTC.
# started with https://docs.python.org/3.4/library/tkinter.html#module-tkinter

import tkinter as tk
import time

def current_iso8601():
    """Get current date and time in ISO8601"""
    # https://en.wikipedia.org/wiki/ISO_8601
    # https://xkcd.com/1179/
    return time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.now = tk.StringVar()
        self.time = tk.Label(self, font=('Helvetica', 24))
        self.time.pack(side="top")
        self.time["textvariable"] = self.now

        self.QUIT = tk.Button(self, text="QUIT", fg="red",
                                            command=root.destroy)
        self.QUIT.pack(side="bottom")

        # initial time display
        self.onUpdate()

    def onUpdate(self):
        # update displayed time
        self.now.set(current_iso8601())
        # schedule timer to call myself after 1 second
        self.after(1000, self.onUpdate)

root = tk.Tk()
app = Application(master=root)
root.mainloop()

How to make Regular expression into non-greedy?

The non-greedy regex modifiers are like their greedy counter-parts but with a ? immediately following them:

*  - zero or more
*? - zero or more (non-greedy)
+  - one or more
+? - one or more (non-greedy)
?  - zero or one
?? - zero or one (non-greedy)

apache server reached MaxClients setting, consider raising the MaxClients setting

When you use Apache with mod_php apache is enforced in prefork mode, and not worker. As, even if php5 is known to support multi-thread, it is also known that some php5 libraries are not behaving very well in multithreaded environments (so you would have a locale call on one thread altering locale on other php threads, for example).

So, if php is not running in cgi way like with php-fpm you have mod_php inside apache and apache in prefork mode. On your tests you have simply commented the prefork settings and increased the worker settings, what you now have is default values for prefork settings and some altered values for the shared ones :

StartServers       20
MinSpareServers    5
MaxSpareServers    10
MaxClients         1024
MaxRequestsPerChild  0

This means you ask apache to start with 20 process, but you tell it that, if there is more than 10 process doing nothing it should reduce this number of children, to stay between 5 and 10 process available. The increase/decrease speed of apache is 1 per minute. So soon you will fall back to the classical situation where you have a fairly low number of free available apache processes (average 2). The average is low because usually you have something like 5 available process, but as soon as the traffic grows they're all used, so there's no process available as apache is very slow in creating new forks. This is certainly increased by the fact your PHP requests seems to be quite long, they do not finish early and the apache forks are not released soon enough to treat another request.

See on the last graphic the small amount of green before the red peak? If you could graph this on a 1 minute basis instead of 5 minutes you would see that this green amount was not big enough to take the incoming traffic without any error message.

Now you set 1024 MaxClients. I guess the cacti graph are not taken after this configuration modification, because with such modification, when no more process are available, apache would continue to fork new children, with a limit of 1024 busy children. Take something like 20MB of RAM per child (or maybe you have a big memory_limit in PHP and allows something like 64MB or 256MB and theses PHP requests are really using more RAM), maybe a DB server... your server is now slowing down because you have only 768MB of RAM. Maybe when apache is trying to initiate the first 20 children you already reach the available RAM limit.

So. a classical way of handling that is to check the amount of memory used by an apache fork (make some top commands while it is running), then find how many parallel request you can handle with this amount of RAM (that mean parallel apache children in prefork mode). Let's say it's 12, for example. Put this number in apache mpm settings this way:

<IfModule prefork.c>
  StartServers       12
  MinSpareServers    12
  MaxSpareServers    12
  MaxClients         12
  MaxRequestsPerChild  300
</IfModule>

That means you do not move the number of fork while traffic increase or decrease, because you always want to use all the RAM and be ready for traffic peaks. The 300 means you recyclate each fork after 300 requests, it's better than 0, it means you will not have potential memory leaks issues. MaxClients is set to 12 25 or 50 which is more than 12 to handle the ListenBacklog queue, which can enqueue some requests, you may take a bigger queue, but you would get some timeouts maybe (removed this strange sentende, I can't remember why I said that, if more than 12 requests are incoming the next one will be pushed in the Backlog queue, but you should set MaxClient to your targeted number of processes).

And yes, that means you cannot handle more than 12 parallel requests.

If you want to handle more requests:

  • buy some more RAM
  • try to use apache in worker mode, but remove mod_php and use php as a parallel daemon with his own pooler settings (this is called php-fpm), connect it with fastcgi. Note that you will certainly need to buy some RAM to allow a big number of parallel php-fpm process, but maybe less than with mod_php
  • Reduce the time spent in your php process. From your cacti graphs you have to potential problems: a real traffic peak around 11:25-11:30 or some php code getting very slow. Fast requests will reduce the number of parallel requests.

If your problem is really traffic peaks, solutions could be available with caches, like a proxy-cache server. If the problem is a random slowness in PHP then... it's an application problem, do you do some HTTP query to another site from PHP, for example?

And finally, as stated by @Jan Vlcinsky you could try nginx, where php will only be available as php-fpm. If you cannot buy RAM and must handle a big traffic that's definitively desserve a test.

Update: About internal dummy connections (if it's your problem, but maybe not).

Check this link and this previous answer. This is 'normal', but if you do not have a simple virtualhost theses requests are maybe hitting your main heavy application, generating slow http queries and preventing regular users to acces your apache processes. They are generated on graceful reload or children managment.

If you do not have a simple basic "It works" default Virtualhost prevent theses requests on your application by some rewrites:

  RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
  RewriteRule .* - [F,L]

Update:

Having only one Virtualhost does not protect you from internal dummy connections, it is worst, you are sure now that theses connections are made on your unique Virtualhost. So you should really avoid side effects on your application by using the rewrite rules.

Reading your cacti graphics, it seems your apache is not in prefork mode bug in worker mode. Run httpd -l or apache2 -l on debian, and check if you have worker.c or prefork.c. If you are in worker mode you may encounter some PHP problems in your application, but you should check the worker settings, here is an example:

<IfModule worker.c>
  StartServers           3
  MaxClients           500
  MinSpareThreads       75
  MaxSpareThreads      250 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

You start 3 processes, each containing 25 threads (so 3*25=75 parallel requests available by default), you allow 75 threads doing nothing, as soon as one thread is used a new process is forked, adding 25 more threads. And when you have more than 250 threads doing nothing (10 processes) some process are killed. You must adjust theses settings with your memory. Here you allow 500 parallel process (that's 20 process of 25 threads). Your usage is maybe more:

<IfModule worker.c>
  StartServers           2
  MaxClients           250
  MinSpareThreads       50
  MaxSpareThreads      150 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

LaTeX source code listing like in professional books

Have a try on the listings package. Here is an example of what I used some time ago to have a coloured Java listing:

\usepackage{listings}

[...]

\lstset{language=Java,captionpos=b,tabsize=3,frame=lines,keywordstyle=\color{blue},commentstyle=\color{darkgreen},stringstyle=\color{red},numbers=left,numberstyle=\tiny,numbersep=5pt,breaklines=true,showstringspaces=false,basicstyle=\footnotesize,emph={label}}

[...]

\begin{lstlisting}
public void here() {
    goes().the().code()
}

[...]

\end{lstlisting}

You may want to customize that. There are several references of the listings package. Just google them.

Convert json data to a html table

You can use simple jQuery jPut plugin

http://plugins.jquery.com/jput/

<script>
$(document).ready(function(){

var json = [{"name": "name1","email":"[email protected]"},{"name": "name2","link":"[email protected]"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
    jsonData:json,
    //ajax_url:"youfile.json",  if you want to call from a json file
    name:"tbody_template",
});

});
</script>   

<table jput="t_template">
 <tbody jput="tbody_template">
     <tr>
         <td>{{name}}</td>
         <td>{{email}}</td>
     </tr>
 </tbody>
</table>

<table>
 <tbody id="tbody">
 </tbody>
</table>

How can I combine multiple rows into a comma-delimited list in Oracle?

In this example we are creating a function to bring a comma delineated list of distinct line level AP invoice hold reasons into one field for header level query:

 FUNCTION getHoldReasonsByInvoiceId (p_InvoiceId IN NUMBER) RETURN VARCHAR2

  IS

  v_HoldReasons   VARCHAR2 (1000);

  v_Count         NUMBER := 0;

  CURSOR v_HoldsCusror (p2_InvoiceId IN NUMBER)
   IS
     SELECT DISTINCT hold_reason
       FROM ap.AP_HOLDS_ALL APH
      WHERE status_flag NOT IN ('R') AND invoice_id = p2_InvoiceId;
BEGIN

  v_HoldReasons := ' ';

  FOR rHR IN v_HoldsCusror (p_InvoiceId)
  LOOP
     v_Count := v_COunt + 1;

     IF (v_Count = 1)
     THEN
        v_HoldReasons := rHR.hold_reason;
     ELSE
        v_HoldReasons := v_HoldReasons || ', ' || rHR.hold_reason;
     END IF;
  END LOOP;

  RETURN v_HoldReasons;
END; 

Commenting out a set of lines in a shell script

: || {
your code here
your code here
your code here
your code here
}

Where is the Keytool application?

If you have Android installed in windows, you will also find it here: C:\Program Files\Android\jdk\microsoft_dist_openjdk_1.8.0.25\jre\bin

Set folder for classpath

Use the command as

java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>

The above command will set the mentioned paths to classpath only once for executing the class named TestClass.

If you want to execute more then one classes, then you can follow this

set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"

After this you can execute as many classes as you want just by simply typing

java <your-class-name>

The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)

If you want to set the classpth only once so that it could work for everytime, then do as follows

1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
    a.  Variable Name-     classpath
    b.  Variable Value-    .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.

Remember this will work every time. You don't need to explicitly set the classpath again and again.

NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.

Hope this will help you.

alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

How do check if a parameter is empty or null in Sql Server stored procedure in IF statement?

Of course that works; when @item1 = N'', it IS NOT NULL.

You can define @item1 as NULL by default at the top of your stored procedure, and then not pass in a parameter.

No assembly found containing an OwinStartupAttribute Error

I deleted all DLLs from the branch which wasn't working, then I copied all DDls from my branch which was working to my branch wich wasn't. This solved the issue.

Mercurial — revert back to old version and continue from there

hg update [-r REV]

If later you commit, you will effectively create a new branch. Then you might continue working only on this branch or eventually merge the existing one into it.

How to clear APC cache entries?

A good solution for me was to simply not using the outdated user cache any more after deploy.

If you add prefix to each of you keys you can change the prefix on changing the data structure of cache entries. This will help you to get the following behavior on deploy:

  1. Don't use outdated cache entries after deploy of only updated structures
  2. Don't clean the whole cache on deploy to not slow down your page
  3. Some old cached entries can be reused after reverting your deploy (If the entries wasn't automatically removed already)
  4. APC will remove old cache entries after expire OR on missing cache space

This is possible for user cache only.

How can I use pickle to save a dict?

>>> import pickle
>>> with open("/tmp/picklefile", "wb") as f:
...     pickle.dump({}, f)
... 

normally it's preferable to use the cPickle implementation

>>> import cPickle as pickle
>>> help(pickle.dump)
Help on built-in function dump in module cPickle:

dump(...)
    dump(obj, file, protocol=0) -- Write an object in pickle format to the given file.

    See the Pickler docstring for the meaning of optional argument proto.

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

Refused to execute script, strict MIME type checking is enabled?

I accidentally named the js file .min instead of .min.js ...

How to save a data frame as CSV to a user selected location using tcltk

You need not to use even the package "tcltk". You can simply do as shown below:

write.csv(x, file = "c:\\myname\\yourfile.csv", row.names = FALSE)

Give your path inspite of "c:\myname\yourfile.csv".

How to cin to a vector

One-liner to read a fixed amount of numbers into a vector (C++11):

#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
#include <cstddef>

int main()
{
    const std::size_t LIMIT{5};
    std::vector<int> collection;

    std::generate_n(std::back_inserter(collection), LIMIT,
        []()
        {
            return *(std::istream_iterator<int>(std::cin));
        }
    );

    return 0;
}

How to use ng-repeat for dictionaries in AngularJs?

JavaScript developers tend to refer to the above data-structure as either an object or hash instead of a Dictionary.

Your syntax above is wrong as you are initializing the users object as null. I presume this is a typo, as the code should read:

// Initialize users as a new hash.
var users = {};
users["182982"] = "...";

To retrieve all the values from a hash, you need to iterate over it using a for loop:

function getValues (hash) {
    var values = [];
    for (var key in hash) {

        // Ensure that the `key` is actually a member of the hash and not
        // a member of the `prototype`.
        // see: http://javascript.crockford.com/code.html#for%20statement
        if (hash.hasOwnProperty(key)) {
            values.push(key);
        }
    }
    return values;
};

If you plan on doing a lot of work with data-structures in JavaScript then the underscore.js library is definitely worth a look. Underscore comes with a values method which will perform the above task for you:

var values = _.values(users);

I don't use Angular myself, but I'm pretty sure there will be a convenience method build in for iterating over a hash's values (ah, there we go, Artem Andreev provides the answer above :))

Importing CSV File to Google Maps

The easiest way to do this is generate a KML file (see http://code.google.com/apis/kml/articles/csvtokml.html for a possible solution). You can then open that up in Google Maps by storing it online and linking to it from Google Maps as described at http://code.google.com/apis/kml/documentation/whatiskml.html

EDIT: http://www.gpsbabel.org/ may let you do it without coding.

HTML combo box with option to type an entry

Given that the HTML datalist tag is still not fully supported, an alternate approach that I used is the Dojo Toolkit ComboBox. It was easier to implement and better documented than other options I've explored. It also plays nicely with existing frameworks. In my case, I added this combobox to an existing website that's based on Codeigniter and Bootstrap with no problems You just need to be sure to apply the Dojo theme (e.g. class="claro") to the combo's parent element instead of the body tag to avoid styling conflicts.

First, include the CSS for one of the Dojo themes (such as 'Claro'). It's important that the CSS file is included prior to the JS files below.

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/dojo/1.9.6/dijit/themes/claro/claro.css" />

Next, include jQuery and Dojo Toolkit via CDN

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.10.3/dojo/dojo.js"></script>

Next, you can just follow Dojo's sample code or use the sample below to get a working combobox.

<body>
    <!-- Dojo Dijit ComboBox with 'Claro' theme -->
    <div class="claro"><input id="item_name_1" class=""/></div>

    <script type="text/javascript">
        $(document).ready(function () {
            //In this example, dataStore is simply an array of JSON-encoded id/name pairs
            dataStore = [{"id":"43","name":"Domain Name Renewal"},{"id":"42","name":"Hosting Renewal"}];

            require(
                [ "dojo/store/Memory", "dijit/form/ComboBox", "dojo/domReady!"], 
                function (Memory, ComboBox) {
                    var stateStore = new Memory({
                        data: dataStore
                    });

                    var combo = new ComboBox({
                        id: "item_name_1",
                        name: "desc_1",
                        store: stateStore,
                        searchAttr: "name"},                        
                        "item_name_1"
                        ).startup();

                });

        });

    </script>
</body>

Pass multiple parameters to rest API - Spring

you can pass multiple params in url like

http://localhost:2000/custom?brand=dell&limit=20&price=20000&sort=asc

and in order to get this query fields , you can use map like

    @RequestMapping(method = RequestMethod.GET, value = "/custom")
    public String controllerMethod(@RequestParam Map<String, String> customQuery) {

        System.out.println("customQuery = brand " + customQuery.containsKey("brand"));
        System.out.println("customQuery = limit " + customQuery.containsKey("limit"));
        System.out.println("customQuery = price " + customQuery.containsKey("price"));
        System.out.println("customQuery = other " + customQuery.containsKey("other"));
        System.out.println("customQuery = sort " + customQuery.containsKey("sort"));

        return customQuery.toString();
    }

How can I change the color of a Google Maps marker?

Personally, I think the icons generated by the Google Charts API look great and are easy to customise dynamically.

See my answer on Google Maps API 3 - Custom marker color for default (dot) marker

Getting the current date in SQL Server?

SELECT CAST(GETDATE() AS DATE)

Returns the current date with the time part removed.

DATETIMEs are not "stored in the following format". They are stored in a binary format.

SELECT CAST(GETDATE() AS BINARY(8))

The display format in the question is independent of storage.

Formatting into a particular display format should be done by your application.

How to split (chunk) a Ruby array into parts of X elements?

If you're using rails you can also use in_groups_of:

foo.in_groups_of(3)

Ruby - ignore "exit" in code

One hackish way to define an exit method in context:

class Bar; def exit; end; end 

This works because exit in the initializer will be resolved as self.exit1. In addition, this approach allows using the object after it has been created, as in: b = B.new.

But really, one shouldn't be doing this: don't have exit (or even puts) there to begin with.

(And why is there an "infinite" loop and/or user input in an intiailizer? This entire problem is primarily the result of poorly structured code.)


1 Remember Kernel#exit is only a method. Since Kernel is included in every Object, then it's merely the case that exit normally resolves to Object#exit. However, this can be changed by introducing an overridden method as shown - nothing fancy.

How do I enable saving of filled-in fields on a PDF form?

With the latest version of Adobe Reader, Adobe Reader XI, it seems that you can save the form.

From their webpage: Type your responses right on the PDF form, or click through and fill in the form fields. Then save and submit

How can I get nth element from a list?

I'm not saying that there's anything wrong with your question or the answer given, but maybe you'd like to know about the wonderful tool that is Hoogle to save yourself time in the future: With Hoogle, you can search for standard library functions that match a given signature. So, not knowing anything about !!, in your case you might search for "something that takes an Int and a list of whatevers and returns a single such whatever", namely

Int -> [a] -> a

Lo and behold, with !! as the first result (although the type signature actually has the two arguments in reverse compared to what we searched for). Neat, huh?

Also, if your code relies on indexing (instead of consuming from the front of the list), lists may in fact not be the proper data structure. For O(1) index-based access there are more efficient alternatives, such as arrays or vectors.

IntelliJ shortcut to show a popup of methods in a class that can be searched

Do Cmd+F12+Fn Key on mac in IntelliJ if clicking Cmd+F12 starts.

Preloading @font-face fonts?

As I found the best way is doing is preloading a stylesheet that contains the font face, and then let browser to load it automatically. I used the font-face in other locations (in the html page), but then I could observe the font changing effect briefly.

<link href="fonts.css?family=Open+Sans" rel="preload stylesheet" as="style">

then in the font.css file, specify as following.

@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 400;
  src: local('Open Sans Regular'), local('OpenSans-Regular'),
       url('open-sans-v16-latin-regular.woff2') format('woff2'); /*  Super Modern Browsers */
}

You can't assign a name to fonts when it's preloaded through link tag (correct me if I was wrong I couldn't find a way yet), and thus you have to use font-face to assign the name to the font. Even though it's possible to load a font through link tag, it's not recommended as you can't assign a name to the font with it. Without a name as with font-face, you won't be able to use it anywhere in the web page. According to gtmetrix, style sheet loads at the beginning, then rest of the scripts/style by order, then the font before dom is loaded, and therefore you don't see font changing effect.

Unicode character in PHP string

PHP does not know these Unicode escape sequences. But as unknown escape sequences remain unaffected, you can write your own function that converts such Unicode escape sequences:

function unicodeString($str, $encoding=null) {
    if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
    return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', create_function('$match', 'return mb_convert_encoding(pack("H*", $match[1]), '.var_export($encoding, true).', "UTF-16BE");'), $str);
}

Or with an anonymous function expression instead of create_function:

function unicodeString($str, $encoding=null) {
    if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
    return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', function($match) use ($encoding) {
        return mb_convert_encoding(pack('H*', $match[1]), $encoding, 'UTF-16BE');
    }, $str);
}

Its usage:

$str = unicodeString("\u1000");

SQL Server FOR EACH Loop

[CREATE PROCEDURE [rat].[GetYear]

AS
BEGIN

-- variable for storing start date
Declare @StartYear as int
-- Variable for the End date 
Declare @EndYear as int 

-- Setting the value in strat Date
select @StartYear = Value from   rat.Configuration where Name = 'REPORT_START_YEAR'; 

-- Setting the End date 
select @EndYear = Value from   rat.Configuration where Name = 'REPORT_END_YEAR'; 


-- Creating Tem table 
    with [Years] as
    (
        --Selecting the Year
        select @StartYear [Year] 
        --doing Union 
        union all
         -- doing the loop in Years table 
         select Year+1 Year from [Years] where Year < @EndYear
     )
    --Selecting the Year table 
selec]

Transaction isolation levels relation with locks on table

As brb tea says, depends on the database implementation and the algorithm they use: MVCC or Two Phase Locking.

CUBRID (open source RDBMS) explains the idea of this two algorithms:

  • Two-phase locking (2PL)

The first one is when the T2 transaction tries to change the A record, it knows that the T1 transaction has already changed the A record and waits until the T1 transaction is completed because the T2 transaction cannot know whether the T1 transaction will be committed or rolled back. This method is called Two-phase locking (2PL).

  • Multi-version concurrency control (MVCC)

The other one is to allow each of them, T1 and T2 transactions, to have their own changed versions. Even when the T1 transaction has changed the A record from 1 to 2, the T1 transaction leaves the original value 1 as it is and writes that the T1 transaction version of the A record is 2. Then, the following T2 transaction changes the A record from 1 to 3, not from 2 to 4, and writes that the T2 transaction version of the A record is 3.

When the T1 transaction is rolled back, it does not matter if the 2, the T1 transaction version, is not applied to the A record. After that, if the T2 transaction is committed, the 3, the T2 transaction version, will be applied to the A record. If the T1 transaction is committed prior to the T2 transaction, the A record is changed to 2, and then to 3 at the time of committing the T2 transaction. The final database status is identical to the status of executing each transaction independently, without any impact on other transactions. Therefore, it satisfies the ACID property. This method is called Multi-version concurrency control (MVCC).

The MVCC allows concurrent modifications at the cost of increased overhead in memory (because it has to maintain different versions of the same data) and computation (in REPETEABLE_READ level you can't loose updates so it must check the versions of the data, like Hiberate does with Optimistick Locking).

In 2PL Transaction isolation levels control the following:

  • Whether locks are taken when data is read, and what type of locks are requested.

  • How long the read locks are held.

  • Whether a read operation referencing rows modified by another transaction:

    • Block until the exclusive lock on the row is freed.

    • Retrieve the committed version of the row that existed at the time the statement or transaction started.

    • Read the uncommitted data modification.

Choosing a transaction isolation level does not affect the locks that are acquired to protect data modifications. A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction. For read operations, transaction isolation levels primarily define the level of protection from the effects of modifications made by other transactions.

A lower isolation level increases the ability of many users to access data at the same time, but increases the number of concurrency effects, such as dirty reads or lost updates, that users might encounter.

Concrete examples of the relation between locks and isolation levels in SQL Server (use 2PL except on READ_COMMITED with READ_COMMITTED_SNAPSHOT=ON)

  • READ_UNCOMMITED: do not issue shared locks to prevent other transactions from modifying data read by the current transaction. READ UNCOMMITTED transactions are also not blocked by exclusive locks that would prevent the current transaction from reading rows that have been modified but not committed by other transactions. [...]

  • READ_COMMITED:

    • If READ_COMMITTED_SNAPSHOT is set to OFF (the default): uses shared locks to prevent other transactions from modifying rows while the current transaction is running a read operation. The shared locks also block the statement from reading rows modified by other transactions until the other transaction is completed. [...] Row locks are released before the next row is processed. [...]
    • If READ_COMMITTED_SNAPSHOT is set to ON, the Database Engine uses row versioning to present each statement with a transactionally consistent snapshot of the data as it existed at the start of the statement. Locks are not used to protect the data from updates by other transactions.
  • REPETEABLE_READ: Shared locks are placed on all data read by each statement in the transaction and are held until the transaction completes.

  • SERIALIZABLE: Range locks are placed in the range of key values that match the search conditions of each statement executed in a transaction. [...] The range locks are held until the transaction completes.

How to set TextView textStyle such as bold, italic

One way you can do is :

myTextView.setTypeface(null, Typeface.ITALIC);
myTextView.setTypeface(null, Typeface.BOLD_ITALIC);
myTextView.setTypeface(null, Typeface.BOLD);
myTextView.setTypeface(null, Typeface.NORMAL);

Another option if you want to keep the previous typeface and don't want to lose previously applied then:

myTextView.setTypeface(textView.getTypeface(), Typeface.NORMAL);      
myTextView.setTypeface(textView.getTypeface(), Typeface.BOLD);        
myTextView.setTypeface(textView.getTypeface(), Typeface.ITALIC);      
myTextView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC); 

MongoDB "root" user

"userAdmin is effectively the superuser role for a specific database. Users with userAdmin can grant themselves all privileges. However, userAdmin does not explicitly authorize a user for any privileges beyond user administration." from the link you posted

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

Wanted to share what caused the error in my case. Spend couple hours to figure this out, so hopefully it will help to save someone some time.

Strangely enough, the error was raised with the Enable drop directory quota setting being enabled for the domain.

enter image description here

I am not the expert and don't know the technical explanation, but unticking the mentioned setting sorted the problem.

ISO time (ISO 8601) in Python

I've developed this function:

def iso_8601_format(dt):
    """YYYY-MM-DDThh:mm:ssTZD (1997-07-16T19:20:30-03:00)"""

    if dt is None:
        return ""

    fmt_datetime = dt.strftime('%Y-%m-%dT%H:%M:%S')
    tz = dt.utcoffset()
    if tz is None:
        fmt_timezone = "+00:00"
    else:
        fmt_timezone = str.format('{0:+06.2f}', float(tz.total_seconds() / 3600))

    return fmt_datetime + fmt_timezone

scp copy directory to another server with private key auth

or you can also do ( for pem file )

 scp -r -i file.pem [email protected]:/home/backup /home/user/Desktop/

Logical operators ("and", "or") in DOS batch

The IF statement does not support logical operators AND and OR. Cascading IF statements make an implicit conjunction:

IF Exist File1.Dat IF Exist File2.Dat GOTO FILE12_EXIST_LABEL

If File1.Dat and File2.Dat exist then jump to the label FILE12_EXIST_LABEL.

See also: IF /?

Get current value selected in dropdown using jQuery

You can try:

$("._someDropDown").val();

Select rows which are not present in other table

A.) The command is NOT EXISTS, you're missing the 'S'.

B.) Use NOT IN instead

SELECT ip 
  FROM login_log 
  WHERE ip NOT IN (
    SELECT ip
    FROM ip_location
  )
;

Access nested dictionary items via a list of keys?

Extending @DomTomCat and others' approach, these functional (ie, return modified data via deepcopy without affecting the input) setter and mapper works for nested dict and list.

setter:

def set_at_path(data0, keys, value):
    data = deepcopy(data0)
    if len(keys)>1:
        if isinstance(data,dict):
            return {k:(set_by_path(v,keys[1:],value) if k==keys[0] else v) for k,v in data.items()}
        if isinstance(data,list):
            return [set_by_path(x[1],keys[1:],value) if x[0]==keys[0] else x[1] for x in enumerate(data)]
    else:
        data[keys[-1]]=value
        return data

mapper:

def map_at_path(data0, keys, f):
    data = deepcopy(data0)
    if len(keys)>1:
        if isinstance(data,dict):
            return {k:(map_at_path(v,keys[1:],f) if k==keys[0] else v) for k,v in data.items()}
        if isinstance(data,list):
            return [map_at_path(x[1],keys[1:],f) if x[0]==keys[0] else x[1] for x in enumerate(data)]
    else:
        data[keys[-1]]=f(data[keys[-1]])
        return data

How to handle the new window in Selenium WebDriver using Java?

i was having some issues with windowhandle and tried this one. this one works good for me.

String parentWindowHandler = driver.getWindowHandle(); 
String subWindowHandler = null;

Set<String> handles = driver.getWindowHandles();
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
    subWindowHandler = iterator.next();
    driver.switchTo().window(subWindowHandler);

    System.out.println(subWindowHandler);
}


driver.switchTo().window(parentWindowHandler); 

ReferenceError: describe is not defined NodeJs

You can also do like this:

  var mocha = require('mocha')
  var describe = mocha.describe
  var it = mocha.it
  var assert = require('chai').assert

  describe('#indexOf()', function() {
    it('should return -1 when not present', function() {
      assert.equal([1,2,3].indexOf(4), -1)
    })
  })

Reference: http://mochajs.org/#require

Laravel Mail::send() sending to multiple to or bcc addresses

it works for me fine, if you a have string, then simply explode it first.

$emails = array();

Mail::send('emails.maintenance',$mail_params, function($message) use ($emails) {
    foreach ($emails as $email) {
        $message->to($email);
    }

    $message->subject('My Email');
});

Run ScrollTop with offset of element by ID

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

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

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

Image comparison - fast algorithm

My company has about 24million images come in from manufacturers every month. I was looking for a fast solution to ensure that the images we upload to our catalog are new images.

I want to say that I have searched the internet far and wide to attempt to find an ideal solution. I even developed my own edge detection algorithm.
I have evaluated speed and accuracy of multiple models. My images, which have white backgrounds, work extremely well with phashing. Like redcalx said, I recommend phash or ahash. DO NOT use MD5 Hashing or anyother cryptographic hashes. Unless, you want only EXACT image matches. Any resizing or manipulation that occurs between images will yield a different hash.

For phash/ahash, Check this out: imagehash

I wanted to extend *redcalx'*s post by posting my code and my accuracy.

What I do:

from PIL import Image
from PIL import ImageFilter
import imagehash

img1=Image.open(r"C:\yourlocation")
img2=Image.open(r"C:\yourlocation")
if img1.width<img2.width:
    img2=img2.resize((img1.width,img1.height))
else:
    img1=img1.resize((img2.width,img2.height))
img1=img1.filter(ImageFilter.BoxBlur(radius=3))
img2=img2.filter(ImageFilter.BoxBlur(radius=3))
phashvalue=imagehash.phash(img1)-imagehash.phash(img2)
ahashvalue=imagehash.average_hash(img1)-imagehash.average_hash(img2)
totalaccuracy=phashvalue+ahashvalue

Here are some of my results:

item1  item2  totalsimilarity
desk1  desk1       3
desk1  phone1     22
chair1 desk1      17
phone1 chair1     34

Hope this helps!

How does Django's Meta class work?

You are asking a question about two different things:

  1. Meta inner class in Django models:

    This is just a class container with some options (metadata) attached to the model. It defines such things as available permissions, associated database table name, whether the model is abstract or not, singular and plural versions of the name etc.

    Short explanation is here: Django docs: Models: Meta options

    List of available meta options is here: Django docs: Model Meta options

    For latest version of Django: Django docs: Model Meta options

  2. Metaclass in Python:

    The best description is here: What are metaclasses in Python?

How can I create directory tree in C++/Linux?

#include <sys/types.h>
#include <sys/stat.h>

int status;
...
status = mkdir("/tmp/a/b/c", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

From here. You may have to do separate mkdirs for /tmp, /tmp/a, /tmp/a/b/ and then /tmp/a/b/c because there isn't an equivalent of the -p flag in the C api. Be sure and ignore the EEXISTS errno while you're doing the upper level ones.

Should I use string.isEmpty() or "".equals(string)?

One thing you might want to consider besides the other issues mentioned is that isEmpty() was introduced in 1.6, so if you use it you won't be able to run the code on Java 1.5 or below.

Import pfx file into particular certificate store from command line

For Windows 10:

Import certificate to Trusted Root Certification Authorities for Current User:

certutil -f -user -p oracle -importpfx root "example.pfx"

Import certificate to Trusted People for Current User:

certutil -f -user -p oracle -importpfx TrustedPeople "example.pfx"

Import certificate to Trusted Root Certification Authorities on Local Machine:

certutil -f -user -p oracle -enterprise -importpfx root "example.pfx"

Import certificate to Trusted People on Local Machine:

certutil -f -user -p oracle -enterprise -importpfx TrustedPeople "example.pfx"

Adding days to a date in Java

Here is some simple code to give output as currentdate + D days = some 'x' date (future date):

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

Calendar c = Calendar.getInstance();    
c.add(Calendar.DATE, 5);
System.out.println(dateFormat.format(c.getTime()));

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I have encountered this error code when enumerating names and calling worksheet.get_Range(name). It seems to occur when the name does NOT apply to a range, in my case it is the name of a macro.

Java get last element of a collection

To avoid some of the problems mentioned above (not robust for nulls etc etc), to get first and last element in a list an approach could be

import java.util.List;

public static final <A> A getLastElement(List<A> list) {
    return list != null ? getElement(list, list.size() - 1) : null;
}

public static final <A> A getFirstElement(List<A> list) {
    return list != null ? getElement(list, 0) : null;
}   

private static final <A> A getElement(List<A> list, int pointer) {
    A res = null;
    if (list.size() > 0) {
        res = list.get(pointer);            
    }
    return res;
}

The convention adopted is that the first/last element of an empty list is null...

Copy folder recursively in Node.js

This is how I would do it personally:

function copyFolderSync(from, to) {
    fs.mkdirSync(to);
    fs.readdirSync(from).forEach(element => {
        if (fs.lstatSync(path.join(from, element)).isFile()) {
            fs.copyFileSync(path.join(from, element), path.join(to, element));
        } else {
            copyFolderSync(path.join(from, element), path.join(to, element));
        }
    });
}

It works for folders and files.

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

Given that neither time is going to be very accurate, one way to use setTimeout to be a little more accurate is to calculate how long the delay was since the last iteration, and then adjust the next iteration as appropriate. For example:

var myDelay = 1000;
var thisDelay = 1000;
var start = Date.now();

function startTimer() {    
    setTimeout(function() {
        // your code here...
        // calculate the actual number of ms since last time
        var actual = Date.now() - start;
        // subtract any extra ms from the delay for the next cycle
        thisDelay = myDelay - (actual - myDelay);
        start = Date.now();
        // start the timer again
        startTimer();
    }, thisDelay);
}

So the first time it'll wait (at least) 1000 ms, when your code gets executed, it might be a little late, say 1046 ms, so we subtract 46 ms from our delay for the next cycle and the next delay will be only 954 ms. This won't stop the timer from firing late (that's to be expected), but helps you to stop the delays from pilling up. (Note: you might want to check for thisDelay < 0 which means the delay was more than double your target delay and you missed a cycle - up to you how you want to handle that case).

Of course, this probably won't help you keep several timers in sync, in which case you might want to figure out how to control them all with the same timer.

So looking at your code, all your delays are a multiple of 500, so you could do something like this:

var myDelay = 500;
var thisDelay = 500;
var start = Date.now();
var beatCount = 0;

function startTimer() {    
    setTimeout(function() {
        beatCount++;
        // your code here...
        //code for the bass playing goes here  

        if (count%2 === 0) {
            //code for the chords playing goes here (every 1000 ms)
        }

        if (count%16) {
            //code for the drums playing goes here (every 8000 ms)
        }

        // calculate the actual number of ms since last time
        var actual = Date.now() - start;
        // subtract any extra ms from the delay for the next cycle
        thisDelay = myDelay - (actual - myDelay);
        start = Date.now();
        // start the timer again
        startTimer();
    }, thisDelay);
}

jquery toggle slide from left to right and back

Use this...

$('#cat_icon').click(function () {
    $('#categories').toggle("slow");
    //$('#cat_icon').hide();
});
$('.panel_title').click(function () {
    $('#categories').toggle("slow");
    //$('#cat_icon').show();
});

See this Example

Greetings.

Problems with a PHP shell script: "Could not open input file"

I know its stupid but in my case i was outside of my project folder i didn't have spark file.

How to start http-server locally

To start server locally paste the below code in package.json and run npm start in command line.

"scripts": { "start": "http-server -c-1 -p 8081" },

Transport endpoint is not connected

I have exactly the same problem. I haven't found a solution anywhere, but I have been able to fix it without rebooting by simply unmounting and remounting the mountpoint.

For your system the commands would be:

fusermount -uz /data
mount /data

The -z forces the unmount, which solved the need to reboot for me. You may need to do this as sudo depending on your setup. You may encounter the below error if the command does not have the required elevated permissions:

fusermount: entry for /data not found in /etc/mtab

I'm using Ubuntu 14.04 LTS, with the current version of mhddfs.

What does "connection reset by peer" mean?

It's fatal. The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake. This bypasses the normal half-closed state transition. I like this description:

"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur.

How to remove leading zeros using C#

This Regex let you avoid wrong result with digits which consits only from zeroes "0000" and work on digits of any length:

using System.Text.RegularExpressions;

/*
00123 => 123
00000 => 0
00000a => 0a
00001a => 1a
00001a => 1a
0000132423423424565443546546356546454654633333a => 132423423424565443546546356546454654633333a
*/

Regex removeLeadingZeroesReg = new Regex(@"^0+(?=\d)");
var strs = new string[]
{
    "00123",
    "00000",
    "00000a",
    "00001a",
    "00001a",
    "0000132423423424565443546546356546454654633333a",
};
foreach (string str in strs)
{
    Debug.Print(string.Format("{0} => {1}", str, removeLeadingZeroesReg.Replace(str, "")));
}

And this regex will remove leading zeroes anywhere inside string:

new Regex(@"(?<!\d)0+(?=\d)");
//  "0000123432 d=0 p=002 3?0574 m=600"
//     => "123432 d=0 p=2 3?574 m=600"

In git how is fetch different than pull and how is merge different than rebase?

Fetch vs Pull

Git fetch just updates your repo data, but a git pull will basically perform a fetch and then merge the branch pulled

What is the difference between 'git pull' and 'git fetch'?


Merge vs Rebase

from Atlassian SourceTree Blog, Merge or Rebase:

Merging brings two lines of development together while preserving the ancestry of each commit history.

In contrast, rebasing unifies the lines of development by re-writing changes from the source branch so that they appear as children of the destination branch – effectively pretending that those commits were written on top of the destination branch all along.

Also, check out Learn Git Branching, which is a nice game that has just been posted to HackerNews (link to post) and teaches a lot of branching and merging tricks. I believe it will be very helpful in this matter.

How to pass integer from one Activity to another?

In Sender Activity Side:

Intent passIntent = new Intent(getApplicationContext(), "ActivityName".class);
passIntent.putExtra("value", integerValue);
startActivity(passIntent);

In Receiver Activity Side:

int receiveValue = getIntent().getIntExtra("value", 0);

How to select option in drop down protractorjs e2e tests

We can create a custom DropDown class for this and add a method as:

async selectSingleValue(value: string) {
        await this.element.element(by.xpath('.//option[normalize-space(.)=\'' + value + '\']')).click();
    }

Also, to verify what value is currently selected, we can have:

async getSelectedValues() {
        return await this.element.$('option:checked').getText();
    }

Take nth column in a text file

If you are using structured data, this has the added benefit of not invoking an extra shell process to run tr and/or cut or something. ...

(Of course, you will want to guard against bad inputs with conditionals and sane alternatives.)

...
while read line ; 
do 
    lineCols=( $line ) ;
    echo "${lineCols[0]}"
    echo "${lineCols[1]}"
done < $myFQFileToRead ; 
...

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

I faced same problem and tried above solutions but none of them worked for me. Then I tried following steps and the problem was solved:

  • Go to the project properties.
  • Go to Java Build Path option.
  • Then add *.jar file as external jar.
  • Then go to the order and export option and select the libraries and jars of the project.
  • save the current changes and clean the project and run the project again.

Write a number with two decimal places SQL Server

try this

SELECT CONVERT(DECIMAL(10,2),YOURCOLUMN)

Issue with background color in JavaFX 8

Try this one in your css document,

-fx-background-color : #ffaadd;

or

-fx-base : #ffaadd; 

Also, you can set background color on your object with this code directly.

yourPane.setBackground(new Background(new BackgroundFill(Color.DARKGREEN, CornerRadii.EMPTY, Insets.EMPTY)));

How can I round down a number in Javascript?

You can try to use this function if you need to round down to a specific number of decimal places

function roundDown(number, decimals) {
    decimals = decimals || 0;
    return ( Math.floor( number * Math.pow(10, decimals) ) / Math.pow(10, decimals) );
}

examples

alert(roundDown(999.999999)); // 999
alert(roundDown(999.999999, 3)); // 999.999
alert(roundDown(999.999999, -1)); // 990

Comparing the contents of two files in Sublime Text

The Diff Option only appears if the files are in a folder that is part of a Project.

Than you can actually compare files natively right in Sublime Text.

Navigate to the folder containing them through Open Folder... or in a project Select the two files (ie, by holding Ctrl on Windows or ? on macOS) you want to compare in the sidebar Right click and select the Diff files... option.

Initialize a long in Java

  1. You should add L: long i = 12345678910L;.
  2. Yes.

BTW: it doesn't have to be an upper case L, but lower case is confused with 1 many times :).

How to get a path to the desktop for current user in C#?

 string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
 string extension = ".log";
 filePath += @"\Error Log\" + extension;
 if (!Directory.Exists(filePath))
 {
      Directory.CreateDirectory(filePath);
 }

github: server certificate verification failed

You can also disable SSL verification, (if the project does not require a high level of security other than login/password) by typing :

git config --global http.sslverify false

enjoy git :)

How to run single test method with phpunit?

Following command will execute exactly testSaveAndDrop test.

phpunit --filter '/::testSaveAndDrop$/' escalation/EscalationGroupTest.php

How to print out the method name and line number and conditionally disable NSLog?

It's easy to change your existing NSLogs to display line number and class from which they are called. Add one line of code to your prefix file:

#define NSLog(__FORMAT__, ...) NSLog((@"%s [Line %d] " __FORMAT__), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)

Java collections maintaining insertion order

Theres's a section in the O'Reilly Java Cookbook called "Avoiding the urge to sort" The question you should be asking is actually the opposite of your original question ... "Do we gain something by sorting?" It take a lot of effort to sort and maintain that order. Sure sorting is easy but it usually doesn't scale in most programs. If you're going to be handling thousands or tens of thousands of requests (insrt,del,get,etc) per second whether not you're using a sorted or non sorted data structure is seriously going to matter.

character count using jquery

Use .length to count number of characters, and $.trim() function to remove spaces, and replace(/ /g,'') to replace multiple spaces with just one. Here is an example:

   var str = "      Hel  lo       ";
   console.log(str.length); 
   console.log($.trim(str).length); 
   console.log(str.replace(/ /g,'').length); 

Output:

20
7
5

Source: How to count number of characters in a string with JQuery

What exactly is nullptr?

Also, do you have another example (beside the Wikipedia one) where nullptr is superior to good old 0?

Yes. It's also a (simplified) real-world example that occurred in our production code. It only stood out because gcc was able to issue a warning when crosscompiling to a platform with different register width (still not sure exactly why only when crosscompiling from x86_64 to x86, warns warning: converting to non-pointer type 'int' from NULL):

Consider this code (C++03):

#include <iostream>

struct B {};

struct A
{
    operator B*() {return 0;}
    operator bool() {return true;}
};

int main()
{
    A a;
    B* pb = 0;
    typedef void* null_ptr_t;
    null_ptr_t null = 0;

    std::cout << "(a == pb): " << (a == pb) << std::endl;
    std::cout << "(a == 0): " << (a == 0) << std::endl; // no warning
    std::cout << "(a == NULL): " << (a == NULL) << std::endl; // warns sometimes
    std::cout << "(a == null): " << (a == null) << std::endl;
}

It yields this output:

(a == pb): 1
(a == 0): 0
(a == NULL): 0
(a == null): 1

SQL - Select first 10 rows only?

Firebird:

SELECT FIRST 10 * FROM MYTABLE

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

I was on Windows when this problem appeared.

The error is strange because it happens before I could enter my username and my password. What if there was a cache or something like this? I dig it online and found this answer on gitlab's support forum:

I open "Control Panel => User Accounts => Manage your credentials => Windows Credentials" I found two for https://@github.com and one was the wrong user. I deleted it and on the next "git push" I was reprompted and provided the correct credentials and it worked! Some other notes - this could have happened with any git remote.

In the Windows Credentials, I found two GitLab entries for an old account. I remove both and now it works!

The panel:

enter image description here

Difference between INNER JOIN and LEFT SEMI JOIN

Tried in Hive and got the below output

table1

1,wqe,chennai,india

2,stu,salem,india

3,mia,bangalore,india

4,yepie,newyork,USA

table2

1,wqe,chennai,india

2,stu,salem,india

3,mia,bangalore,india

5,chapie,Los angels,USA

Inner Join

SELECT * FROM table1 INNER JOIN table2 ON (table1.id = table2.id);

1 wqe chennai india 1 wqe chennai india

2 stu salem india 2 stu salem india

3 mia bangalore india 3 mia bangalore india

Left Join

SELECT * FROM table1 LEFT JOIN table2 ON (table1.id = table2.id);

1 wqe chennai india 1 wqe chennai india

2 stu salem india 2 stu salem india

3 mia bangalore india 3 mia bangalore india

4 yepie newyork USA NULL NULL NULL NULL

Left Semi Join

SELECT * FROM table1 LEFT SEMI JOIN table2 ON (table1.id = table2.id);

1 wqe chennai india

2 stu salem india

3 mia bangalore india

note: Only records in left table are displayed whereas for Left Join both the table records displayed

EC2 instance has no public DNS

After verifying VPC and Subnet settings, my EC2 instance still didn't have a public DNS. After a day of searching for a resolution, I finally figured it out.

I had to create a new Elastic IP address, then associate it to my instance.

From the EC2 Dashboard:

Go to Elastic IPs from the sidebar.

Click Allocate new address, then Allocate.

Go back to the EC2 Dashboard. Go to Network Interfaces.

Select the EC2 instance without a public DNS. Then Actions - Associate Address.

The Address field, select the new elastic IP address.

The Associate to private IP address field, select the private IP address with no public DNS.

Click Associate Address.

Your EC2 instance should now have a public DNS.

Styling JQuery UI Autocomplete

Are you looking for this selector?:

.ui-menu .ui-menu-item a{
    background:red;
    height:10px;
    font-size:8px;
}

Ugly demo:

http://jsfiddle.net/zeSTc/

Just replace with your code:

.ui-menu .ui-menu-item a{
    color: #96f226;
    border-radius: 0px;
    border: 1px solid #454545;
}

demo: http://jsfiddle.net/w5Dt2/

Convert a object into JSON in REST service by Spring MVC

Spring framework itself handles json conversion when controller is annotated properly.

For eg:

   @PutMapping(produces = {"application/json"})
        @ResponseBody
        public UpdateResponse someMethod(){ //do something
return UpdateResponseInstance;
}

Here spring internally converts the UpdateResponse object to corresponding json string and returns it. In order to do it spring internally uses Jackson library.

If you require a json representation of a model object anywhere apart from controller then you can use objectMapper provided by jackson. Model should be properly annotated for this to work.

Eg:

ObjectMapper mapper = new ObjectMapper();
SomeModelClass someModelObject = someModelRepository.findById(idValue).get();
mapper.writeValueAsString(someModelObject);

Read environment variables in Node.js

When using Node.js, you can retrieve environment variables by key from the process.env object:

for example

var mode   = process.env.NODE_ENV;
var apiKey = process.env.apiKey; // '42348901293989849243'

Here is the answer that will explain setting environment variables in node.js

How to click or tap on a TextView text

To click on a piece of the text (not the whole TextView), you can use Html or Linkify (both create links that open urls, though, not a callback in the app).

Linkify

Use a string resource like:

<string name="links">Here is a link: http://www.stackoverflow.com</string>

Then in a textview:

TextView textView = ...
textView.setText(R.string.links);
Linkify.addLinks(textView, Linkify.ALL);

Html

Using Html.fromHtml:

<string name="html">Here you can put html &lt;a href="http://www.stackoverflow.com"&gt;Link!&lt;/&gt;</string>

Then in your textview:

textView.setText(Html.fromHtml(getString(R.string.html)));

Team Build Error: The Path ... is already mapped to workspace

I couldn't get any other solution to work.

I had a new account created and the old account no longer had permissions (both on same machine).

I tried: 1) Deleting the workspace (couldn't see in VS with or without remote workspaces checked) 2) Deleting from the command line 3) New owner command 4) Deleting the cache

So I simply opened VS as admin and mapped to a different folder.

Git Push Error: insufficient permission for adding an object to repository database

This can easily happen if you ran git init with a different user from the one you are planning to use when pushing changes.

If you blindly follow the instructions on [1] this will happen as you probably created the git-user as root and then immediately moved on to git init without changing user in between.

[1] http://git-scm.com/book/en/Git-on-the-Server-Setting-Up-the-Server

Show DataFrame as table in iPython Notebook

It seems you can just display both dfs using a comma in between in display. I noticed this on some notebooks on github. This code is from Jake VanderPlas's notebook.

class display(object):
    """Display HTML representation of multiple objects"""
    template = """<div style="float: left; padding: 10px;">
    <p style='font-family:"Courier New", Courier, monospace'>{0}</p>{1}
    </div>"""
    def __init__(self, *args):
        self.args = args

    def _repr_html_(self):
        return '\n'.join(self.template.format(a, eval(a)._repr_html_())
                     for a in self.args)

    def __repr__(self):
        return '\n\n'.join(a + '\n' + repr(eval(a))
                       for a in self.args)

display('df', "df2")

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

You can solve that using display table.

Here is the updated JSFiddle that solves your problem.

CSS

.body {
    display: table;
    background-color: green;
}

.left-side {
    background-color: blue;
    float: none;
    display: table-cell;
    border: 1px solid;
}

.right-side {
    background-color: red;
    float: none;
    display: table-cell;
    border: 1px solid;
}

HTML

<div class="row body">
        <div class="col-xs-9 left-side">
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
        </div>
        <div class="col-xs-3 right-side">
            asdfdf
        </div>
    </div>

Search for exact match of string in excel row using VBA Macro

Use worksheet.find (worksheet is your worksheet) and use the row-range for its range-object. You can get the rangeobject like: worksheet.rows(rowIndex) as example

Then give find the required parameters it should find it for you fine. If I recall correctly, find returns the first match per default. I have no Excel at hand, so you have to look up find for yourself, sorry

I would advise against using a for-loop it is more fragile and ages slower than find.

Print the contents of a DIV

In Opera, try:

    print_win.document.write('</body></html>');
    print_win.document.close(); // This bit is important
    print_win.print();
    print_win.close();

Is there a Python equivalent of the C# null-coalescing operator?

Addionally to @Bothwells answer (which I prefer) for single values, in order to null-checking assingment of function return values, you can use new walrus-operator (since python3.8):

def test():
    return

a = 2 if (x:= test()) is None else x

Thus, test function does not need to be evaluated two times (as in a = 2 if test() is None else test())

How to add a new project to Github using VS Code

There is a nice GUI way to do this. Press CTRL+SHIFT+G ( or View-CSM in menu) and here you have a lot of options. With (...) you can do almost anything you want. After things be done, type your commit message into input box and press CTRL+ENTER. Pretty easy. If you have remote repo - you'll see a little spinner mark in bottom left corner near repo name. Press it and sync to remote easily.
But in order to do all of this you must have repo to be initialized in your working directory before (git init from terminal).

java.io.FileNotFoundException: the system cannot find the file specified

Relative paths can be used, but they can be tricky. The best solution is to know where your files are being saved, that is, print the folder:

import java.io.File;
import java.util.*;

public class Hangman1 {

    public static void main(String[] args) throws Exception {
        File myFile = new File("word.txt");
        System.out.println("Attempting to read from file in: "+myFile.getCanonicalPath());

        Scanner input = new Scanner(myFile);
        String in = "";
        in = input.nextLine();
    }

}

This code should print the folder where it is looking for. Place the file there and you'll be good to go.

Volley JsonObjectRequest Post request not working

try to use this helper class

import java.io.UnsupportedEncodingException;
import java.util.Map;    
import org.json.JSONException;
import org.json.JSONObject;    
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class CustomRequest extends Request<JSONObject> {

    private Listener<JSONObject> listener;
    private Map<String, String> params;

    public CustomRequest(String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    public CustomRequest(int method, String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return params;
    };

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        listener.onResponse(response);
    }
}

In activity/fragment do use this

RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params, this.createRequestSuccessListener(), this.createRequestErrorListener());

requestQueue.add(jsObjRequest);

Remove Duplicate objects from JSON Array

_x000D_
_x000D_
var standardsList = [_x000D_
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},_x000D_
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},_x000D_
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},_x000D_
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},_x000D_
    {"Grade": "Math K", "Domain": "Geometry"},_x000D_
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},_x000D_
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},_x000D_
    {"Grade": "Math 1", "Domain": "Orders of Operation"},_x000D_
    {"Grade": "Math 2", "Domain": "Geometry"},_x000D_
    {"Grade": "Math 2", "Domain": "Geometry"}_x000D_
];_x000D_
_x000D_
standardsList = standardsList.filter((li, idx, self) => self.map(itm => itm.Grade+itm.Domain).indexOf(li.Grade+li.Domain) === idx)_x000D_
_x000D_
document.write(JSON.stringify(standardsList))
_x000D_
_x000D_
_x000D_

here is a functional way of doing it that is much easier

standardsList = standardsList.filter((li, idx, self) => self.map(itm => iem.Grade+itm.domain).indexOf(li.Grade+li.domain) === idx)

pull access denied repository does not exist or may require docker login

This error message might possibly indicate something else.

In my case I defined another Docker-Image elsewhere from which the current Docker inherited its settings (docker-compos.yml):

FROM my_own_image:latest

The error message I got:

qohelet$ docker-compose up
Building web
Step 1/22 : FROM my_own_image:latest
ERROR: Service 'web' failed to build: pull access denied for my_own_image, repository does not exist or may require 'docker login'

Due to a reinstall the previous Docker were gone and I couldn't build my docker using docker-compose up with this command:

sudo docker build -t my_own_image:latest -f MyOwnImage.Dockerfile .

In your specific case you might have defined your own php-docker.

How to copy a map?

You have to manually copy each key/value pair to a new map. This is a loop that people have to reprogram any time they want a deep copy of a map.

You can automatically generate the function for this by installing mapper from the maps package using

go get -u github.com/drgrib/maps/cmd/mapper

and running

mapper -types string:aStruct

which will generate the file map_float_astruct.go containing not only a (deep) Copy for your map but also other "missing" map functions ContainsKey, ContainsValue, GetKeys, and GetValues:

func ContainsKeyStringAStruct(m map[string]aStruct, k string) bool {
    _, ok := m[k]
    return ok
}

func ContainsValueStringAStruct(m map[string]aStruct, v aStruct) bool {
    for _, mValue := range m {
        if mValue == v {
            return true
        }
    }

    return false
}

func GetKeysStringAStruct(m map[string]aStruct) []string {
    keys := []string{}

    for k, _ := range m {
        keys = append(keys, k)
    }

    return keys
}

func GetValuesStringAStruct(m map[string]aStruct) []aStruct {
    values := []aStruct{}

    for _, v := range m {
        values = append(values, v)
    }

    return values
}

func CopyStringAStruct(m map[string]aStruct) map[string]aStruct {
    copyMap := map[string]aStruct{}

    for k, v := range m {
        copyMap[k] = v
    }

    return copyMap
}

Full disclosure: I am the creator of this tool. I created it and its containing package because I found myself constantly rewriting these algorithms for the Go map for different type combinations.

Java Multithreading concept and join() method

My Comments:

When I see the output, the output is mixed with One, Two, Three which are the thread names and they run simultaneously. I am not sure when you say thread is not running by main method.

Not sure if I understood your question or not. But I m putting my answer what I could understand, hope it can help you.

1) Then you created the object, it called the constructor, in construct it has start method which started the thread and executed the contents written inside run() method.

So as you created 3 objects (3 threads - one, two, three), all 3 threads started executing simultaneously.

2) Join and Synchronization They are 2 different things, Synchronization is when there are multiple threads sharing a common resource and one thread should use that resource at a time. E.g. Threads such as DepositThread, WithdrawThread etc. do share a common object as BankObject. So while DepositThread is running, the WithdrawThread will wait if they are synchronized. wait(), notify(), notifyAll() are used for inter-thread communication. Plz google to know more.

about Join(), it is when multiple threads are running, but you join. e.g. if there are two thread t1 and t2 and in multi-thread env they run, the output would be: t1-0 t2-0 t1-1 t2-1 t1-2 t2-2

and we use t1.join(), it would be: t1-0 t1-1 t1-2 t2-0 t2-1 t2-2

This is used in realtime when sometimes you don't mix up the thread in certain conditions and one depends another to be completed (not in shared resource), so you can call the join() method.

Using union and order by clause in mysql

You can do this by adding a pseudo-column named rank to each select, that you can sort by first, before sorting by your other criteria, e.g.:

select *
from (
    select 1 as Rank, id, add_date from Table 
    union all
    select 2 as Rank, id, add_date from Table where distance < 5
    union all
    select 3 as Rank, id, add_date from Table where distance between 5 and 15
) a
order by rank, id, add_date desc

Possible to extend types in Typescript?

May be below approach will be helpful for someone TS with reactjs

interface Event {
   name: string;
   dateCreated: string;
   type: string;
}

interface UserEvent<T> extends Event<T> {
    UserId: string;
}

Difference between Git and GitHub

In simple way we can tell below are the difference between git and git hub and VSTS.

git: - Treat git as a engine/technology to achieve source version control to our project. Unlike TFS (again a centralized source version control ) git is distributed version control technology. That means git it actually does not mandate to have any server. Through git technology we can make our own local machine as a source code repository not required to have a centralized server always(in large scale it can have Microsoft server to push and keep our project source code). But with SVN and TFS kind version control, it is mandatory that a server be associated with it.

For example if I am a free-lance developer and I directly report to my client and there is no other developer involved, I need to keep version control of my code to roll back(any version) and commit my codes and I don't have budget to get a server and I don't have time to install and use other server in my machine as TFS server and TFS client. So, the optimal way is to install git engine and use my local machine as a repository for version controlling by git.

GitHub: - as I said previously git is a technology and used with some command / shell commands , ie git only doesn't have UI. GitHub is online product or online repository which uses git technology for their process and achieve version controls along with other functionalities like bug tracking,Project management, Support ticket management ..etc. In other words Git Hub is a wrapper build on git technology with a UI and other functionalities by other third party firm, it is actually a product owned by somebody or some group based on git technology , where as git is open source, and not marketable product.

VSTS : - VSTS is a Microsoft product for online repository keeping source version control which can be treated as an alternate to git hub. Since its of Microsoft , VSTS support both git technology and TFS(TFVC-team foundation version control). Because TFS is another old Microsoft product to achieve this version control.Gradually I assume VSTS will gradually dump TFS as git is the prominent technology in this area and it is open source.

Frontend tool to manage H2 database

There's a shell client built in too which is handy.

java -cp h2*.jar org.h2.tools.Shell

http://opensource-soa.blogspot.com.au/2009/03/how-to-use-h2-shell.html

$ java -cp h2.jar org.h2.tools.Shell -help
Interactive command line tool to access a database using JDBC.
Usage: java org.h2.tools.Shell <options>
Options are case sensitive. Supported options are:
[-help] or [-?]        Print the list of options
[-url "<url>"]         The database URL (jdbc:h2:...)
[-user <user>]         The user name
[-password <pwd>]      The password
[-driver <class>]      The JDBC driver class to use (not required in most cases)
[-sql "<statements>"]  Execute the SQL statements and exit
[-properties "<dir>"]  Load the server properties from this directory
If special characters don't work as expected, you may need to use
 -Dfile.encoding=UTF-8 (Mac OS X) or CP850 (Windows).
See also http://h2database.com/javadoc/org/h2/tools/Shell.html

error C2065: 'cout' : undeclared identifier

The code below compiles and runs properly for me using gcc. Try copy/pasting this and see if it works.

#include <iostream>
using namespace std;

int bob (int a) { cout << "hey" << endl; return 0; };

int main () {
    int a = 1;
    bob(a);
    return 0;
}

UIImage resize (Scale proportion)

That's ok not a big problem . thing is u got to find the proportional width and height

like if size is 2048.0 x 1360.0 which has to be resized to 320 x 480 resolution then the resulting image size should be 722.0 x 480.0

here is the formulae to do that . if w,h is original and x,y are resulting image.
w/h=x/y 
=> 
x=(w/h)*y;  

submitting w=2048,h=1360,y=480 => x=722.0 ( here width>height. if height>width then consider x to be 320 and calculate y)

U can submit in this web page . ARC

Confused ? alright , here is category for UIImage which will do the thing for you.

@interface UIImage (UIImageFunctions)
    - (UIImage *) scaleToSize: (CGSize)size;
    - (UIImage *) scaleProportionalToSize: (CGSize)size;
@end
@implementation UIImage (UIImageFunctions)

- (UIImage *) scaleToSize: (CGSize)size
{
    // Scalling selected image to targeted size
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, size.width, size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
    CGContextClearRect(context, CGRectMake(0, 0, size.width, size.height));

    if(self.imageOrientation == UIImageOrientationRight)
    {
        CGContextRotateCTM(context, -M_PI_2);
        CGContextTranslateCTM(context, -size.height, 0.0f);
        CGContextDrawImage(context, CGRectMake(0, 0, size.height, size.width), self.CGImage);
    }
    else
        CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), self.CGImage);

    CGImageRef scaledImage=CGBitmapContextCreateImage(context);

    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);

    UIImage *image = [UIImage imageWithCGImage: scaledImage];

    CGImageRelease(scaledImage);

    return image;
}

- (UIImage *) scaleProportionalToSize: (CGSize)size1
{
    if(self.size.width>self.size.height)
    {
        NSLog(@"LandScape");
        size1=CGSizeMake((self.size.width/self.size.height)*size1.height,size1.height);
    }
    else
    {
        NSLog(@"Potrait");
        size1=CGSizeMake(size1.width,(self.size.height/self.size.width)*size1.width);
    }

    return [self scaleToSize:size1];
}

@end

-- the following is appropriate call to do this if img is the UIImage instance.

img=[img scaleProportionalToSize:CGSizeMake(320, 480)];

How to have Java method return generic list of any type?

No need to even pass the class:

public <T> List<T> magicalListGetter() {
    return new ArrayList<T>();
}

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

You probably want to assign the lastname you are reading out here

lastname = sheet.cell(row=r, column=3).value

to something; currently the program just forgets it

you could do that two lines after, like so

unpaidMembers[name] = lastname, email

your program will still crash at the same place, because .items() still won't give you 3-tuples but rather something that has this structure: (name, (lastname, email))

good news is, python can handle this

for name, (lastname, email) in unpaidMembers.items():

etc.

Add JVM options in Tomcat

As Bhavik Shah says, you can do it in JAVA_OPTS, but the recommended way (as per catalina.sh) is to use CATALINA_OPTS:

#   CATALINA_OPTS   (Optional) Java runtime options used when the "start",
#                   "run" or "debug" command is executed.
#                   Include here and not in JAVA_OPTS all options, that should
#                   only be used by Tomcat itself, not by the stop process,
#                   the version command etc.
#                   Examples are heap size, GC logging, JMX ports etc.

#   JAVA_OPTS       (Optional) Java runtime options used when any command
#                   is executed.
#                   Include here and not in CATALINA_OPTS all options, that
#                   should be used by Tomcat and also by the stop process,
#                   the version command etc.
#                   Most options should go into CATALINA_OPTS.

IndentationError: unexpected indent error

The indentation is wrong, as the error tells you. As you can see, you have indented the code beginning with the indicated line too little to be in the for loop, but too much to be at the same level as the for loop. Python sees the lack of indentation as ending the for loop, then complains you have indented the rest of the code too much. (The def line I'm betting is just an artifact of how Stack Overflow wants you to format your code.)

Edit: Given your correction, I'm betting you have a mixture of tabs and spaces in the source file, such that it looks to the human eye like the code lines up, but Python considers it not to. As others have suggested, using only spaces is the recommended practice (see PEP 8). If you start Python with python -t, you will get warnings if there are mixed tabs and spaces in your code, which should help you pinpoint the issue.

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

Read/write files within a Linux kernel module

You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go "one level deeper" and call VFS level functions instead of the syscall handler directly:

Includes:

#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>

Opening a file (similar to open):

struct file *file_open(const char *path, int flags, int rights) 
{
    struct file *filp = NULL;
    mm_segment_t oldfs;
    int err = 0;

    oldfs = get_fs();
    set_fs(get_ds());
    filp = filp_open(path, flags, rights);
    set_fs(oldfs);
    if (IS_ERR(filp)) {
        err = PTR_ERR(filp);
        return NULL;
    }
    return filp;
}

Close a file (similar to close):

void file_close(struct file *file) 
{
    filp_close(file, NULL);
}

Reading data from a file (similar to pread):

int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_read(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}   

Writing data to a file (similar to pwrite):

int file_write(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_write(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}

Syncing changes a file (similar to fsync):

int file_sync(struct file *file) 
{
    vfs_fsync(file, 0);
    return 0;
}

[Edit] Originally, I proposed using file_fsync, which is gone in newer kernel versions. Thanks to the poor guy suggesting the change, but whose change was rejected. The edit was rejected before I could review it.

Difference between a virtual function and a pure virtual function

You can actually provide implementations of pure virtual functions in C++. The only difference is all pure virtual functions must be implemented by derived classes before the class can be instantiated.

How can I plot a confusion matrix?

@bninopaul 's answer is not completely for beginners

here is the code you can "copy and run"

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt

array = [[13,1,1,0,2,0],
         [3,9,6,0,1,0],
         [0,0,16,2,0,0],
         [0,0,0,13,0,0],
         [0,0,0,0,15,0],
         [0,0,1,0,0,15]]

df_cm = pd.DataFrame(array, range(6), range(6))
# plt.figure(figsize=(10,7))
sn.set(font_scale=1.4) # for label size
sn.heatmap(df_cm, annot=True, annot_kws={"size": 16}) # font size

plt.show()

result

Replacing blank values (white space) with NaN in pandas

This should work

df.loc[df.Variable == '', 'Variable'] = 'Value'

or

df.loc[df.Variable1 == '', 'Variable2'] = 'Value'

'Source code does not match the bytecode' when debugging on a device

You can created AVD, select API Level equal your tagetApi andr compileApi, it works for me.

how to make jni.h be found?

Above answers give you a hardcoded path solution. This is bad on so many levels (java version change, OS change, etc).

Cleaner solution is to add:

JAVA_HOME = $(shell dirname $$(readlink -f $$(which java))|sed 's^jre/bin^^')

near the top of your makefile, then add:

-I$(JAVA_HOME)/include

To your include flags.

I am posting this because I ran into the same problem and spent too much time googling for wrong answers (I am building an app on multiple platforms so the build environment needs to be transportable).

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

I added @Component annotation from import org.springframework.stereotype.Component and the problem was solved.

Terminal Commands: For loop with echo

By using jot:

jot -w "http://example.com/%d.jpg" 1000 1

How to configure Chrome's Java plugin so it uses an existing JDK in the machine

Starting with Version 42, released April 14, 2015, Chrome blocks all NPAPI plugins, including Java. Until September 2015 there will be a way around this, by going to chrome://flags/#enable-npapi and clicking on Enable. After that, you will have to use the IE tab extension to run the Direct-X version of the Java plugin.

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

[UPDATED privacy keys list to iOS 13 - see below]

There is a list of all Cocoa Keys that you can specify in your Info.plist file:

https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html

(Xcode: Target -> Info -> Custom iOS Target Properties)

iOS already required permissions to access microphone, camera, and media library earlier (iOS 6, iOS 7), but since iOS 10 app will crash if you don't provide the description why you are asking for the permission (it can't be empty).

Privacy keys with example description: cheatsheet

Source

Alternatively, you can open Info.plist as source code: source code

Source

And add privacy keys like this:

<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} always location use</string>

List of all privacy keys: [UPDATED to iOS 13]

NFCReaderUsageDescription
NSAppleMusicUsageDescription
NSBluetoothAlwaysUsageDescription
NSBluetoothPeripheralUsageDescription
NSCalendarsUsageDescription
NSCameraUsageDescription
NSContactsUsageDescription
NSFaceIDUsageDescription
NSHealthShareUsageDescription
NSHealthUpdateUsageDescription
NSHomeKitUsageDescription
NSLocationAlwaysUsageDescription
NSLocationUsageDescription
NSLocationWhenInUseUsageDescription
NSMicrophoneUsageDescription
NSMotionUsageDescription
NSPhotoLibraryAddUsageDescription
NSPhotoLibraryUsageDescription
NSRemindersUsageDescription
NSSiriUsageDescription
NSSpeechRecognitionUsageDescription
NSVideoSubscriberAccountUsageDescription

Update 2019:

In the last months, two of my apps were rejected during the review because the camera usage description wasn't specifying what I do with taken photos.

I had to change the description from ${PRODUCT_NAME} need access to the camera to take a photo to ${PRODUCT_NAME} need access to the camera to update your avatar even though the app context was obvious (user tapped on the avatar).

It seems that Apple is now paying even more attention to the privacy usage descriptions, and we should explain in details why we are asking for permission.

Windows batch - concatenate multiple text files into one

I am reiterating some of the other points already made, but including a 3rd example that helps when you have files across folders that you want to concatenate.

Example 1 (files in the same folder):

copy file1.txt+file2.txt+file3.txt file123.txt

Example 2 (files in same folder):

type *.txt > combined.txt

Example 3 (files exist across multiple folders, assumes newfileoutput.txt doesn't exist):

for /D %f in (folderName) DO type %f/filename.txt >> .\newfileoutput.txt

How do I get the APK of an installed app without root access?

Accessing /data/app is possible without root permission; the permissions on that directory are rwxrwx--x. Execute permission on a directory means you can access it, however lack of read permission means you cannot obtain a listing of its contents -- so in order to access it you must know the name of the file that you will be accessing. Android's package manager will tell you the name of the stored apk for a given package.

To do this from the command line, use adb shell pm list packages to get the list of installed packages and find the desired package.

With the package name, we can get the actual file name and location of the APK using adb shell pm path your-package-name.

And knowing the full directory, we can finally pull the adb using adb pull full/directory/of/the.apk

Credit to @tarn for pointing out that under Lollipop, the apk path will be /data/app/your-package-name-1/base.apk

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

We don't know what server.properties file is that, we neither know what SimocoPoolSize means (do you?)

Let's guess you are using some custom pool of database connections. Then, I guess the problem is that your pool is configured to open 100 or 120 connections, but you Postgresql server is configured to accept MaxConnections=90 . These seem conflictive settings. Try increasing MaxConnections=120.

But you should first understand your db layer infrastructure, know what pool are you using, if you really need so many open connections in the pool. And, specially, if you are gracefully returning the opened connections to the pool

How to get SLF4J "Hello World" working with log4j?

you need to add 3 dependency ( API+ API implementation + log4j dependency) 
Add also this 
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.5</version>
</dependency>

# And to see log in command line , set log4j.properties 

# Root logger option
log4j.rootLogger=INFO, file, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

#And to see log in file  , set log4j.properties 
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./logs/logging.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Trigger back-button functionality on button click in Android

If you need the exact functionality of the back button in your custom button, why not just call yourActivity.onBackPressed() that way if you override the functionality of the backbutton your custom button will behave the same.

'DataFrame' object has no attribute 'sort'

sort() was deprecated for DataFrames in favor of either:

sort() was deprecated (but still available) in Pandas with release 0.17 (2015-10-09) with the introduction of sort_values() and sort_index(). It was removed from Pandas with release 0.20 (2017-05-05).

Importing class/java files in Eclipse

You can import a bunch of .java files to your existing project without creating a new project. Here are the steps:

  1. Right-click on the Default Package in the Project Manager pane underneath your project and choose Import
  2. An Import Wizard window will display. Choose File system and select the Next button
  3. You are now prompted to choose a file
  4. Simply browse your folder with .java files in it
  5. Select desired .java files
  6. Click on Finish to finish the import wizard

Check the following webpage for more information: http://people.cs.uchicago.edu/~kaharris/10200/tutorials/eclipse/Step_04.html

Render HTML to an image

Use html2canvas just include plugin and call method to convert HTML to Canvas then download as image PNG

        html2canvas(document.getElementById("image-wrap")).then(function(canvas) {
            var link = document.createElement("a");
            document.body.appendChild(link);
            link.download = "manpower_efficiency.jpg";
            link.href = canvas.toDataURL();
            link.target = '_blank';
            link.click();
        });

Source: http://www.freakyjolly.com/convert-html-document-into-image-jpg-png-from-canvas/

Test class with a new() call in it with Mockito

    public class TestedClass {
    public LoginContext login(String user, String password) {
        LoginContext lc = new LoginContext("login", callbackHandler);
        lc.doThis();
        lc.doThat();
    }
  }

-- Test Class:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(TestedClass.class)
    public class TestedClassTest {

        @Test
        public void testLogin() {
            LoginContext lcMock = mock(LoginContext.class);
            whenNew(LoginContext.class).withArguments(anyString(), anyString()).thenReturn(lcMock);
//comment: this is giving mock object ( lcMock )
            TestedClass tc = new TestedClass();
            tc.login ("something", "something else"); ///  testing this method.
            // test the login's logic
        }
    }

When calling the actual method tc.login ("something", "something else"); from the testLogin() { - This LoginContext lc is set to null and throwing NPE while calling lc.doThis();

Remove all occurrences of a value from a list?

I believe this is probably faster than any other way if you don't care about the lists order, if you do take care about the final order store the indexes from the original and resort by that.

category_ids.sort()
ones_last_index = category_ids.count('1')
del category_ids[0:ones_last_index]

Linux: command to open URL in default browser

For opening a URL in the browser through the terminal, CentOS 7 users can use gio open command. For example, if you want to open google.com then gio open https://www.google.com will open google.com URL in the browser.

xdg-open https://www.google.com will also work but this tool has been deprecated, Use gio open instead. I prefer this as this is the easiest way to open a URL using a command from the terminal.

Getting the number of filled cells in a column (VBA)

If you want to find the last populated cell in a particular column, the best method is:

Range("A" & Rows.Count).End(xlUp).Row

This code uses the very last cell in the entire column (65536 for Excel 2003, 1048576 in later versions), and then find the first populated cell above it. This has the ability to ignore "breaks" in your data and find the true last row.

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

You will get like this error

error ss

Try the following steps

1. Open Command Prompt (Press Windows key and type "cmd" and hit Enter) Then type this command as show in picture

netstat -aon | find ":8080" | find "LISTENING" cmd command

  1. Now open Task Manager (Press Windows key and type "Task Manager" and hit Enter) In that, go to Details Tab and under PID Column, search for the number you found in cmd

task manager

  1. Right Click on that program and select end process

When do I need to use AtomicBoolean in Java?

When multiple threads need to check and change the boolean. For example:

if (!initialized) {
   initialize();
   initialized = true;
}

This is not thread-safe. You can fix it by using AtomicBoolean:

if (atomicInitialized.compareAndSet(false, true)) {
    initialize();
}

Add line break to ::after or ::before pseudo-element content

<p>Break sentence after the comma,<span class="mbr"> </span>in case of mobile version.</p>
<p>Break sentence after the comma,<span class="dbr"> </span>in case of desktop version.</p>

The .mbr and .dbr classes can simulate line-break behavior using CSS display:table. Useful if you want to replace real <br />.

Check out this demo Codepen: https://codepen.io/Marko36/pen/RBweYY,
and this post on responsive site use: Responsive line-breaks: simulate <br /> at given breakpoints.

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

This happened to me on Windows 7 and VS 2013 while viewing a project on the browser after build. I only had to close the browser "Chrome" then made sure that the port is not in use in my Network Activities using some utility (Kaspersky) then tried again and worked without any problems.

What is the difference between a JavaBean and a POJO?

Java beans are special type of POJOs.

Specialities listed below with reason

enter image description here

Can a CSV file have a comment?

I think the best way to add comments to a CSV file would be to add a "Comments" field or record right into the data.

Most CSV-parsing applications that I've used implement both field-mapping and record-choosing. So, to comment on the properties of a field, add a record just for field descriptions. To comment on a record, add a field at the end of it (well, all records, really) just for comments.

These are the only two reasons I can think of to comment a CSV file. But the only problem I can foresee would be programs that refuse to accept the file at all if any single record doesn't pass some validation rules. In that case, you'd have trouble writing a string-type field description record for any numeric fields.

I am by no means an expert, though, so feel free to point out any mistakes in my theory.

Proper way to initialize C++ structs

I write some test code:

#include <string>
#include <iostream>
#include <stdio.h>

using namespace std;

struct sc {
    int x;
    string y;
    int* z;
};

int main(int argc, char** argv)
{
   int* r = new int[128];
   for(int i = 0; i < 128; i++ ) {
        r[i] = i+32;
   }
   cout << r[100] << endl;
   delete r;

   sc* a = new sc;
   sc* aa = new sc[2];
   sc* b = new sc();
   sc* ba = new sc[2]();

   cout << "az:" << a->z << endl;
   cout << "bz:" << b->z << endl;
   cout << "a:" << a->x << " y" << a->y << "end" << endl;
   cout << "b:" << b->x << " y" << b->y <<  "end" <<endl;
   cout << "aa:" << aa->x << " y" << aa->y <<  "end" <<endl;
   cout << "ba:" << ba->x << " y" << ba->y <<  "end" <<endl;
}

g++ compile and run:

./a.out 
132
az:0x2b0000002a
bz:0
a:854191480 yend
b:0 yend
aa:854190968 yend
ba:0 yend

How to mention C:\Program Files in batchfile

Now that bash is out for windows 10, if you want to access program files from bash, you can do it like so: cd /mnt/c/Program\ Files.

How to layout multiple panels on a jFrame? (java)

You'll want to use a number of layout managers to help you achieve the basic results you want.

Check out A Visual Guide to Layout Managers for a comparision.

You could use a GridBagLayout but that's one of the most complex (and powerful) layout managers available in the JDK.

You could use a series of compound layout managers instead.

I'd place the graphics component and text area on a single JPanel, using a BorderLayout, with the graphics component in the CENTER and the text area in the SOUTH position.

I'd place the text field and button on a separate JPanel using a GridBagLayout (because it's the simplest I can think of to achieve the over result you want)

I'd place these two panels onto a third, master, panel, using a BorderLayout, with the first panel in the CENTER and the second at the SOUTH position.

But that's me

How to set a selected option of a dropdown list control using angular JS

I don't know if this will help anyone or not but as I was facing the same issue I thought of sharing how I got the solution.

You can use track by attribute in your ng-options.

Assume that you have:

variants:[{'id':0, name:'set of 6 traits'}, {'id':1, name:'5 complete sets'}]

You can mention your ng-options as:

ng-options="v.name for v in variants track by v.id"

Hope this helps someone in future.

Best C# API to create PDF

Update:

I'm not sure when or if the license changed for the iText# library, but it is licensed under AGPL which means it must be licensed if included with a closed-source product. The question does not (currently) require free or open-source libraries. One should always investigate the license type of any library used in a project.


I have used iText# with success in .NET C# 3.5; it is a port of the open source Java library for PDF generation and it's free.

There is a NuGet package available for iTextSharp version 5 and the official developer documentation, as well as C# examples, can be found at itextpdf.com

Open web in new tab Selenium + Python

Opening the new empty tab within same window in chrome browser is not possible up to my knowledge but you can open the new tab with web-link.

So far I surfed net and I got good working content on this question. Please try to follow the steps without missing.

import selenium.webdriver as webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get('https://www.google.com?q=python#q=python')
first_link = driver.find_element_by_class_name('l')

# Use: Keys.CONTROL + Keys.SHIFT + Keys.RETURN to open tab on top of the stack 
first_link.send_keys(Keys.CONTROL + Keys.RETURN)

# Switch tab to the new tab, which we will assume is the next one on the right
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

driver.quit()

I think this is better solution so far.

Credits: https://gist.github.com/lrhache/7686903

Fitting iframe inside a div

Based on the link provided by @better_use_mkstemp, here's a fiddle where nested iframe resizes to fill parent div: http://jsfiddle.net/orlenko/HNyJS/

Html:

<div id="content">
    <iframe src="http://www.microsoft.com" name="frame2" id="frame2" frameborder="0" marginwidth="0" marginheight="0" scrolling="auto" onload="" allowtransparency="false"></iframe>
</div>
<div id="block"></div>
<div id="header"></div>
<div id="footer"></div>

Relevant parts of CSS:

div#content {
    position: fixed;
    top: 80px;
    left: 40px;
    bottom: 25px;
    min-width: 200px;
    width: 40%;
    background: black;
}

div#content iframe {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100%;
    width: 100%;
}

Git - Pushing code to two remotes

To send to both remote with one command, you can create a alias for it:

git config alias.pushall '!git push origin devel && git push github devel'

With this, when you use the command git pushall, it will update both repositories.

document.body.appendChild(i)

It is working. Just modify to null check:

if(document.body != null){
    document.body.appendChild(element);
}

Pointy's suggestion is good; it may work, but I didn't try.

Invalid default value for 'dateAdded'

I solved mine by changing DATE to DATETIME

Windows shell command to get the full path to the current directory?

Based on the follow up question (store the data in a variable) in the comments to the chdir post I'm betting he wants to store the current path to restore it after changeing directories.

The original user should look at "pushd", which changes directory and pushes the current one onto a stack that can be restored with a "popd". On any modern Windows cmd shell that is the way to go when making batch files.

If you really need to grab the current path then modern cmd shells also have a %CD% variable that you can easily stuff away in another variable for reference.

encapsulation vs abstraction real world example

I feel like encapsulation may make more sense to discuss when you see HOW NOT TO DO in programming. For example, consider a Car class as below.

 class Car{
   public float speed =0;
   public boolean isReverse = false;
   public boolean isStarted = false;
 }

The client code may use above car class as below.

class Main{
  public static void main(args String[]){
   Car car = new Car();
   // No need to start??
   car.speed = 100; // Turbo mode directly to 100
   car.speed = 0; // Turbo break
  }
}

See more at: http://brevitaz.com/encapsulation-example-benefits-java/

This is uncontrolled access to car speed and other variables. By encapsulation, Car class can have complete control over how the data variables within car class can be modified.

Any concrete entity that has some behavior is example of Encapsulation. The behavior is provided by wrapping up something and hiding something from client.In case of mobile, it is signals, chips, circuits, battery and so on.

For abstraction of the same example - normal user may say I am ok with anything using which I can make calls and receive calls. This abstraction can be substituted by any concrete mobile. Check out Abstraction examples.

Auto-increment on partial primary key with Entity Framework Core

Annotate the property like below

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }

To use identity columns for all value-generated properties on a new model, simply place the following in your context's OnModelCreating():

builder.ForNpgsqlUseIdentityColumns();

This will create make all keys and other properties which have .ValueGeneratedOnAdd() have Identity by default. You can use ForNpgsqlUseIdentityAlwaysColumns() to have Identity always, and you can also specify identity on a property-by-property basis with UseNpgsqlIdentityColumn() and UseNpgsqlIdentityAlwaysColumn().

postgres efcore value generation

How to find common elements from multiple vectors?

intersect_all <- function(a,b,...){
  all_data <- c(a,b,...)
  require(plyr)
  count_data<- length(list(a,b,...))
  freq_dist <- count(all_data)
  intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"]
  intersect_data
}


intersect_all(a,b,c)

UPDATE EDIT A simpler code

intersect_all <- function(a,b,...){
  Reduce(intersect, list(a,b,...))
}

intersect_all(a,b,c)

How to set a maximum execution time for a mysql query?

pt_kill has an option for such. But it is on-demand, not continually monitoring. It does what @Rafa suggested. However see --sentinel for a hint of how to come close with cron.

How to find files modified in last x minutes (find -mmin does not work as expected)

To search for files in /target_directory and all its sub-directories, that have been modified in the last 60 minutes:

$ find /target_directory -type f -mmin -60

To find the most recently modified files, sorted in the reverse order of update time (i.e., the most recently updated files first):

$ find /etc -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort -r

Extracting columns from text file with different delimiters in Linux

You can use cut with a delimiter like this:

with space delim:

cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv

with tab delim:

cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv

I gave you the version of cut in which you can extract a list of intervals...

Hope it helps!

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

I made a Gist that should dynamically load jQuery if it isn't already loaded, and if the source fails, it proceeds onto fallbacks (stitched together from many answers): https://gist.github.com/tigerhawkvok/9673154

Please note I plan to keep the Gist updated but not this answer, for what it's worth!

/* See https://gist.github.com/tigerhawkvok/9673154 for the latest version */
function cascadeJQLoad(i) { // Use alternate CDNs where appropriate to load jQuery
    if (typeof(i) != "number") i = 0;
    // the actual paths to your jQuery CDNs
    var jq_paths = [
        "ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js",
        "ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.0.min.js"
    ];
    // Paths to your libraries that require jQuery
    var dependent_libraries = [
        "js/c.js"
    ];
    if (window.jQuery === undefined && i < jq_paths.length) {
        i++;
        loadJQ(jq_paths[i], i, dependent_libraries);
    }
    if (window.jQuery === undefined && i == jq_paths.length) {
        // jQuery failed to load
        // Insert your handler here
    }
}

/***
 * You shouldn't have to modify anything below here
 ***/

function loadJQ(jq_path, i, libs) { //load jQuery if it isn't already
    if (typeof(jq_path) == "undefined") return false;
    if (typeof(i) != "number") i = 1;
    var loadNextJQ = function() {
        var src = 'https:' == location.protocol ? 'https' : 'http';
        var script_url = src + '://' + jq_path;
        loadJS(script_url, function() {
            if (window.jQuery === undefined) cascadeJQLoad(i);
        });
    }
    window.onload = function() {
        if (window.jQuery === undefined) loadNextJQ();
        else {
            // Load libraries that rely on jQuery
            if (typeof(libs) == "object") {
                $.each(libs, function() {
                    loadJS(this.toString());
                });
            }
        }
    }
    if (i > 0) loadNextJQ();
}

function loadJS(src, callback) {
    var s = document.createElement('script');
    s.src = src;
    s.async = true;
    s.onreadystatechange = s.onload = function() {
        var state = s.readyState;
        try {
            if (!callback.done && (!state || /loaded|complete/.test(state))) {
                callback.done = true;
                callback();
            }
        } catch (e) {
            // do nothing, no callback function passed
        }
    };
    s.onerror = function() {
        try {
            if (!callback.done) {
                callback.done = true;
                callback();
            }
        } catch (e) {
            // do nothing, no callback function passed
        }
    }
    document.getElementsByTagName('head')[0].appendChild(s);
}

/*
 * The part that actually calls above
 */

if (window.readyState) { //older microsoft browsers
    window.onreadystatechange = function() {
        if (this.readyState == 'complete' || this.readyState == 'loaded') {
            cascadeJQLoad();
        }
    }
} else { //modern browsers
    cascadeJQLoad();
}

what is trailing whitespace and how can I handle this?

Trailing whitespace:

It is extra spaces (and tabs) at the end of line      
                                                 ^^^^^ here

Strip them:

#!/usr/bin/env python2
"""\
strip trailing whitespace from file
usage: stripspace.py <file>
"""

import sys

if len(sys.argv[1:]) != 1:
  sys.exit(__doc__)

content = ''
outsize = 0
inp = outp = sys.argv[1]
with open(inp, 'rb') as infile:
  content = infile.read()
with open(outp, 'wb') as output:
  for line in content.splitlines():
    newline = line.rstrip(" \t")
    outsize += len(newline) + 1
    output.write(newline + '\n')

print("Done. Stripped %s bytes." % (len(content)-outsize))

https://gist.github.com/techtonik/c86f0ea6a86ed3f38893

Parse JSON in TSQL

I seem to have a huge masochistic streak in that I've written a JSON parser. It converts a JSON document into a SQL Adjacency list table, which is easy to use to update your data tables. Actually, I've done worse, in that I've done code to do the reverse process, which is to go from a hierarchy table to a JSON string

The article and code is here: Consuming Json strings in SQL server.

Select * from parseJSON('{
  "Person":
  {
     "firstName": "John",
     "lastName": "Smith",
     "age": 25,
     "Address":
     {
        "streetAddress":"21 2nd Street",
        "city":"New York",
        "state":"NY",
        "postalCode":"10021"
     },
     "PhoneNumbers":
     {
        "home":"212 555-1234",
        "fax":"646 555-4567"
     }
  }
}
')

To get:

enter image description here

Best way to reset an Oracle sequence to the next value in an existing column?

Today, in Oracle 12c or newer, you probably have the column defined as GENERATED ... AS IDENTITY, and Oracle takes care of the sequence itself.

You can use an ALTER TABLE Statement to modify "START WITH" of the identity.

ALTER TABLE tbl MODIFY ("ID" NUMBER(13,0) GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 3580 NOT NULL ENABLE);

Bash mkdir and subfolders

FWIW,

Poor mans security folder (to protect a public shared folder from little prying eyes ;) )

mkdir -p {0..9}/{0..9}/{0..9}/{0..9}

Now you can put your files in a pin numbered folder. Not exactly waterproof, but it's a barrier for the youngest.

CSS word-wrapping in div

Setting just the width and float css properties would get a wrapping panel. The folowing example work just fine:

<div style="float:left; width: 250px">
Pellentesque feugiat tempor elit. Ut mollis lacinia quam. 
Sed pharetra, augue aliquam   ornare vestibulum, metus massa
laoreet tellus, eget iaculis lacus ipsum et diam. 
</div>

Maybe there are other styles in place that modify the appearance?

Resetting a setTimeout

clearTimeout() and feed the reference of the setTimeout, which will be a number. Then re-invoke it:

var initial;

function invocation() {
    alert('invoked')
    initial = window.setTimeout( 
    function() {
        document.body.style.backgroundColor = 'black'
    }, 5000);
}

invocation();

document.body.onclick = function() {
    alert('stopped')
    clearTimeout( initial )
    // re-invoke invocation()
}

In this example, if you don't click on the body element in 5 seconds the background color will be black.

Reference:

Note: setTimeout and clearTimeout are not ECMAScript native methods, but Javascript methods of the global window namespace.

Array.Add vs +=

When using the $array.Add()-method, you're trying to add the element into the existing array. An array is a collection of fixed size, so you will receive an error because it can't be extended.

$array += $element creates a new array with the same elements as old one + the new item, and this new larger array replaces the old one in the $array-variable

You can use the += operator to add an element to an array. When you use it, Windows PowerShell actually creates a new array with the values of the original array and the added value. For example, to add an element with a value of 200 to the array in the $a variable, type:

    $a += 200

Source: about_Arrays

+= is an expensive operation, so when you need to add many items you should try to add them in as few operations as possible, ex:

$arr = 1..3    #Array
$arr += (4..5) #Combine with another array in a single write-operation

$arr.Count
5

If that's not possible, consider using a more efficient collection like List or ArrayList (see the other answer).

Largest and smallest number in an array

Int[] number ={1,2,3,4,5,6,7,8,9,10};
Int? Result = null;
 foreach(Int i in number)

    {
       If(!Result.HasValue || i< Result)

        { 

            Result =i;
         }
     }

     Console.WriteLine(Result);
   }

Best PHP IDE for Mac? (Preferably free!)

Komodo is wonderful, and it runs on OS X; they have a free version, Komodo Edit.

UPDATE from 2015: I've switched to PHPStorm from Jetbrains, the same folks that built IntelliJ IDEA and Resharper. It's better. Not just better. It's well worth the money.

android edittext onchange listener

Anyone using ButterKnife. You can use like:

@OnTextChanged(R.id.zip_code)
void onZipCodeTextChanged(CharSequence zipCode, int start, int count, int after) {

}

Java getting the Enum name given the Enum Value

In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().

Using ForEach:

List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
            if(eachCategory.toString().equals("3")){
                String name = eachCategory.name();
            }
        });

Or, using Filter:

When you want to find with code:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

When you want to find with name:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

Hope it helps! I know this is a very old post, but someone can get help.

How to automatically indent source code?

Also, there's the handy little "increase indent" and "decrease indent" buttons. If you highlight a block of code and click those buttons the entire block will indent.

How to get config parameters in Symfony2 Twig Templates

You can also take advantage of the built-in Service Parameters system, which lets you isolate or reuse the value:

# app/config/parameters.yml
parameters:
    ga_tracking: UA-xxxxx-x

# app/config/config.yml
twig:
    globals:
        ga_tracking: "%ga_tracking%"

Now, the variable ga_tracking is available in all Twig templates:

<p>The google tracking code is: {{ ga_tracking }}</p>

The parameter is also available inside the controllers:

$this->container->getParameter('ga_tracking');

You can also define a service as a global Twig variable (Symfony2.2+):

# app/config/config.yml
twig:
    # ...
    globals:
        user_management: "@acme_user.user_management"

http://symfony.com/doc/current/templating/global_variables.html

If the global variable you want to set is more complicated - say an object - then you won't be able to use the above method. Instead, you'll need to create a Twig Extension and return the global variable as one of the entries in the getGlobals method.

Change the encoding of a file in Visual Studio Code

The existing answers show a possible solution for single files or file types. However, you can define the charset standard in VS Code by following this path:

File > Preferences > Settings > Encoding > Choose your option

This will define a character set as default. Besides that, you can always change the encoding in the lower right corner of the editor (blue symbol line) for the current project.

UIImage: Resize, then Crop

This question seems to have been put to rest, but in my quest for a solution that I could more easily understand (and written in Swift), I arrived at this (also posted to: How to crop the UIImage?)


I wanted to be able to crop from a region based on an aspect ratio, and scale to a size based on a outer bounding extent. Here is my variation:

import AVFoundation
import ImageIO

class Image {

    class func crop(image:UIImage, crop source:CGRect, aspect:CGSize, outputExtent:CGSize) -> UIImage {

        let sourceRect = AVMakeRectWithAspectRatioInsideRect(aspect, source)
        let targetRect = AVMakeRectWithAspectRatioInsideRect(aspect, CGRect(origin: CGPointZero, size: outputExtent))

        let opaque = true, deviceScale:CGFloat = 0.0 // use scale of device's main screen
        UIGraphicsBeginImageContextWithOptions(targetRect.size, opaque, deviceScale)

        let scale = max(
            targetRect.size.width / sourceRect.size.width,
            targetRect.size.height / sourceRect.size.height)

        let drawRect = CGRect(origin: -sourceRect.origin * scale, size: image.size * scale)
        image.drawInRect(drawRect)

        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return scaledImage
    }
}

There are a couple things that I found confusing, the separate concerns of cropping and resizing. Cropping is handled with the origin of the rect that you pass to drawInRect, and scaling is handled by the size portion. In my case, I needed to relate the size of the cropping rect on the source, to my output rect of the same aspect ratio. The scale factor is then output / input, and this needs to be applied to the drawRect (passed to drawInRect).

One caveat is that this approach effectively assumes that the image you are drawing is larger than the image context. I have not tested this, but I think you can use this code to handle cropping / zooming, but explicitly defining the scale parameter to be the aforementioned scale parameter. By default, UIKit applies a multiplier based on the screen resolution.

Finally, it should be noted that this UIKit approach is higher level than CoreGraphics / Quartz and Core Image approaches, and seems to handle image orientation issues. It is also worth mentioning that it is pretty fast, second to ImageIO, according to this post here: http://nshipster.com/image-resizing/

Proper MIME type for .woff2 fonts

font/woff2

For nginx add the following to the mime.types file:

font/woff2 woff2;


Old Answer

The mime type (sometime written as mimetype) for WOFF2 fonts has been proposed as application/font-woff2.

Also, if you refer to the spec (http://dev.w3.org/webfonts/WOFF2/spec/) you will see that font/woff2 is being discussed. I suspect that the filal mime type for all fonts will eventually be the more logical font/* (font/ttf, font/woff2 etc)...

N.B. WOFF2 is still in 'Working Draft' status -- not yet adopted officially.

Stop Chrome Caching My JS Files

When doing updates to my web applications I will either use a handler to return a single JS file to avoid the massive hits on my server, or add a small query string to them:

<script type="text/javascript" src="/mine/myscript?20111205"></script>

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.

Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload

How to provide password to a command that prompts for one in bash?

Secure commands will not allow this, and rightly so, I'm afraid - it's a security hole you could drive a truck through.

If your command does not allow it using input redirection, or a command-line parameter, or a configuration file, then you're going to have to resort to serious trickery.

Some applications will actually open up /dev/tty to ensure you will have a hard time defeating security. You can get around them by temporarily taking over /dev/tty (creating your own as a pipe, for example) but this requires serious privileges and even it can be defeated.

How to make the HTML link activated by clicking on the <li>?

Just to throw this option out there:

<ul id="menu">
    <a href="#"><li>Something1</li></a>
    <a href="#"><li>Something2</li></a>
    <a href="#"><li>Something3</li></a>
    <a href="#"><li>Something4</li></a>
</ul>

This is the style I use in my menus, it makes the list item itself a hyperlink (similar to how one would make an image a link).
For styling, I usually apply something like this:

nav ul a {
    color: inherit;
    text-decoration: none;
}

I can then apply whatever styling to the <li> that I wish.

Note: Validators will complain about this method, but if you're like me and do not base your life around them, this should work just fine.

Visualizing decision tree in scikit-learn

Alternatively, you could try using pydot for producing the png file from dot:

...
tree.export_graphviz(dtreg, out_file='tree.dot') #produces dot file

import pydot
dotfile = StringIO()
tree.export_graphviz(dtreg, out_file=dotfile)
pydot.graph_from_dot_data(dotfile.getvalue()).write_png("dtree2.png")
...

Can I run a 64-bit VMware image on a 32-bit machine?

You can if your processor is 64-bit and Virtualization Technology (VT) extension is enabled (it can be switched off in BIOS). You can't do it on 32-bit processor.

To check this under Linux you just need to look into /proc/cpuinfo file. Just look for the appropriate flag (vmx for Intel processor or svm for AMD processor)

egrep '(vmx|svm)' /proc/cpuinfo

To check this under Windows you need to use a program like CPU-Z which will display your processor architecture and supported extensions.

Is it possible to disable scrolling on a ViewPager

I created a Kotlin version based on converting this answer from Java: https://stackoverflow.com/a/13437997/8023278

There is no built in way to disable swiping between pages of a ViewPager, what's required is an extension of ViewPager that overrides onTouchEvent and onInterceptTouchEvent to prevent the swiping action. To make it more generalised we can add a method setSwipePagingEnabled to enable/disable swiping between pages.

class SwipeLockableViewPager(context: Context, attrs: AttributeSet): ViewPager(context, attrs) {
    private var swipeEnabled = false

    override fun onTouchEvent(event: MotionEvent): Boolean {
        return when (swipeEnabled) {
            true -> super.onTouchEvent(event)
            false -> false
        }
    }

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        return when (swipeEnabled) {
            true -> super.onInterceptTouchEvent(event)
            false -> false
        }
    }

    fun setSwipePagingEnabled(swipeEnabled: Boolean) {
        this.swipeEnabled = swipeEnabled
    }
}

Then in our layout xml we use our new SwipeLockableViewPager instead of the standard ViewPager

<mypackage.SwipeLockableViewPager 
        android:id="@+id/myViewPager" 
        android:layout_height="match_parent" 
        android:layout_width="match_parent" />

Now in our activity/fragment we can call myViewPager.setSwipePagingEnabled(false) and users won't be able to swipe between pages


UPDATE

As of 2020 we now have ViewPager2. If you migrate to ViewPager2 there is a built in method to disable swiping: myViewPager2.isUserInputEnabled = false

downcast and upcast

Upcasting (using (Employee)someInstance) is generally easy as the compiler can tell you at compile time if a type is derived from another.

Downcasting however has to be done at run time generally as the compiler may not always know whether the instance in question is of the type given. C# provides two operators for this - is which tells you if the downcast works, and return true/false. And as which attempts to do the cast and returns the correct type if possible, or null if not.

To test if an employee is a manager:

Employee m = new Manager();
Employee e = new Employee();

if(m is Manager) Console.WriteLine("m is a manager");
if(e is Manager) Console.WriteLine("e is a manager");

You can also use this

Employee someEmployee = e  as Manager;
    if(someEmployee  != null) Console.WriteLine("someEmployee (e) is a manager");

Employee someEmployee = m  as Manager;
    if(someEmployee  != null) Console.WriteLine("someEmployee (m) is a manager");

Select mySQL based only on month and year

Yeah this is working, but it returns one row only while there is several rows to retrieve using selected columns only. Like SELECT Title,Date FROM mytable WHERE YEAR(Date)=2017 AND MONTH(Date)=09 returns only one row.

matplotlib: how to change data points color based on some variable

If you want to plot lines instead of points, see this example, modified here to plot good/bad points representing a function as a black/red as appropriate:

def plot(xx, yy, good):
    """Plot data

    Good parts are plotted as black, bad parts as red.

    Parameters
    ----------
    xx, yy : 1D arrays
        Data to plot.
    good : `numpy.ndarray`, boolean
        Boolean array indicating if point is good.
    """
    import numpy as np
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    from matplotlib.colors import from_levels_and_colors
    from matplotlib.collections import LineCollection
    cmap, norm = from_levels_and_colors([0.0, 0.5, 1.5], ['red', 'black'])
    points = np.array([xx, yy]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lines = LineCollection(segments, cmap=cmap, norm=norm)
    lines.set_array(good.astype(int))
    ax.add_collection(lines)
    plt.show()

Ruby: Calling class method from instance

Here's an approach on how you might implement a _class method that works as self.class for this situation. Note: Do not use this in production code, this is for interest-sake :)

From: Can you eval code in the context of a caller in Ruby? and also http://rubychallenger.blogspot.com.au/2011/07/caller-binding.html

# Rabid monkey-patch for Object
require 'continuation' if RUBY_VERSION >= '1.9.0'
class Object
  def __; eval 'self.class', caller_binding; end
  alias :_class :__
  def caller_binding
    cc = nil; count = 0
    set_trace_func lambda { |event, file, lineno, id, binding, klass|
      if count == 2
        set_trace_func nil
        cc.call binding
      elsif event == "return"
        count += 1
      end
    }
    return callcc { |cont| cc = cont }
  end
end

# Now we have awesome
def Tiger
  def roar
    # self.class.roar
    __.roar
    # or, even
    _class.roar
  end
  def self.roar
    # TODO: tigerness
  end
end

Maybe the right answer is to submit a patch for Ruby :)

How can I set the background color of <option> in a <select> element?

_x000D_
_x000D_
select.list1 option.option2
{
    background-color: #007700;
}
_x000D_
<select class="list1">
  <option value="1">Option 1</option>
  <option value="2" class="option2">Option 2</option>
</select>
_x000D_
_x000D_
_x000D_

How to add parameters to an external data query in Excel which can't be displayed graphically?

Easy Workaround (no VBA required)

  1. Right Click Table, expand "Table" context manu, select "External Data Properties"
  2. Click button "Connection Properties" (labelled in tooltip only)
  3. Go-to Tab "Definition"

From here, edit the SQL directly by adding '?' wherever you want a parameter. Works the same way as before except you don't get nagged.