Programs & Examples On #Python embedding

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

Sounds like you need to change the path to your java executable to match the newest version. Basically, installing the latest Java does not necessarily mean your machine is configured to use the latest version. You didn't mention any platform details, so that's all I can say.

Python reshape list to ndim array

The answers above are good. Adding a case that I used. Just if you don't want to use numpy and keep it as list without changing the contents.

You can run a small loop and change the dimension from 1xN to Nx1.

    tmp=[]
    for b in bus:
        tmp.append([b])
    bus=tmp

It is maybe not efficient while in case of very large numbers. But it works for a small set of numbers. Thanks

How to center form in bootstrap 3

Wrap whatever you are trying to center around this div.

<div class="position-absolute top-50 start-50 translate-middle"></div>

https://getbootstrap.com/docs/5.0/utilities/position/

How can I shrink the drawable on a button?

  • Using "BATCH DRAWABLE IMPORT" feature you can import custom size depending upon your requirement example 20dp*20dp

    • Now after importing use the imported drawable_image as drawable_source for your button

    • It's simpler this way enter image description here

How to extract custom header value in Web API message handler?

var token = string.Empty;
if (Request.Headers.TryGetValue("MyKey",  out headerValues))
{
    token = headerValues.FirstOrDefault();
}

jQuery if statement, syntax

You can wrap jQuery calls inside normal JavaScript code. So, for example:

$(document).ready(function() {
    if (someCondition && someOtherCondition) {
        // Make some jQuery call.
    }
});

Exit/save edit to sudoers file? Putty SSH

#UBUNTU20

if you are opening this file as root, then type

root# visudo

the file will be opened, go to the line where you want to add/modifiy anything simply without any insert or i button pressed.

press ctrl + O
press ctrl + x
press enter

Facebook Graph API : get larger pictures in one request

You can use full_picture instead of picture key to get full size image.

Match line break with regular expression

By default . (any character) does not match newline characters.

This means you can simply match zero or more of any character then append the end tag.

Find: <li><a href="#">.* Replace: $0</a>

Decorators with parameters?

In case both the function and the decorator have to take arguments you can follow the below approach.

For example there is a decorator named decorator1 which takes an argument

@decorator1(5)
def func1(arg1, arg2):
    print (arg1, arg2)

func1(1, 2)

Now if the decorator1 argument has to be dynamic, or passed while calling the function,

def func1(arg1, arg2):
    print (arg1, arg2)


a = 1
b = 2
seconds = 10

decorator1(seconds)(func1)(a, b)

In the above code

  • seconds is the argument for decorator1
  • a, b are the arguments of func1

Jupyter notebook not running code. Stuck on In [*]

This is because when we run a loop until it's termination the Kernel is in busy state and so IN [*] is shown up. Since Kernel is busy and if we just leave that cell to execute completely and switch to another cell to run, the corresponding cell will get busy and so again for that cell IN[*] is shown. In that case you just need to restart your jupyter notebook and all is fine then.

But be sure that your loop will terminate this time or else again this error will turn up.

How to echo out the values of this array?

foreach ($array as $key => $val) {
   echo $val;
}

Is it possible to use global variables in Rust?

Look at the const and static section of the Rust book.

You can use something as follows:

const N: i32 = 5; 

or

static N: i32 = 5;

in global space.

But these are not mutable. For mutability, you could use something like:

static mut N: i32 = 5;

Then reference them like:

unsafe {
    N += 1;

    println!("N: {}", N);
}

How do I run a batch file from my Java Application?

The executable used to run batch scripts is cmd.exe which uses the /c flag to specify the name of the batch file to run:

Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c", "build.bat"});

Theoretically you should also be able to run Scons in this manner, though I haven't tested this:

Runtime.getRuntime().exec(new String[]{"scons", "-Q", "implicit-deps-changed", "build\file_load_type", "export\file_load_type"});

EDIT: Amara, you say that this isn't working. The error you listed is the error you'd get when running Java from a Cygwin terminal on a Windows box; is this what you're doing? The problem with that is that Windows and Cygwin have different paths, so the Windows version of Java won't find the scons executable on your Cygwin path. I can explain further if this turns out to be your problem.

ImportError: no module named win32api

The following should work:

pip install pywin32

But it didn't for me. I fixed this by downloading and installing the exe from here:

https://github.com/mhammond/pywin32/releases

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

How to wait for a number of threads to complete?

The join() was not helpful to me. see this sample in Kotlin:

    val timeInMillis = System.currentTimeMillis()
    ThreadUtils.startNewThread(Runnable {
        for (i in 1..5) {
            val t = Thread(Runnable {
                Thread.sleep(50)
                var a = i
                kotlin.io.println(Thread.currentThread().name + "|" + "a=$a")
                Thread.sleep(200)
                for (j in 1..5) {
                    a *= j
                    Thread.sleep(100)
                    kotlin.io.println(Thread.currentThread().name + "|" + "$a*$j=$a")
                }
                kotlin.io.println(Thread.currentThread().name + "|TaskDurationInMillis = " + (System.currentTimeMillis() - timeInMillis))
            })
            t.start()
        }
    })

The result:

Thread-5|a=5
Thread-1|a=1
Thread-3|a=3
Thread-2|a=2
Thread-4|a=4
Thread-2|2*1=2
Thread-3|3*1=3
Thread-1|1*1=1
Thread-5|5*1=5
Thread-4|4*1=4
Thread-1|2*2=2
Thread-5|10*2=10
Thread-3|6*2=6
Thread-4|8*2=8
Thread-2|4*2=4
Thread-3|18*3=18
Thread-1|6*3=6
Thread-5|30*3=30
Thread-2|12*3=12
Thread-4|24*3=24
Thread-4|96*4=96
Thread-2|48*4=48
Thread-5|120*4=120
Thread-1|24*4=24
Thread-3|72*4=72
Thread-5|600*5=600
Thread-4|480*5=480
Thread-3|360*5=360
Thread-1|120*5=120
Thread-2|240*5=240
Thread-1|TaskDurationInMillis = 765
Thread-3|TaskDurationInMillis = 765
Thread-4|TaskDurationInMillis = 765
Thread-5|TaskDurationInMillis = 765
Thread-2|TaskDurationInMillis = 765

Now let me use the join() for threads:

    val timeInMillis = System.currentTimeMillis()
    ThreadUtils.startNewThread(Runnable {
        for (i in 1..5) {
            val t = Thread(Runnable {
                Thread.sleep(50)
                var a = i
                kotlin.io.println(Thread.currentThread().name + "|" + "a=$a")
                Thread.sleep(200)
                for (j in 1..5) {
                    a *= j
                    Thread.sleep(100)
                    kotlin.io.println(Thread.currentThread().name + "|" + "$a*$j=$a")
                }
                kotlin.io.println(Thread.currentThread().name + "|TaskDurationInMillis = " + (System.currentTimeMillis() - timeInMillis))
            })
            t.start()
            t.join()
        }
    })

And the result:

Thread-1|a=1
Thread-1|1*1=1
Thread-1|2*2=2
Thread-1|6*3=6
Thread-1|24*4=24
Thread-1|120*5=120
Thread-1|TaskDurationInMillis = 815
Thread-2|a=2
Thread-2|2*1=2
Thread-2|4*2=4
Thread-2|12*3=12
Thread-2|48*4=48
Thread-2|240*5=240
Thread-2|TaskDurationInMillis = 1568
Thread-3|a=3
Thread-3|3*1=3
Thread-3|6*2=6
Thread-3|18*3=18
Thread-3|72*4=72
Thread-3|360*5=360
Thread-3|TaskDurationInMillis = 2323
Thread-4|a=4
Thread-4|4*1=4
Thread-4|8*2=8
Thread-4|24*3=24
Thread-4|96*4=96
Thread-4|480*5=480
Thread-4|TaskDurationInMillis = 3078
Thread-5|a=5
Thread-5|5*1=5
Thread-5|10*2=10
Thread-5|30*3=30
Thread-5|120*4=120
Thread-5|600*5=600
Thread-5|TaskDurationInMillis = 3833

As it's clear when we use the join:

  1. The threads are running sequentially.
  2. The first sample takes 765 Milliseconds while the second sample takes 3833 Milliseconds.

Our solution to prevent blocking other threads was creating an ArrayList:

val threads = ArrayList<Thread>()

Now when we want to start a new thread we most add it to the ArrayList:

addThreadToArray(
    ThreadUtils.startNewThread(Runnable {
        ...
    })
)

The addThreadToArray function:

@Synchronized
fun addThreadToArray(th: Thread) {
    threads.add(th)
}

The startNewThread funstion:

fun startNewThread(runnable: Runnable) : Thread {
    val th = Thread(runnable)
    th.isDaemon = false
    th.priority = Thread.MAX_PRIORITY
    th.start()
    return th
}

Check the completion of the threads as below everywhere it's needed:

val notAliveThreads = ArrayList<Thread>()
for (t in threads)
    if (!t.isAlive)
        notAliveThreads.add(t)
threads.removeAll(notAliveThreads)
if (threads.size == 0){
    // The size is 0 -> there is no alive threads.
}

UnicodeDecodeError, invalid continuation byte

Use this, If it shows the error of UTF-8

pd.read_csv('File_name.csv',encoding='latin-1')

Play an audio file using jQuery when a button is clicked

JSFiddle Demonstration

This is what I use with JQuery:

$('.button').on('click', function () { 
    var obj = document.createElement("audio");
        obj.src = "linktoyourfile.wav"; 
        obj.play(); 
});

Is it possible to set UIView border properties from interface builder?

Please add these 2 simple line of code:

self.YourViewName.layer.cornerRadius = 15
self.YourViewName.layer.masksToBounds = true

It will work fine.

Can't use WAMP , port 80 is used by IIS 7.5

goto services and stop the "World Wide Web Publishing Service" after restart the wamp server. after that start the "World Wide Web Publishing Service"

Difference between List, List<?>, List<T>, List<E>, and List<Object>

You're right: String is a subset of Object. Since String is more "precise" than Object, you should cast it to use it as an argument for System.out.println().

Generics in C#, using type of a variable as parameter

I'm not sure whether I understand your question correctly, but you can write your code in this way:

bool DoesEntityExist<T>(T instance, ....)

You can call the method in following fashion:

DoesEntityExist(myTypeInstance, ...)

This way you don't need to explicitly write the type, the framework will overtake the type automatically from the instance.

If Python is interpreted, what are .pyc files?

Machines don't understand English or any other languages, they understand only byte code, which they have to be compiled (e.g., C/C++, Java) or interpreted (e.g., Ruby, Python), the .pyc is a cached version of the byte code. https://www.geeksforgeeks.org/difference-between-compiled-and-interpreted-language/ Here is a quick read on what is the difference between compiled language vs interpreted language, TLDR is interpreted language does not require you to compile all the code before run time and thus most of the time they are not strict on typing etc.

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

I used the following on Mac OSX.

currDate=`date +%Y%m%d`
epochDate=$(date -j -f "%Y%m%d" "${currDate}" "+%s")

ProcessBuilder: Forwarding stdout and stderr of started processes without blocking the main thread

It's really surprising to me that the redirection methods in ProcessBuilder don't accept an OutputStream, only File. Yet another proof of forced boilerplate code that Java forces you to write.

That said, let's look at a list of comprehensive options:

  1. If you want the process output to simply be redirected to its parent's output stream, inheritIO will do the job.
  2. If you want the process output to go to a file, use redirect*(file).
  3. If you want the process output to go to a logger, you need to consume the process InputStream in a separate thread. See the answers that use a Runnable or CompletableFuture. You can also adapt the code below to do this.
  4. If you want to the process output to go to a PrintWriter, that may or may not be the stdout (very useful for testing), you can do the following:
static int execute(List<String> args, PrintWriter out) {
    ProcessBuilder builder = new ProcessBuilder()
            .command(args)
            .redirectErrorStream(true);
    Process process = null;
    boolean complete = false;
    try {
        process = builder.start();
        redirectOut(process.getInputStream(), out)
                .orTimeout(TIMEOUT, TimeUnit.SECONDS);
        complete = process.waitFor(TIMEOUT, TimeUnit.SECONDS);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } catch (InterruptedException e) {
        LOG.warn("Thread was interrupted", e);
    } finally {
        if (process != null && !complete) {
            LOG.warn("Process {} didn't finish within {} seconds", args.get(0), TIMEOUT);
            process = process.destroyForcibly();
        }
    }

    return process != null ? process.exitValue() : 1;
}

private static CompletableFuture<Void> redirectOut(InputStream in, PrintWriter out) {
    return CompletableFuture.runAsync(() -> {
        try (
                InputStreamReader inputStreamReader = new InputStreamReader(in);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader)
        ) {
            bufferedReader.lines()
                    .forEach(out::println);
        } catch (IOException e) {
            LOG.error("Failed to redirect process output", e);
        }
    });
}

Advantages of the code above over the other answers thus far:

  1. redirectErrorStream(true) redirects the error stream to the output stream, so that we only have to bother with one.
  2. CompletableFuture.runAsync runs from the ForkJoinPool. Note that this code doesn't block by calling get or join on the CompletableFuture but sets a timeout instead on its completion (Java 9+). There's no need for CompletableFuture.supplyAsync because there's nothing really to return from the method redirectOut.
  3. BufferedReader.lines is simpler than using a while loop.

Handling NULL values in Hive

Firstly — I don't think column1 is not NULL or column1 <> '' makes very much sense. Maybe you meant to write column1 is not NULL and column1 <> '' (AND instead of OR)?

Secondly — because of Hive's "schema on read" approach to table definitions, invalid values will be converted to NULL when you read from them. So, for example, if table1.column1 is of type STRING and table2.column1 is of type INT, then I don't think that table1.column1 IS NOT NULL is enough to guarantee that table2.column1 IS NOT NULL. (I'm not sure about this, though.)

TypeScript enum to object array

_x000D_
_x000D_
enum GoalProgressMeasurements {_x000D_
    Percentage = 1,_x000D_
    Numeric_Target = 2,_x000D_
    Completed_Tasks = 3,_x000D_
    Average_Milestone_Progress = 4,_x000D_
    Not_Measured = 5_x000D_
}_x000D_
    _x000D_
const array = []_x000D_
    _x000D_
for (const [key, value] of Object.entries(GoalProgressMeasurements)) {_x000D_
    if (!Number.isNaN(Number(key))) {_x000D_
        continue;_x000D_
    }_x000D_
_x000D_
    array.push({ id: value, name: key.replace('_', '') });_x000D_
}_x000D_
_x000D_
console.log(array);
_x000D_
_x000D_
_x000D_

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

In case anyone comes to this post and has a similar issue. I just experienced a similar problem, but the solution was quite simple.

A developer had mistakenly dropped a copy of the web.config into the CSS directory. Once deleted, all errors were resolved and the page properly displayed.

How to configure logging to syslog in Python?

From https://github.com/luismartingil/per.scripts/tree/master/python_syslog

#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
Implements a new handler for the logging module which uses the pure syslog python module.

@author:  Luis Martin Gil
@year: 2013
'''
import logging
import syslog

class SysLogLibHandler(logging.Handler):
    """A logging handler that emits messages to syslog.syslog."""
    FACILITY = [syslog.LOG_LOCAL0,
                syslog.LOG_LOCAL1,
                syslog.LOG_LOCAL2,
                syslog.LOG_LOCAL3,
                syslog.LOG_LOCAL4,
                syslog.LOG_LOCAL5,
                syslog.LOG_LOCAL6,
                syslog.LOG_LOCAL7]
    def __init__(self, n):
        """ Pre. (0 <= n <= 7) """
        try:
            syslog.openlog(logoption=syslog.LOG_PID, facility=self.FACILITY[n])
        except Exception , err:
            try:
                syslog.openlog(syslog.LOG_PID, self.FACILITY[n])
            except Exception, err:
                try:
                    syslog.openlog('my_ident', syslog.LOG_PID, self.FACILITY[n])
                except:
                    raise
        # We got it
        logging.Handler.__init__(self)

    def emit(self, record):
        syslog.syslog(self.format(record))

if __name__ == '__main__':
    """ Lets play with the log class. """
    # Some variables we need
    _id = 'myproj_v2.0'
    logStr = 'debug'
    logFacilityLocalN = 1

    # Defines a logging level and logging format based on a given string key.
    LOG_ATTR = {'debug': (logging.DEBUG,
                          _id + ' %(levelname)-9s %(name)-15s %(threadName)-14s +%(lineno)-4d %(message)s'),
                'info': (logging.INFO,
                         _id + ' %(levelname)-9s %(message)s'),
                'warning': (logging.WARNING,
                            _id + ' %(levelname)-9s %(message)s'),
                'error': (logging.ERROR,
                          _id + ' %(levelname)-9s %(message)s'),
                'critical': (logging.CRITICAL,
                             _id + ' %(levelname)-9s %(message)s')}
    loglevel, logformat = LOG_ATTR[logStr]

    # Configuring the logger
    logger = logging.getLogger()
    logger.setLevel(loglevel)

    # Clearing previous logs
    logger.handlers = []

    # Setting formaters and adding handlers.
    formatter = logging.Formatter(logformat)
    handlers = []
    handlers.append(SysLogLibHandler(logFacilityLocalN))
    for h in handlers:
        h.setFormatter(formatter)
        logger.addHandler(h)

    # Yep!
    logging.debug('test debug')
    logging.info('test info')
    logging.warning('test warning')
    logging.error('test error')
    logging.critical('test critical')

WebAPI to Return XML

You should simply return your object, and shouldn't be concerned about whether its XML or JSON. It is the client responsibility to request JSON or XML from the web api. For example, If you make a call using Internet explorer then the default format requested will be Json and the Web API will return Json. But if you make the request through google chrome, the default request format is XML and you will get XML back.

If you make a request using Fiddler then you can specify the Accept header to be either Json or XML.

Accept: application/xml

You may wanna see this article: Content Negotiation in ASP.NET MVC4 Web API Beta – Part 1

EDIT: based on your edited question with code:

Simple return list of string, instead of converting it to XML. try it using Fiddler.

public List<string> Get(int tenantID, string dataType, string ActionName)
    {
       List<string> SQLResult = MyWebSite_DataProvidor.DB.spReturnXMLData("SELECT * FROM vwContactListing FOR XML AUTO, ELEMENTS").ToList();
       return SQLResult;
     }

For example if your list is like:

List<string> list = new List<string>();
list.Add("Test1");
list.Add("Test2");
list.Add("Test3");
return list;

and you specify Accept: application/xml the output will be:

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
  <string>Test1</string>
  <string>Test2</string>
  <string>Test3</string>
</ArrayOfstring>

and if you specify 'Accept: application/json' in the request then the output will be:

[
  "Test1",
  "Test2",
  "Test3"
]

So let the client request the content type, instead of you sending the customized xml.

How to declare a variable in MySQL?

SET

SET @var_name = value 

OR

SET @var := value

both operators = and := are accepted


SELECT

SELECT col1, @var_name := col2 from tb_name WHERE "conditon";

if multiple record sets found only the last value in col2 is keep (override);

SELECT col1, col2 INTO @var_name, col3 FROM .....

in this case the result of select is not containing col2 values


Ex both methods used

-- TRIGGER_BEFORE_INSERT --- setting a column value from calculations

...
SELECT count(*) INTO @NR FROM a_table WHERE a_condition;
SET NEW.ord_col =  IFNULL( @NR, 0 ) + 1;
...

.trim() in JavaScript not working in IE

We can get official code From the internet! Refer this:

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

Running the following code before any other code will create trim() if it's not natively available.

if (!String.prototype.trim) {
  (function() {
    // Make sure we trim BOM and NBSP
    var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
    String.prototype.trim = function() {
      return this.replace(rtrim, '');
    };
  })();
}

for more: I just found there is js project for supporting EcmaScript 5: https://github.com/es-shims/es5-shim by reading the source code, we can get more knowledge about trim.

defineProperties(StringPrototype, {
 // http://blog.stevenlevithan.com/archives/faster-trim-javascript
 // http://perfectionkills.com/whitespace-deviations/
  trim: function trim() {
    if (typeof this === 'undefined' || this === null) {
      throw new TypeError("can't convert " + this + ' to object');
    }
    return String(this).replace(trimBeginRegexp, '').replace(trimEndRegexp, '');
  }
}, hasTrimWhitespaceBug);

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

I get such warning in following case:

1) file1 which contains <script type="text/javascript" src="/javascript/jquery-1.10.2.js"></script>. Page has input fields. I enter some value in input field and click button. Jquery sends input to external php file.

2) external php file also contains jquery and in the external php file i also included <script type="text/javascript" src="/javascript/jquery-1.10.2.js"></script>. Because if this i got the warning.

Removed <script type="text/javascript" src="/javascript/jquery-1.10.2.js"></script> from external php file and works without the warning.

As i understand on loading the first file (file1), i load jquery-1.10.2.js and as the page does not reloads (it sends data to external php file using jquery $.post), then jquery-1.10.2.js continue to exist. So not necessary again to load it.

How to apply style classes to td classes?

When using with a reactive bootstrap table, i did not find that the

table.classname td {

syntax worked as there was no <table> tag at all. Often modules like this don't use the outer tag but just dive right in maybe using <thead> and <tbody> for grouping at most.

Simply specifying like this worked great though

td.classname {
    max-width: 500px;
    text-overflow: initial;
    white-space: wrap;
    word-wrap: break-word;
}

as it directly overrides the <td> and can be used only on the elements you want to change. Maybe in your case use

thead.medium td {
  font-size: 40px; 
}
tbody.small td {
  font-size:25px;
}

for consistent font sizing with a bigger header.

How to close a Tkinter window by pressing a Button?

from tkinter import *

window = tk()
window.geometry("300x300")

def close_window (): 

    window.destroy()

button = Button ( text = "Good-bye", command = close_window)
button.pack()

window.mainloop()

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

Why doesn't Java allow overriding of static methods?

In Java (and many OOP languages, but I cannot speak for all; and some do not have static at all) all methods have a fixed signature - the parameters and types. In a virtual method, the first parameter is implied: a reference to the object itself and when called from within the object, the compiler automatically adds this.

There is no difference for static methods - they still have a fixed signature. However, by declaring the method static you have explicitly stated that the compiler must not include the implied object parameter at the beginning of that signature. Therefore, any other code that calls this must must not attempt to put a reference to an object on the stack. If it did do that, then the method execution would not work since the parameters would be in the wrong place - shifted by one - on the stack.

Because of this difference between the two; virtual methods always have a reference to the context object (i.e. this) so then it is possible to reference anything within the heap that belong to that instance of the object. But with static methods, since there is no reference passed, that method cannot access any object variables and methods since the context is not known.

If you wish that Java would change the definition so that a object context is passed in for every method, static or virtual, then you would in essence have only virtual methods.

As someone asked in a comment to the op - what is your reason and purpose for wanting this feature?

I do not know Ruby much, as this was mentioned by the OP, I did some research. I see that in Ruby classes are really a special kind of object and one can create (even dynamically) new methods. Classes are full class objects in Ruby, they are not in Java. This is just something you will have to accept when working with Java (or C#). These are not dynamic languages, though C# is adding some forms of dynamic. In reality, Ruby does not have "static" methods as far as I could find - in that case these are methods on the singleton class object. You can then override this singleton with a new class and the methods in the previous class object will call those defined in the new class (correct?). So if you called a method in the context of the original class it still would only execute the original statics, but calling a method in the derived class, would call methods either from the parent or sub-class. Interesting and I can see some value in that. It takes a different thought pattern.

Since you are working in Java, you will need to adjust to that way of doing things. Why they did this? Well, probably to improve performance at the time based on the technology and understanding that was available. Computer languages are constantly evolving. Go back far enough and there is no such thing as OOP. In the future, there will be other new ideas.

EDIT: One other comment. Now that I see the differences and as I Java/C# developer myself, I can understand why the answers you get from Java developers may be confusing if you are coming from a language like Ruby. Java static methods are not the same as Ruby class methods. Java developers will have a hard time understanding this, as will conversely those who work mostly with a language like Ruby/Smalltalk. I can see how this would also be greatly confusing by the fact that Java also uses "class method" as another way to talk about static methods but this same term is used differently by Ruby. Java does not have Ruby style class methods (sorry); Ruby does not have Java style static methods which are really just old procedural style functions, as found in C.

By the way - thanks for the question! I learned something new for me today about class methods (Ruby style).

How to stop flask application without using ctrl-c

Google Cloud VM instance + Flask App

I hosted my Flask Application on Google Cloud Platform Virtual Machine. I started the app using python main.py But the problem was ctrl+c did not work to stop the server.

This command $ sudo netstat -tulnp | grep :5000 terminates the server.

My Flask app runs on port 5000 by default.

Note: My VM instance is running on Linux 9.

It works for this. Haven't tested for other platforms. Feel free to update or comment if it works for other versions too.

How to check if number is divisible by a certain number?

n % x == 0

Means that n can be divided by x. So... for instance, in your case:

boolean isDivisibleBy20 = number % 20 == 0;

Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:

boolean even = (number & 1) == 0;
boolean odd  = (number & 1) != 0;

insert/delete/update trigger in SQL server

the am giving you is the code for trigger for INSERT, UPDATE and DELETE this works fine on Microsoft SQL SERVER 2008 and onwards database i am using is Northwind

/* comment section first create a table to keep track of Insert, Delete, Update
create table Emp_Audit(
                    EmpID int,
                    Activity varchar(20),
                    DoneBy varchar(50),
                    Date_Time datetime NOT NULL DEFAULT GETDATE()
                   );

select * from Emp_Audit*/

create trigger Employee_trigger
on Employees
after UPDATE, INSERT, DELETE
as
declare @EmpID int,@user varchar(20), @activity varchar(20);
if exists(SELECT * from inserted) and exists (SELECT * from deleted)
begin
    SET @activity = 'UPDATE';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from inserted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values (@EmpID,@activity,@user);
end

If exists (Select * from inserted) and not exists(Select * from deleted)
begin
    SET @activity = 'INSERT';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from inserted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end

If exists(select * from deleted) and not exists(Select * from inserted)
begin 
    SET @activity = 'DELETE';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from deleted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end

What does request.getParameter return?

Both if (one.length() > 0) {} and if (!"".equals(one)) {} will check against an empty foo parameter, and an empty parameter is what you'd get if the the form is submitted with no value in the foo text field.

If there's any chance you can use the Expression Language to handle the parameter, you could access it with empty param.foo in an expression.

<c:if test='${not empty param.foo}'>
    This page code gets rendered.
</c:if>

READ_EXTERNAL_STORAGE permission for Android

You have to ask for the permission at run time:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
        && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            REQUEST_PERMISSION);
    dialog.dismiss();
    return;
}

And in the callback below you can access the storage without a problem.

@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_PERMISSION) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission granted.
        } else {
            // User refused to grant permission.
        }
    }
}

How to copy a row and insert in same table with a autoincrement field in MySQL?

I was looking for the same feature but I don't use MySQL. I wanted to copy ALL the fields except of course the primary key (id). This was a one shot query, not to be used in any script or code.

I found my way around with PL/SQL but I'm sure any other SQL IDE would do. I did a basic

SELECT * 
FROM mytable 
WHERE id=42;

Then export it to a SQL file where I could find the

INSERT INTO table (col1, col2, col3, ... , col42) 
VALUES (1, 2, 3, ..., 42);

I just edited it and used it :

INSERT INTO table (col1, col2, col3, ... , col42) 
VALUES (mysequence.nextval, 2, 3, ..., 42);

jquery datatables default sort

This worked for me:

       jQuery('#tblPaging').dataTable({
            "sort": true,
            "pageLength": 20
        });

Select info from table where row has max date

You can use a window MAX() like this:

SELECT
  *, 
  max_date = MAX(date) OVER (PARTITION BY group)
FROM table

to get max dates per group alongside other data:

group  date      cash  checks  max_date
-----  --------  ----  ------  --------
1      1/1/2013  0     0       1/3/2013
2      1/1/2013  0     800     1/1/2013
1      1/3/2013  0     700     1/3/2013
3      1/1/2013  0     600     1/5/2013
1      1/2/2013  0     400     1/3/2013
3      1/5/2013  0     200     1/5/2013

Using the above output as a derived table, you can then get only rows where date matches max_date:

SELECT
  group,
  date,
  checks
FROM (
  SELECT
    *, 
    max_date = MAX(date) OVER (PARTITION BY group)
  FROM table
) AS s
WHERE date = max_date
;

to get the desired result.

Basically, this is similar to @Twelfth's suggestion but avoids a join and may thus be more efficient.

You can try the method at SQL Fiddle.

How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?

Option 1:

You can set CMake variables at command line like this:

cmake -D CMAKE_C_COMPILER="/path/to/your/c/compiler/executable" -D CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable" /path/to/directory/containing/CMakeLists.txt

See this to learn how to create a CMake cache entry.


Option 2:

In your shell script build_ios.sh you can set environment variables CC and CXX to point to your C and C++ compiler executable respectively, example:

export CC=/path/to/your/c/compiler/executable
export CXX=/path/to/your/cpp/compiler/executable
cmake /path/to/directory/containing/CMakeLists.txt

Option 3:

Edit the CMakeLists.txt file of "Assimp": Add these lines at the top (must be added before you use project() or enable_language() command)

set(CMAKE_C_COMPILER "/path/to/your/c/compiler/executable")
set(CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable")

See this to learn how to use set command in CMake. Also this is a useful resource for understanding use of some of the common CMake variables.


Here is the relevant entry from the official FAQ: https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

How do I tokenize a string sentence in NLTK?

As @PavelAnossov answered, the canonical answer, use the word_tokenize function in nltk:

from nltk import word_tokenize
sent = "This is my text, this is a nice way to input text."
word_tokenize(sent)

If your sentence is truly simple enough:

Using the string.punctuation set, remove punctuation then split using the whitespace delimiter:

import string
x = "This is my text, this is a nice way to input text."
y = "".join([i for i in x if not in string.punctuation]).split(" ")
print y

What is the difference between linear regression and logistic regression?

Simply put, linear regression is a regression algorithm, which outpus a possible continous and infinite value; logistic regression is considered as a binary classifier algorithm, which outputs the 'probability' of the input belonging to a label (0 or 1).

Using parameters in batch files at Windows command line

Use variables i.e. the .BAT variables and called %0 to %9

deleting folder from java

I wrote a method for this sometime back. It deletes the specified directory and returns true if the directory deletion was successful.

/**
 * Delets a dir recursively deleting anything inside it.
 * @param dir The dir to delete
 * @return true if the dir was successfully deleted
 */
public static boolean deleteDirectory(File dir) {
    if(! dir.exists() || !dir.isDirectory())    {
        return false;
    }

    String[] files = dir.list();
    for(int i = 0, len = files.length; i < len; i++)    {
        File f = new File(dir, files[i]);
        if(f.isDirectory()) {
            deleteDirectory(f);
        }else   {
            f.delete();
        }
    }
    return dir.delete();
}

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

When trying to translate Excel file with .xlsx suffix, you need to add additional jar, xmlbeansxxx.jar. xxxx is version, such as xmlbeans-2.3.0.jar

What's the fastest way to read a text file line-by-line?

If you're using .NET 4, simply use File.ReadLines which does it all for you. I suspect it's much the same as yours, except it may also use FileOptions.SequentialScan and a larger buffer (128 seems very small).

Cannot stop or restart a docker container

Enjoy

sudo aa-remove-unknown

This is what worked for me.

How to tell Jackson to ignore a field during serialization if its value is null?

If in Spring Boot, you can customize the jackson ObjectMapper directly through property files.

Example application.yml:

spring:
  jackson:
    default-property-inclusion: non_null # only include props if non-null

Possible values are:

always|non_null|non_absent|non_default|non_empty

More: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-customize-the-jackson-objectmapper

DropdownList DataSource

You can bind the DropDownList in different ways by using List, Dictionary, Enum, DataSet DataTable.
Main you have to consider three thing while binding the datasource of a dropdown.

  1. DataSource - Name of the dataset or datatable or your datasource
  2. DataValueField - These field will be hidden
  3. DataTextField - These field will be displayed on the dropdwon.

you can use following code to bind a dropdownlist to a datasource as a datatable:

  SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);

    SqlCommand cmd = new SqlCommand("Select * from tblQuiz", con);

    SqlDataAdapter da = new SqlDataAdapter(cmd);

    DataTable dt=new DataTable();
    da.Fill(dt);

    DropDownList1.DataTextField = "QUIZ_Name";
    DropDownList1.DataValueField = "QUIZ_ID"

    DropDownList1.DataSource = dt;
    DropDownList1.DataBind();

if you want to process on selection of dropdownlist, then you have to change AutoPostBack="true" you can use SelectedIndexChanged event to write your code.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    string strQUIZ_ID=DropDownList1.SelectedValue;
    string strQUIZ_Name=DropDownList1.SelectedItem.Text;
    // Your code..............
}

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

Your email session should be provided an authenticator instance as below

Session session = Session.getDefaultInstance(props,
    new Authenticator() {
        protected PasswordAuthentication  getPasswordAuthentication() {
        return new PasswordAuthentication(
                    "[email protected]", "password");
                }
    });

a complete example is here http://bharatonjava.wordpress.com/2012/08/27/sending-email-using-java-mail-api/

Launch an event when checking a checkbox in Angular2

You can use ngModel like

<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>

To update the checkbox state by updating the property checkboxValue in your code and when the checkbox is changed by the user addProp() is called.

Reusing output from last command in Bash

If you don't want to recompute the previous command you can create a macro that scans the current terminal buffer, tries to guess the -supposed- output of the last command, copies it to the clipboard and finally types it to the terminal.

It can be used for simple commands that return a single line of output (tested on Ubuntu 18.04 with gnome-terminal).

Install the following tools: xdootool, xclip , ruby

In gnome-terminal go to Preferences -> Shortcuts -> Select all and set it to Ctrl+shift+a.

Create the following ruby script:

cat >${HOME}/parse.rb <<EOF
#!/usr/bin/ruby
stdin = STDIN.read
d = stdin.split(/\n/)
e = d.reverse
f = e.drop_while { |item| item == "" }
g = f.drop_while { |item| item.start_with? "${USER}@" }
h = g[0] 
print h
EOF

In the keyboard settings add the following keyboard shortcut:

bash -c '/bin/sleep 0.3 ; xdotool key ctrl+shift+a ; xdotool key ctrl+shift+c ; ( (xclip -out | ${HOME}/parse.rb ) > /tmp/clipboard ) ; (cat /tmp/clipboard | xclip -sel clip ) ; xdotool key ctrl+shift+v '

The above shortcut:

  • copies the current terminal buffer to the clipboard
  • extracts the output of the last command (only one line)
  • types it into the current terminal

How to write a:hover in inline CSS?

I just figured out a different solution.

My issue: I have an <a> tag around some slides/main content viewer as well as <a> tags in the footer. I want them to go to the same place in IE, so the whole paragraph would be underlined onHover, even though they're not links: the slide as a whole is a link. IE doesn't know the difference. I also have some actual links in my footer that do need the underline and color change onHover. I thought I would have to put styles inline with the footer tags to make the color change, but advice from above suggests that this is impossible.

Solution: I gave the footer links two different classes, and my problem was solved. I was able to have the onHover color change in one class, have the slides onHover have no color change/underline, and still able to have the external HREFS in the footer and the slides at the same time!

No module named _sqlite3

It seems your makefile didn't include the appropriate .so file. You can correct this problem with the steps below:

  1. Install sqlite-devel (or libsqlite3-dev on some Debian-based systems)
  2. Re-configure and re-compiled Python with ./configure --enable-loadable-sqlite-extensions && make && sudo make install

Note

The sudo make install part will set that python version to be the system-wide standard, which can have unforseen consequences. If you run this command on your workstation, you'll probably want to have it installed alongside the existing python, which can be done with sudo make altinstall.

Generate sql insert script from excel worksheet

You can use the following excel statement:

="INSERT INTO table_name(`"&$A$1&"`,`"&$B$1&"`,`"&$C$1&"`, `"&$D$1&"`) VALUES('"&SUBSTITUTE(A2, "'", "\'")&"','"&SUBSTITUTE(B2, "'", "\'")&"','"&SUBSTITUTE(C2, "'", "\'")&"', "&D2&");"

This improves upon Hart CO's answer as it takes into account column names and gets rid of compile errors due to quotes in the column. The final column is an example of a numeric value column, without quotes.

How to get current CPU and RAM usage in Python?

I don't believe that there is a well-supported multi-platform library available. Remember that Python itself is written in C so any library is simply going to make a smart decision about which OS-specific code snippet to run, as you suggested above.

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

When you define a Foreign Key in table B referencing the Primary Key of table A it means that when a value is in B, it must be in A. This is to prevent unconsistent modifications to the tables.

In your example, your tables contain:

tblDomare with PRIMARY KEY (PersNR):

PersNR     |fNamn     |eNamn      |Erfarenhet
-----------|----------|-----------|----------
6811034679 |'Bengt'   |'Carlberg' |10
7606091347 |'Josefin' |'Backman'  |4
8508284163 |'Johanna' |'Backman'  |1
---------------------------------------------

tblBana:

BanNR
-----
1
2
3
-----

This statement:

ALTER TABLE tblDomare
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);

says that any line in tblDomare with key PersNR must have a correspondence in table tblBana on key BanNR. Your error is because you have lines inserted in tblDomare with no correspondence in tblBana.

2 solutions to fix your issue:

  • either add lines in tblBana with BanNR in (6811034679, 7606091347, 8508284163)
  • or remove all lines in tblDomare that have no correspondence in tblBana (but your table would be empty)

General advice: you should have the Foreign Key constraint before populating the tables. Foreign keys are here to prevent the user of the table from filling the tables with inconsistencies.

SQL Server Pivot Table with multiple column aggregates

I used your own pivot as a nested query and came to this result:

SELECT
  [sub].[chardate],
  SUM(ISNULL([Australia], 0)) AS [Transactions Australia],
  SUM(CASE WHEN [Australia] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Australia],
  SUM(ISNULL([Austria], 0)) AS [Transactions Austria],
  SUM(CASE WHEN [Austria] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Austria]
FROM
(
  select * 
  from  mytransactions
  pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
) AS [sub]
GROUP BY
  [sub].[chardate],
  [sub].[numericmonth]
ORDER BY 
  [sub].[numericmonth] ASC

Here is the Fiddle.

What does the star operator mean, in a function call?

One small point: these are not operators. Operators are used in expressions to create new values from existing values (1+2 becomes 3, for example. The * and ** here are part of the syntax of function declarations and calls.

How to manually install a pypi module without pip/easy_install?

Even though Sheena's answer does the job, pip doesn't stop just there.

From Sheena's answer:

  1. Download the package
  2. unzip it if it is zipped
  3. cd into the directory containing setup.py
  4. If there are any installation instructions contained in documentation contained herein, read and follow the instructions OTHERWISE
  5. type in python setup.py install

At the end of this, you'll end up with a .egg file in site-packages. As a user, this shouldn't bother you. You can import and uninstall the package normally. However, if you want to do it the pip way, you can continue the following steps.

In the site-packages directory,

  1. unzip <.egg file>
  2. rename the EGG-INFO directory as <pkg>-<version>.dist-info
  3. Now you'll see a separate directory with the package name, <pkg-directory>
  4. find <pkg-directory> > <pkg>-<version>.dist-info/RECORD
  5. find <pkg>-<version>.dist-info >> <pkg>-<version>.dist-info/RECORD. The >> is to prevent overwrite.

Now, looking at the site-packages directory, you'll never realize you installed without pip. To uninstall, just do the usual pip uninstall <pkg>.

Returning an empty array

You can return empty array by following two ways:

If you want to return array of int then

  1. Using {}:

    int arr[] = {};
    return arr;
    
  2. Using new int[0]:

    int arr[] = new int[0];
    return arr;
    

Same way you can return array for other datatypes as well.

Calculate difference in keys contained in two Python dictionaries

@Maxx has an excellent answer, use the unittest tools provided by Python:

import unittest


class Test(unittest.TestCase):
    def runTest(self):
        pass

    def testDict(self, d1, d2, maxDiff=None):
        self.maxDiff = maxDiff
        self.assertDictEqual(d1, d2)

Then, anywhere in your code you can call:

try:
    Test().testDict(dict1, dict2)
except Exception, e:
    print e

The resulting output looks like the output from diff, pretty-printing the dictionaries with + or - prepending each line that is different.

How do I get column datatype in Oracle with PL-SQL with low privileges?

ALL_TAB_COLUMNS should be queryable from PL/SQL. DESC is a SQL*Plus command.

SQL> desc all_tab_columns;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 OWNER                                     NOT NULL VARCHAR2(30)
 TABLE_NAME                                NOT NULL VARCHAR2(30)
 COLUMN_NAME                               NOT NULL VARCHAR2(30)
 DATA_TYPE                                          VARCHAR2(106)
 DATA_TYPE_MOD                                      VARCHAR2(3)
 DATA_TYPE_OWNER                                    VARCHAR2(30)
 DATA_LENGTH                               NOT NULL NUMBER
 DATA_PRECISION                                     NUMBER
 DATA_SCALE                                         NUMBER
 NULLABLE                                           VARCHAR2(1)
 COLUMN_ID                                          NUMBER
 DEFAULT_LENGTH                                     NUMBER
 DATA_DEFAULT                                       LONG
 NUM_DISTINCT                                       NUMBER
 LOW_VALUE                                          RAW(32)
 HIGH_VALUE                                         RAW(32)
 DENSITY                                            NUMBER
 NUM_NULLS                                          NUMBER
 NUM_BUCKETS                                        NUMBER
 LAST_ANALYZED                                      DATE
 SAMPLE_SIZE                                        NUMBER
 CHARACTER_SET_NAME                                 VARCHAR2(44)
 CHAR_COL_DECL_LENGTH                               NUMBER
 GLOBAL_STATS                                       VARCHAR2(3)
 USER_STATS                                         VARCHAR2(3)
 AVG_COL_LEN                                        NUMBER
 CHAR_LENGTH                                        NUMBER
 CHAR_USED                                          VARCHAR2(1)
 V80_FMT_IMAGE                                      VARCHAR2(3)
 DATA_UPGRADED                                      VARCHAR2(3)
 HISTOGRAM                                          VARCHAR2(15)

How to pass multiple parameters in a querystring

Query String: ?strID=XXXX&strName=yyyy&strDate=zzzzz

before you redirect:

string queryString = Request.QueryString.ToString();

Response.Redirect("page.aspx?"+queryString);

How to add one day to a date?

use DateTime object obj.Add to add what ever you want day hour and etc. Hope this works:)

How do you discover model attributes in Rails?

If you're just interested in the properties and data types from the database, you can use Model.inspect.

irb(main):001:0> User.inspect
=> "User(id: integer, email: string, encrypted_password: string,
 reset_password_token: string, reset_password_sent_at: datetime,
 remember_created_at: datetime, sign_in_count: integer,
 current_sign_in_at: datetime, last_sign_in_at: datetime,
 current_sign_in_ip: string, last_sign_in_ip: string, created_at: datetime,
 updated_at: datetime)"

Alternatively, having run rake db:create and rake db:migrate for your development environment, the file db/schema.rb will contain the authoritative source for your database structure:

ActiveRecord::Schema.define(version: 20130712162401) do
  create_table "users", force: true do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
end

How to launch another aspx web page upon button click?

This button post to the current page while at the same time opens OtherPage.aspx in a new browser window. I think this is what you mean with ...the original page and the newly launched page should both be launched.

<asp:Button ID="myBtn" runat="server" Text="Click me" 
     onclick="myBtn_Click" OnClientClick="window.open('OtherPage.aspx', 'OtherPage');" />

Batch file to run a command in cmd within a directory

Chain arbitrary commands using & like this:

command1 & command2 & command3 & ...

Thus, in your particular case, put this line in a batch file on your desktop:

START cmd.exe /k "cd C:\activiti-5.9\setup & ant demo.start"

You can also use && to chain commands, albeit this will perform error checking and the execution chain will break if one of the commands fails. The behaviour is detailed here.

Edit: Intrigued by @James K's comment "You CAN chain the commands, but they will have no effect", I tested some more and to my surprise discovered, that the program I was starting in my original test - firefox.exe - while not existing in a directory in the PATH environment variable, is actually executable anywhere on my system (which really made me wonder - see bottom of answer for explanation). So in fact executing...

START cmd.exe /k "cd C:\progra~1\mozill~1 && firefox"

...didn't prove the solution was working. So I chose another program (nLite) after making sure that it was not executable anywhere on my system:

START cmd.exe /k "cd C:\progra~1\nlite && nlite"

And that works just as my original answer already suggested. A Windows version is not given in the question, but I'm using Windows XP, btw.


If anybody is interested why firefox.exe, while not being in PATH, is executable anywhere on my system - and very probably on yours as well - this is due to a registry key where applications can be registered to be available everywhere. See this SU answer for details.

Binding a list in @RequestParam

Change hidden field value with checkbox toggle like below...

HTML:

<input type='hidden' value='Unchecked' id="deleteAll" name='anyName'>
<input type="checkbox"  onclick="toggle(this)"/> Delete All

Script:

function toggle(obj) {`var $input = $(obj);
    if ($input.prop('checked')) {

    $('#deleteAll').attr( 'value','Checked');

    } else {

    $('#deleteAll').attr( 'value','Unchecked');

    }

}

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

Your build script should match with application build.gradle dependencies.

ext {
        buildToolsVersion = "27.0.3"
        minSdkVersion = 16
        compileSdkVersion = 27
        targetSdkVersion = 26
        supportLibVersion = "27.1.1"
    }


dependencies {
    .................
    ...................

    implementation 'com.android.support:support-v4:27.1.0'
    implementation 'com.android.support:design:27.1.0'
    ................
    ...........
}

if you want to downgrade dependencies then also downgrade supportLibVersion and buildToolsVersion .

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

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

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

Add list to set?

list objects are unhashable. you might want to turn them in to tuples though.

How to take a screenshot programmatically on iOS

I couldn't find an answer with Swift 3 implementation. So here it goes.

static func screenshotOf(window: UIWindow) -> UIImage? {

    UIGraphicsBeginImageContextWithOptions(window.bounds.size, true, UIScreen.main.scale)

    guard let currentContext = UIGraphicsGetCurrentContext() else {
        return nil
    }

    window.layer.render(in: currentContext)
    guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
        UIGraphicsEndImageContext()
        return nil
    }

    UIGraphicsEndImageContext()
    return image
}

How can I check if some text exist or not in the page using Selenium?

This will help you to check whether required text is there in webpage or not.

driver.getPageSource().contains("Text which you looking for");

Subset data.frame by date

The first thing you should do with date variables is confirm that R reads it as a Date. To do this, for the variable (i.e. vector/column) called Date, in the data frame called EPL2011_12, input

class(EPL2011_12$Date)

The output should read [1] "Date". If it doesn't, you should format it as a date by inputting

EPL2011_12$Date <- as.Date(EPL2011_12$Date, "%d-%m-%y")

Note that the hyphens in the date format ("%d-%m-%y") above can also be slashes ("%d/%m/%y"). Confirm that R sees it as a Date. If it doesn't, try a different formatting command

EPL2011_12$Date <- format(EPL2011_12$Date, format="%d/%m/%y")

Once you have it in Date format, you can use the subset command, or you can use brackets

WhateverYouWant <- EPL2011_12[EPL2011_12$Date > as.Date("2014-12-15"),]

Getting last day of the month in a given string date

Java 8 and above.

By using convertedDate.getMonth().length(convertedDate.isLeapYear()) where convertedDate is an instance of LocalDate.

String date = "1/13/2012";
LocalDate convertedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/d/yyyy"));
convertedDate = convertedDate.withDayOfMonth(
                                convertedDate.getMonth().length(convertedDate.isLeapYear()));

Java 7 and below.

By using getActualMaximum method of java.util.Calendar:

String date = "1/13/2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse(date);
Calendar c = Calendar.getInstance();
c.setTime(convertedDate);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));

How to add default signature in Outlook

I constructed this approach while looking for how to send a message on a recurring schedule. I found the approach where you reference the Inspector property of the created message did not add the signature I wanted (I have more than one account set up in Outlook, with separate signatures.)

The approach below is fairly flexible and still simple.

    Private Sub Add_Signature(ByVal addy as String, ByVal subj as String, ByVal body as String)
       Dim oMsg As MailItem
       Set oMsg = Application.CreateItem(olMailItem)
       oMsg.To = addy
       oMsg.Subject = subj
       oMsg.Body = body
       Dim sig As String
       ' Mysig is the name you gave your signature in the OL Options dialog 
       sig = ReadSignature("Mysig.htm")
       oMsg.HTMLBody = Item.Body & "<p><BR/><BR/></p>" & sig ' oMsg.HTMLBody
       oMsg.Send
       Set oMsg = Nothing
    End Sub

    Private Function ReadSignature(sigName As String) As String
       Dim oFSO, oTextStream, oSig As Object
       Dim appDataDir, sig, sigPath, fileName As String
       appDataDir = Environ("APPDATA") & "\Microsoft\Signatures"
       sigPath = appDataDir & "\" & sigName

       Set oFSO = CreateObject("Scripting.FileSystemObject")
       Set oTextStream = oFSO.OpenTextFile(sigPath)
       sig = oTextStream.ReadAll
       ' fix relative references to images, etc. in sig
       ' by making them absolute paths, OL will find the image
       fileName = Replace(sigName, ".htm", "") & "_files/"
       sig = Replace(sig, fileName, appDataDir & "\" & fileName)
       ReadSignature = sig
    End Function

jQuery get mouse position within an element

I use this piece of code, its quite nice :)

    <script language="javascript" src="http://code.jquery.com/jquery-1.4.1.js" type="text/javascript"></script>
<script language="javascript">
$(document).ready(function(){
    $(".div_container").mousemove(function(e){
        var parentOffset = $(this).parent().offset();
        var relativeXPosition = (e.pageX - parentOffset.left); //offset -> method allows you to retrieve the current position of an element 'relative' to the document
        var relativeYPosition = (e.pageY - parentOffset.top);
        $("#header2").html("<p><strong>X-Position: </strong>"+relativeXPosition+" | <strong>Y-Position: </strong>"+relativeYPosition+"</p>")
    }).mouseout(function(){
        $("#header2").html("<p><strong>X-Position: </strong>"+relativeXPosition+" | <strong>Y-Position: </strong>"+relativeYPosition+"</p>")
    });
});
</script>

C++: How to round a double to an int?

Casting to an int truncates the value. Adding 0.5 causes it to do proper rounding.

int y = (int)(x + 0.5);

how to force maven to update local repo

You can also use this command on the command line:

mvn dependency:purge-local-repository clean install

Select single item from a list

List<string> items = new List<string>();

items.Find(p => p == "blah");

or

items.Find(p => p.Contains("b"));

but this allows you to define what you are looking for via a match predicate...

I guess if you are talking linqToSql then:

example looking for Account...

DataContext dc = new DataContext();

Account item = dc.Accounts.FirstOrDefault(p => p.id == 5);

If you need to make sure that there is only 1 item (throws exception when more than 1)

DataContext dc = new DataContext();

Account item = dc.Accounts.SingleOrDefault(p => p.id == 5);

Can you style html form buttons with css?

You can achieve your desired through easily by CSS :-

HTML

<input type="submit" name="submit" value="Submit Application" id="submit" />

CSS

#submit {
    background-color: #ccc;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius:6px;
    color: #fff;
    font-family: 'Oswald';
    font-size: 20px;
    text-decoration: none;
    cursor: pointer;
    border:none;
}



#submit:hover {
    border: none;
    background:red;
    box-shadow: 0px 0px 1px #777;
}

DEMO

How to insert a new line in Linux shell script?

The simplest way to insert a new line between echo statements is to insert an echo without arguments, for example:

echo Create the snapshots
echo
echo Snapshot created

That is, echo without any arguments will print a blank line.

Another alternative to use a single echo statement with the -e flag and embedded newline characters \n:

echo -e "Create the snapshots\n\nSnapshot created"

However, this is not portable, as the -e flag doesn't work consistently in all systems. A better way if you really want to do this is using printf:

printf "Create the snapshots\n\nSnapshot created\n"

This works more reliably in many systems, though it's not POSIX compliant. Notice that you must manually add a \n at the end, as printf doesn't append a newline automatically as echo does.

Convert string to Date in java

This code will help you to make a result like FEB 17 20:49 .

    String myTimestamp="2014/02/17 20:49";

    SimpleDateFormat form = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    Date date = null;
    Date time = null;
    try 
    {
        date = form.parse(myTimestamp);
        time = new Date(myTimestamp);
        SimpleDateFormat postFormater = new SimpleDateFormat("MMM dd");
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        String newDateStr = postFormater.format(date).toUpperCase();
        String newTimeStr = sdf.format(time);
        System.out.println("Date  : "+newDateStr);
        System.out.println("Time  : "+newTimeStr);
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }

Result :

Date : FEB 17

Time : 20:49

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

Here is my answer in Python 2.7

Print current time with timezone

from datetime import datetime
import tzlocal  # pip install tzlocal

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

Print current time with specific timezone

from datetime import datetime
import pytz # pip install pytz

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

It will print something like

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

Can JavaScript connect with MySQL?

If you want to connect to a MySQL database using JavaScript, you can use Node.js and a library called mysql. You can create queries, and get results as an array of registers. If you want to try it, you can use my project generator to create a backend and choose MySQL as the database to connect. Then, just expose your new REST API or GraphQL endpoint to your front and start working with your MySQL database.


OLD ANSWER LEFT BY NOSTALGIA

THEN

As I understand the question and correct me if I am wrong, it refers to the classic server model with JavaScript only on the client-side. In this classic model, with LAMP servers (Linux, Apache, MySQL, PHP) the language in contact with the database was PHP, so to request data to the database you need to write PHP scripts and echo the returning data to the client. Basically, the distribution of the languages according to physical machines was:

  1. Server Side: PHP and MySQL.
  2. Client Side: HTML/CSS and JavaScript.

This answered to an MVC model (Model, View, Controller) where we had the following functionality:

  1. MODEL: The model is what deals with the data, in this case, the PHP scripts that manage variables or that access data stored, in this case in our MySQL database and send it as JSON data to the client.
  2. VIEW: The view is what we see and it should be completely independent of the model. It just needs to show the data contained in the model, but it shouldn't have relevant data on it. In this case, the view uses HTML and CSS. HTML to create the basic structure of the view, and CSS to give the shape to this basic structure.
  3. CONTROLLER: The controller is the interface between our model and our view. In this case, the language used is JavaScript and it takes the data the model send us as a JSON package and put it inside the containers that offer the HTML structure. The way the controller interacts with the model is by using AJAX. We use GET and POST methods to call PHP scripts on the server-side and to catch the returned data from the server.

For the controller, we have really interesting tools like jQuery, as "low-level" library to control the HTML structure (DOM), and then new, more high-level ones as Knockout.js that allow us to create observers that connect different DOM elements updating them when events occur. There is also Angular.js by Google that works in a similar way, but seems to be a complete environment. To help you to choose among them, here you have two excellent analyses of the two tools: Knockout vs. Angular.js and Knockout.js vs. Angular.js. I am still reading. Hope they help you.

NOW

In modern servers based in Node.js, we use JavaScript for everything. Node.js is a JavaScript environment with many libraries that work with Google V8, Chrome JavaScript engine. The way we work with these new servers is:

  1. Node.js and Express: The mainframe where the server is built. We can create a server with a few lines of code or even use libraries like Express to make even easier to create the server. With Node.js and Express, we will manage the petitions to the server from the clients and will answer them with the appropriate pages.
  2. Jade: To create the pages we use a templating language, in this case, Jade, that allow us to write web pages as we were writing HTML but with differences (it take a little time but is easy to learn). Then, in the code of the server to answer the client's petitions, we just need to render the Jade code into a "real" HTML code.
  3. Stylus: Similar to Jade but for CSS. In this case, we use a middleware function to convert the stylus file into a real CSS file for our page.

Then we have a lot of packages we can install using the NPM (Node.js package manager) and use them directly in our Node.js server just requiring it (for those of you that want to learn Node.js, try this beginner tutorial for an overview). And among these packages, you have some of them to access databases. Using this you can use JavaScript on the server-side to access My SQL databases.

But the best you can do if you are going to work with Node.js is to use the new NoSQL databases like MongoDB, based on JSON files. Instead of storing tables like MySQL, it stores the data in JSON structures, so you can put different data inside each structure like long numeric vectors instead of creating huge tables for the size of the biggest one.

I hope this brief explanation becomes useful to you, and if you want to learn more about this, here you have some resources you can use:

  • Egghead: This site is full of great short tutorials about JavaScript and its environment. It worths a try. And the make discounts from time to time.
  • Code School: With a free and very interesting course about Chrome Developer tools to help you to test the client-side.
  • Codecademy: With free courses about HTML, CSS, JavaScript, jQuery, and PHP that you can follow with online examples.
  • 10gen Education: With everything you need to know about MongoDB in tutorials for different languages.
  • W3Schools: This one has tutorials about all this and you can use it as a reference place because it has a lot of shortcode examples really useful.
  • Udacity: A place with free video courses about different subjects with a few interesting ones about web development and my preferred, an amazing WebGL course for 3D graphics with JavaScript.

I hope it helps you to start.

Have fun!

How to change style of a default EditText

Create xml file like edit_text_design.xml and save it to your drawable folder

i have given the Color codes According to my Choice, Please Change Color Codes As per your Choice !

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

<item>
    <shape>
        <solid android:color="#c2c2c2" />
    </shape>
</item>

<!-- main color -->
<item
    android:bottom="1.5dp"
    android:left="1.5dp"
    android:right="1.5dp">
    <shape>
        <solid android:color="#000" />
    </shape>
</item>

<!-- draw another block to cut-off the left and right bars -->
<item android:bottom="5.0dp">
    <shape>
        <solid android:color="#000" />
    </shape>
</item>

</layer-list>

your Edit Text Should contain it as Background :

add android:background="@drawable/edit_text_design" to all of your EditText's

and your above EditText should now look like this:

      <EditText
        android:id="@+id/name_edit_text"
        android:background="@drawable/edit_text_design"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/profile_image_view_layout"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="20dp"
        android:ems="15"
        android:hint="@string/name_field"
        android:inputType="text" />

Does Ruby have a string.startswith("abc") built in method?

It's called String#start_with?, not String#startswith: In Ruby, the names of boolean-ish methods end with ? and the words in method names are separated with an _. Not sure where the s went, personally, I'd prefer String#starts_with? over the actual String#start_with?

SQL RANK() versus ROW_NUMBER()

Quite a bit:

The rank of a row is one plus the number of ranks that come before the row in question.

Row_number is the distinct rank of rows, without any gap in the ranking.

http://www.bidn.com/blogs/marcoadf/bidn-blog/379/ranking-functions-row_number-vs-rank-vs-dense_rank-vs-ntile

Looking for simple Java in-memory cache

You can easily use imcache. A sample code is below.

void example(){
    Cache<Integer,Integer> cache = CacheBuilder.heapCache().
    cacheLoader(new CacheLoader<Integer, Integer>() {
        public Integer load(Integer key) {
            return null;
        }
    }).capacity(10000).build(); 
}

How to exit in Node.js

Press Ctrl + C twice or .exit.

> 
(To exit, press ^C again or type .exit)
> 

Get name of object or class

I was facing a similar difficulty and none of the solutions presented here were optimal for what I was working on. What I had was a series of functions to display content in a modal and I was trying to refactor it under a single object definition making the functions, methods of the class. The problem came in when I found one of the methods created some nav-buttons inside the modal themselves which used an onClick to one of the functions -- now an object of the class. I have considered (and am still considering) other methods to handle these nav buttons, but I was able to find the variable name for the class itself by sweeping the variables defined in the parent window. What I did was search for anything matching the 'instanceof' my class, and in case there might be more than one, I compared a specific property that was likely to be unique to each instance:

var myClass = function(varName)
{
    this.instanceName = ((varName != null) && (typeof(varName) == 'string') && (varName != '')) ? varName : null;

    /**
     * caching autosweep of window to try to find this instance's variable name
     **/
    this.getInstanceName = function() {
        if(this.instanceName == null)
        {
            for(z in window) {
                if((window[z] instanceof myClass) && (window[z].uniqueProperty === this.uniqueProperty)) {
                    this.instanceName = z;
                    break;
                }
            }
        }
        return this.instanceName;
    }
}

"&" meaning after variable type

It means you're passing the variable by reference.

In fact, in a declaration of a type, it means reference, just like:

int x = 42;
int& y = x;

declares a reference to x, called y.

Git: "please tell me who you are" error

I ran into this error message whilst trying to commit some files.

Simply running git fetch then trying my commit again worked for me.

EF LINQ include multiple and nested entities

You can also try

db.Courses.Include("Modules.Chapters").Single(c => c.Id == id);

How to replace a char in string with an Empty character in C#.NET

If you want to replace a char in a string with an empty char that means you want to remove that char from a string, read the answer of R. Martinho Fernandes.

Here is an exemple of how to remove a char from a string (replace with an "Empty char"):

    public static string RemoveCharFromString(string input, char charItem)
    {
        int indexOfChar = input.IndexOf(charItem);
        if (indexOfChar >= 0)
        {
            input = input.Remove(indexOfChar, 1);
        }
        return input;
    }

or this version that removes all recurrences of a char in a string :

    public static string RemoveCharFromString(string input, char charItem)
    {
        int indexOfChar = input.IndexOf(charItem);
        if (indexOfChar < 0)
        {
            return input;
        }
        return RemoveCharFromString(input.Remove(indexOfChar, 1), charItem);
    }

link with target="_blank" does not open in new tab in Chrome

Your syntax for the target attribute is correct, but browsers need not honor it. They may interpret it as opening the destination in a new tab rather than new window, or they may completely ignore the attribute. Browsers have settings for such issues. Moreover, opening of new windows may be prevented by browser plugins (typically designed to prevent annoying advertisements).

There’s little you can do about this as an author. You might consider opening a new window with JavaScript instead, cf. to the accepted answer to target="_blank" is not working in firefox?, but browsers may be even more reluctant to let pages open new windows that way than via target.

target="_blank" is not working in firefox?

Android ImageButton with a selected state?

ToggleImageButton which implements Checkable interface and supports OnCheckedChangeListener and android:checked xml attribute:

public class ToggleImageButton extends ImageButton implements Checkable {
    private OnCheckedChangeListener onCheckedChangeListener;

    public ToggleImageButton(Context context) {
        super(context);
    }

    public ToggleImageButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        setChecked(attrs);
    }

    public ToggleImageButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setChecked(attrs);
    }

    private void setChecked(AttributeSet attrs) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ToggleImageButton);
        setChecked(a.getBoolean(R.styleable.ToggleImageButton_android_checked, false));
        a.recycle();
    }

    @Override
    public boolean isChecked() {
        return isSelected();
    }

    @Override
    public void setChecked(boolean checked) {
        setSelected(checked);

        if (onCheckedChangeListener != null) {
            onCheckedChangeListener.onCheckedChanged(this, checked);
        }
    }

    @Override
    public void toggle() {
        setChecked(!isChecked());
    }

    @Override
    public boolean performClick() {
        toggle();
        return super.performClick();
    }

    public OnCheckedChangeListener getOnCheckedChangeListener() {
        return onCheckedChangeListener;
    }

    public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
        this.onCheckedChangeListener = onCheckedChangeListener;
    }

    public static interface OnCheckedChangeListener {
        public void onCheckedChanged(ToggleImageButton buttonView, boolean isChecked);
    }
}

res/values/attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ToggleImageButton">
        <attr name="android:checked" />
    </declare-styleable>
</resources>

regular expression to match exactly 5 digits

what is about this? \D(\d{5})\D

This will do on:

f 23 23453 234 2344 2534 hallo33333 "50000"

23453, 33333 50000

PHP post_max_size overrides upload_max_filesize

By POST file uploads are done (commonly, there are also other methods). Look into the method attribute of the form which contains the file-upload field ;)

The lowest limit of any related setting supersedes a higher setting:

See Handling file uploads: Common Pitfals which explains this in detail and how to calculate the values.

SQL query for today's date minus two months

SELECT COUNT(1) FROM FB 
WHERE Dte > DATE_SUB(now(), INTERVAL 2 MONTH)

invalid_grant trying to get oAuth token from google

Look at this https://dev.to/risafj/beginner-s-guide-to-oauth-understanding-access-tokens-and-authorization-codes-2988

First you need an access_token:

$code = $_GET['code'];

$clientid = "xxxxxxx.apps.googleusercontent.com";
$clientsecret = "xxxxxxxxxxxxxxxxxxxxx";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/oauth2/v4/token");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "client_id=".urlencode($clientid)."&client_secret=".urlencode($clientsecret)."&code=".urlencode($code)."&grant_type=authorization_code&redirect_uri=". urlencode("https://yourdomain.com"));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);

$server_output = json_decode($server_output);
$access_token = $server_output->access_token;
$refresh_token = $server_output->refresh_token;
$expires_in = $server_output->expires_in;

Safe the Access Token and the Refresh Token and the expire_in, in a Database. The Access Token expires after $expires_in seconds. Than you need to grab a new Access Token (and safe it in the Database) with the following Request:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/oauth2/v4/token");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "client_id=".urlencode($clientid)."&client_secret=".urlencode($clientsecret)."&refresh_token=".urlencode($refresh_token)."&grant_type=refresh_token");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);

$server_output = json_decode($server_output);
$access_token = $server_output->access_token;
$expires_in = $server_output->expires_in;

Bear in Mind to add the redirect_uri Domain to your Domains in your Google Console: https://console.cloud.google.com/apis/credentials in the Tab "OAuth 2.0-Client-IDs". There you find also your Client-ID and Client-Secret.

What is the difference between HTML tags <div> and <span>?

<div> is a block-level element and <span> is an inline element.

If you wanted to do something with some inline text, <span> is the way to go since it will not introduce line breaks that a <div> would.


As noted by others, there are some semantics implied with each of these, most significantly the fact that a <div> implies a logical division in the document, akin to maybe a section of a document or something, a la:

<div id="Chapter1">
   <p>Lorem ipsum dolor sit amet, <span id="SomeSpecialText1">consectetuer adipiscing</span> elit. Duis congue vehicula purus.</p>
   <p>Nam <span id="SomeSpecialText2">eget magna nec</span> sapien fringilla euismod. Donec hendrerit.</p> 
</div>

OperationalError: database is locked

I disagree with @Patrick's answer which, by quoting this doc, implicitly links OP's problem (Database is locked) to this:

Switching to another database backend. At a certain point SQLite becomes too "lite" for real-world applications, and these sorts of concurrency errors indicate you've reached that point.

This is a bit "too easy" to incriminate SQlite for this problem (which is very powerful when correctly used; it's not only a toy for small databases, fun fact: An SQLite database is limited in size to 140 terabytes).

Unless you have a very busy server with thousands of connections at the same second, the reason for this Database is locked error is probably more a bad use of the API, than a problem inherent to SQlite which would be "too light". Here are more informations about Implementation Limits for SQLite.


Now the solution:

I had the same problem when I was using two scripts using the same database at the same time:

  • one was accessing the DB with write operations
  • the other was accessing the DB in read-only

Solution: always do cursor.close() as soon as possible after having done a (even read-only) query.

Here are more details.

Cannot set property 'display' of undefined

I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.

In this code we add multiple styles in an element:

_x000D_
_x000D_
let_x000D_
    element = document.querySelector('span')_x000D_
  , cssStyle = (el, styles) => {_x000D_
      for (var property in styles) {_x000D_
          el.style[property] = styles[property];_x000D_
      }_x000D_
  }_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_

How to get the difference between two dictionaries in Python?

A function using the symmetric difference set operator, as mentioned in other answers, which preserves the origins of the values:

def diff_dicts(a, b, missing=KeyError):
    """
    Find keys and values which differ from `a` to `b` as a dict.

    If a value differs from `a` to `b` then the value in the returned dict will
    be: `(a_value, b_value)`. If either is missing then the token from 
    `missing` will be used instead.

    :param a: The from dict
    :param b: The to dict
    :param missing: A token used to indicate the dict did not include this key
    :return: A dict of keys to tuples with the matching value from a and b
    """
    return {
        key: (a.get(key, missing), b.get(key, missing))
        for key in dict(
            set(a.items()) ^ set(b.items())
        ).keys()
    }

Example

print(diff_dicts({'a': 1, 'b': 1}, {'b': 2, 'c': 2}))

# {'c': (<class 'KeyError'>, 2), 'a': (1, <class 'KeyError'>), 'b': (1, 2)}

How this works

We use the symmetric difference set operator on the tuples generated from taking items. This generates a set of distinct (key, value) tuples from the two dicts.

We then make a new dict from that to collapse the keys together and iterate over these. These are the only keys that have changed from one dict to the next.

We then compose a new dict using these keys with a tuple of the values from each dict substituting in our missing token when the key isn't present.

How do I exclude Weekend days in a SQL Server query?

Try this code

select (DATEDIFF(DD,'2014-08-01','2014-08-14')+1)- (DATEDIFF(WK,'2014-08-01','2014-08-14')* 2)

Help with packages in java - import does not work

Okay, just to clarify things that have already been posted.

You should have the directory com, containing the directory company, containing the directory example, containing the file MyClass.java.

From the folder containing com, run:

$ javac com\company\example\MyClass.java

Then:

$ java com.company.example.MyClass
Hello from MyClass!

These must both be done from the root of the source tree. Otherwise, javac and java won't be able to find any other packages (in fact, java wouldn't even be able to run MyClass).

A short example

I created the folders "testpackage" and "testpackage2". Inside testpackage, I created TestPackageClass.java containing the following code:

package testpackage;

import testpackage2.MyClass;

public class TestPackageClass {
    public static void main(String[] args) {
        System.out.println("Hello from testpackage.TestPackageClass!");
        System.out.println("Now accessing " + MyClass.NAME);
    }
}

Inside testpackage2, I created MyClass.java containing the following code:

package testpackage2;
public class MyClass {
    public static String NAME = "testpackage2.MyClass";
}

From the directory containing the two new folders, I ran:

C:\examples>javac testpackage\*.java

C:\examples>javac testpackage2\*.java

Then:

C:\examples>java testpackage.TestPackageClass
Hello from testpackage.TestPackageClass!
Now accessing testpackage2.MyClass

Does that make things any clearer?

How do I check if a variable exists?

A simple way is to initialize it at first saying myVar = None

Then later on:

if myVar is not None:
    # Do something

Installing mcrypt extension for PHP on OSX Mountain Lion

mycrypt.o and mcrypt_filter.o are in the ext/.libs of your php downloaded directory. Just copy the files to ext/mcrypt, then run make && make install again.

Send PHP variable to javascript function

If I understand you correctly, you should be able to do something along the lines of the following:

function clicked() {
    var someVariable="<?php echo $phpVariable; ?>";
}

Superscript in markdown (Github flavored)?

<sup> and <sub> tags work and are your only good solution for arbitrary text. Other solutions include:

Unicode

If the superscript (or subscript) you need is of a mathematical nature, Unicode may well have you covered.

I've compiled a list of all the Unicode super and subscript characters I could identify in this gist. Some of the more common/useful ones are:

  • ° SUPERSCRIPT ZERO (U+2070)
  • ¹ SUPERSCRIPT ONE (U+00B9)
  • ² SUPERSCRIPT TWO (U+00B2)
  • ³ SUPERSCRIPT THREE (U+00B3)
  • n SUPERSCRIPT LATIN SMALL LETTER N (U+207F)

People also often reach for <sup> and <sub> tags in an attempt to render specific symbols like these:

  • TRADE MARK SIGN (U+2122)
  • ® REGISTERED SIGN (U+00AE)
  • ? SERVICE MARK (U+2120)

Assuming your editor supports Unicode, you can copy and paste the characters above directly into your document.

Alternatively, you could use the hex values above in an HTML character escape. Eg, &#x00B2; instead of ². This works with GitHub (and should work anywhere else your Markdown is rendered to HTML) but is less readable when presented as raw text/Markdown.

Images

If your requirements are especially unusual, you can always just inline an image. The GitHub supported syntax is:

![Alt text goes here, if you'd like](path/to/image.png) 

You can use a full path (eg. starting with https:// or http://) but it's often easier to use a relative path, which will load the image from the repo, relative to the Markdown document.

If you happen to know LaTeX (or want to learn it) you could do just about any text manipulation imaginable and render it to an image. Sites like Quicklatex make this quite easy.

Create request with POST, which response codes 200 or 201 and content

The output is actually dependent on the content type being requested. However, at minimum you should put the resource that was created in Location. Just like the Post-Redirect-Get pattern.

In my case I leave it blank until requested otherwise. Since that is the behavior of JAX-RS when using Response.created().

However, just note that browsers and frameworks like Angular do not follow 201's automatically. I have noted the behaviour in http://www.trajano.net/2013/05/201-created-with-angular-resource/

Encrypt and Decrypt in Java

KeyGenerator is used to generate keys

You may want to check KeySpec, SecretKey and SecretKeyFactory classes

http://docs.oracle.com/javase/1.5.0/docs/api/javax/crypto/spec/package-summary.html

How to clear all input fields in bootstrap modal when clicking data-dismiss button?

There is a more easy and beautiful way:

$('#MyModal').on('hidden.bs.modal', function () {
    $(this).find('form').trigger('reset');
})

reset is dom build-in funtion, you can also use $(this).find('form')[0].reset();

And Bootstrap's modal class exposes a few events for hooking into modal functionality, detail at here.

hide.bs.modal This event is fired immediately when the hide instance method has been called.

hidden.bs.modal This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).

Changing Font Size For UITableView Section Headers

Another way to do this would be to respond to the UITableViewDelegate method willDisplayHeaderView. The passed view is actually an instance of a UITableViewHeaderFooterView.

The example below changes the font, and also centers the title text vertically and horizontally within the cell. Note that you should also respond to heightForHeaderInSection to have any changes to your header's height accounted for in the layout of the table view. (That is, if you decide to change the header height in this willDisplayHeaderView method.)

You could then respond to the titleForHeaderInSection method to reuse this configured header with different section titles.

Objective-C

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;

    header.textLabel.textColor = [UIColor redColor];
    header.textLabel.font = [UIFont boldSystemFontOfSize:18];
    CGRect headerFrame = header.frame;
    header.textLabel.frame = headerFrame;
    header.textLabel.textAlignment = NSTextAlignmentCenter;
}

Swift 1.2

(Note: if your view controller is a descendant of a UITableViewController, this would need to be declared as override func.)

override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) 
{
    let header:UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView

    header.textLabel.textColor = UIColor.redColor()
    header.textLabel.font = UIFont.boldSystemFontOfSize(18)
    header.textLabel.frame = header.frame
    header.textLabel.textAlignment = NSTextAlignment.Center
}

Swift 3.0

This code also ensures that the app doesn't crash if your header view is something other than a UITableViewHeaderFooterView:

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    guard let header = view as? UITableViewHeaderFooterView else { return }
    header.textLabel?.textColor = UIColor.red
    header.textLabel?.font = UIFont.boldSystemFont(ofSize: 18)
    header.textLabel?.frame = header.frame
    header.textLabel?.textAlignment = .center
}

why are there two different kinds of for loops in java?

The new for-each loop is just a short hand for the older loop. The new loop is easier to use for arrays and some iterators, but not as flexible, so the old loop has to be using in some situations, like counting from 0 to 9.

Unprotect workbook without password

No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.

How to copy java.util.list Collection

Use the ArrayList copy constructor, then sort that.

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

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

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

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

Restarting your server may not work always. I have got this error when I imported MatFormFieldModule.

In app.module.ts, I have imported MatFormField instead of MatFormFieldModule which lead to this error.

Now change it and restart the server, Hope this answer helps you.

Make a link use POST instead of GET

HTML + JQuery: A link that submits a hidden form with POST.

Since I spent a lot of time to understand all these answers, and since all of them have some interesting details, here is the combined version that finally worked for me and which I prefer for its simplicity.

My approach is again to create a hidden form and to submit it by clicking a link somewhere else in the page. It doesn't matter where in the body of the page the form will be placed.

The code for the form:

<form id="myHiddenFormId" action="myAction.php" method="post" style="display: none">
  <input type="hidden" name="myParameterName" value="myParameterValue">
</form>

Description:

The display: none hides the form. You can alternatively put it in a div or another element and set the display: none on the element.

The type="hidden" will create an fild that will not be shown but its data will be transmitted to the action eitherways (see W3C). I understand that this is the simplest input type.

The code for the link:

<a href="" onclick="$('#myHiddenFormId').submit(); return false;" title="My link title">My link text</a>

Description:

The empty href just targets the same page. But it doesn't really matter in this case since the return false will stop the browser from following the link. You may want to change this behavior of course. In my specific case, the action contained a redirection at the end.

The onclick was used to avoid using href="javascript:..." as noted by mplungjan. The $('#myHiddenFormId').submit(); was used to submit the form (instead of defining a function, since the code is very small).

This link will look exactly like any other <a> element. You can actually use any other element instead of the <a> (for example a <span> or an image).

Javascript use variable as object name

Is it a global variable? If so, these are actually part of the window object, so you can do window[objname].value.

If it's local to a function, I don't think there's a good way to do what you want.

Can I have an onclick effect in CSS?

you can use :target

or to filter by class name, use .classname:target

or filter by id name using #idname:target

_x000D_
_x000D_
#id01:target {      
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.msg {
    display:none;
}

.close {        
    color:white;        
    width: 2rem;
    height: 2rem;
    background-color: black;
    text-align:center;
    margin:20px;
}
_x000D_
  
<a href="#id01">Open</a>

<div id="id01" class="msg">    
    <a href="" class="close">&times;</a>
    <p>Some text. Some text. Some text.</p>
    <p>Some text. Some text. Some text.</p>
</div>
_x000D_
_x000D_
_x000D_

regular expression for finding 'href' value of a <a> link

Using regex to parse html is not recommended

regex is used for regularly occurring patterns.html is not regular with it's format(except xhtml).For example html files are valid even if you don't have a closing tag!This could break your code.

Use an html parser like htmlagilitypack

You can use this code to retrieve all href's in anchor tag using HtmlAgilityPack

HtmlDocument doc = new HtmlDocument();
doc.Load(yourStream);

var hrefList = doc.DocumentNode.SelectNodes("//a")
                  .Select(p => p.GetAttributeValue("href", "not found"))
                  .ToList();

hrefList contains all href`s

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

David Walsh has a better and to the point approach.

// Listen for orientation changes
window.addEventListener("orientationchange", function() {
  // Announce the new orientation number
  alert(window.orientation);
}, false);

During these changes, the window.orientation property may change. A value of 0 means portrait view, -90 means a the device is landscape rotated to the right, and 90 means the device is landscape rotated to the left.

http://davidwalsh.name/orientation-change

Focusable EditText inside ListView

This saved my life--->

  1. set this line

    ListView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);

  2. Then in your manifest in activity tag type this-->

    <activity android:windowSoftInputMode="adjustPan">

Your usual intent

What datatype to use when storing latitude and longitude data in SQL databases?

Well, you asked how to store Latitude/Longitude and my answer is: Don't, you might consider using the WGS 84 ( in Europe ETRS 89 ) as it is the standard for Geo references.

But that detail aside I used a User Defined Type in the days before SQL 2008 finally include geo support.

Get the distance between two geo points

http://developer.android.com/reference/android/location/Location.html

Look into distanceTo or distanceBetween. You can create a Location object from a latitude and longitude:

Location location = new Location("");
location.setLatitude(lat);
location.setLongitude(lon);

Select arrow style change

Here is an elegant fix that uses a span to show the value.

Layout is like this:

<div class="selectDiv">
   <span class="selectDefault"></span>
   <select name="txtCountry" class="selectBox">
      <option class="defualt-text">-- Select Country --</option>
      <option value="1">Abkhazia</option>
      <option value="2">Afghanistan</option>
   </select>
</div>

JsFiddle

How Connect to remote host from Aptana Studio 3

There's also an option to Auto Sync built-in in Aptana.

step 1

step 2

How to clear browsing history using JavaScript?

You cannot clear the browser history. It belongs to the user, not the developer. Also have a look at the MDN documentation.

Update: The link you were posting all over does not actually clear your browser history. It just prevents using the back button.

JavaScript global event mechanism

sophisticated error handling

If your error handling is very sophisticated and therefore might throw an error itself, it is useful to add a flag indicating if you are already in "errorHandling-Mode". Like so:

var appIsHandlingError = false;

window.onerror = function() {
    if (!appIsHandlingError) {
        appIsHandlingError = true;
        handleError();
    }
};

function handleError() {
    // graceful error handling
    // if successful: appIsHandlingError = false;
}

Otherwise you could find yourself in an infinite loop.

How to make Excel VBA variables available to multiple macros?

Create a "module" object and declare variables in there. Unlike class-objects that have to be instantiated each time, the module objects are always available. Therefore, a public variable, function, or property in a "module" will be available to all the other objects in the VBA project, macro, Excel formula, or even within a MS Access JET-SQL query def.

How to Get enum item name from its value

Here is another neat trick to define enum using X Macro:

#include <iostream>

#define WEEK_DAYS \
X(MON, "Monday", true) \
X(TUE, "Tuesday", true) \
X(WED, "Wednesday", true) \
X(THU, "Thursday", true) \
X(FRI, "Friday", true) \
X(SAT, "Saturday", false) \
X(SUN, "Sunday", false)

#define X(day, name, workday) day,
enum WeekDay : size_t
{
    WEEK_DAYS
};
#undef X

#define X(day, name, workday) name,
char const *weekday_name[] =
{
    WEEK_DAYS
};
#undef X

#define X(day, name, workday) workday,
bool weekday_workday[]
{
    WEEK_DAYS
};
#undef X

int main()
{
    std::cout << "Enum value: " << WeekDay::THU << std::endl;
    std::cout << "Name string: " << weekday_name[WeekDay::THU] << std::endl;
    std::cout << std::boolalpha << "Work day: " << weekday_workday[WeekDay::THU] << std::endl;

    WeekDay wd = SUN;
    std::cout << "Enum value: " << wd << std::endl;
    std::cout << "Name string: " << weekday_name[wd] << std::endl;
    std::cout << std::boolalpha << "Work day: " << weekday_workday[wd] << std::endl;

    return 0;
}

Live Demo: https://ideone.com/bPAVTM

Outputs:

Enum value: 3
Name string: Thursday
Work day: true
Enum value: 6
Name string: Sunday
Work day: false

How can I install a package with go get?

Command go

Download and install packages and dependencies

Usage:

go get [-d] [-f] [-t] [-u] [-v] [-fix] [-insecure] [build flags] [packages]

Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'.

The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages.

The -f flag, valid only when -u is set, forces get -u not to verify that each package has been checked out from the source control repository implied by its import path. This can be useful if the source is a local fork of the original.

The -fix flag instructs get to run the fix tool on the downloaded packages before resolving dependencies or building the code.

The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution.

The -t flag instructs get to also download the packages required to build the tests for the specified packages.

The -u flag instructs get to use the network to update the named packages and their dependencies. By default, get uses the network to check out missing packages but does not use it to look for updates to existing packages.

The -v flag enables verbose progress and debug output.

Get also accepts build flags to control the installation. See 'go help build'.

When checking out a new package, get creates the target directory GOPATH/src/. If the GOPATH contains multiple entries, get uses the first one. For more details see: 'go help gopath'.

When checking out or updating a package, get looks for a branch or tag that matches the locally installed version of Go. The most important rule is that if the local installation is running version "go1", get searches for a branch or tag named "go1". If no such version exists it retrieves the default branch of the package.

When go get checks out or updates a Git repository, it also updates any git submodules referenced by the repository.

Get never checks out or updates code stored in vendor directories.

For more about specifying packages, see 'go help packages'.

For more about how 'go get' finds source code to download, see 'go help importpath'.

This text describes the behavior of get when using GOPATH to manage source code and dependencies. If instead the go command is running in module-aware mode, the details of get's flags and effects change, as does 'go help get'. See 'go help modules' and 'go help module-get'.

See also: go build, go install, go clean.


For example, showing verbose output,

$ go get -v github.com/capotej/groupcache-db-experiment/...
github.com/capotej/groupcache-db-experiment (download)
github.com/golang/groupcache (download)
github.com/golang/protobuf (download)
github.com/capotej/groupcache-db-experiment/api
github.com/capotej/groupcache-db-experiment/client
github.com/capotej/groupcache-db-experiment/slowdb
github.com/golang/groupcache/consistenthash
github.com/golang/protobuf/proto
github.com/golang/groupcache/lru
github.com/capotej/groupcache-db-experiment/dbserver
github.com/capotej/groupcache-db-experiment/cli
github.com/golang/groupcache/singleflight
github.com/golang/groupcache/groupcachepb
github.com/golang/groupcache
github.com/capotej/groupcache-db-experiment/frontend
$ 

How to set the min and max height or width of a Frame?

A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:

from tkinter import Frame, Tk

class MyApp():
    def __init__(self):
        self.root = Tk()

        self.my_frame_red = Frame(self.root, bg='red')
        self.my_frame_red.grid(row=0, column=0, sticky='nsew')

        self.my_frame_blue = Frame(self.root, bg='blue')
        self.my_frame_blue.grid(row=0, column=1, sticky='nsew')

        self.root.grid_rowconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(1, weight=1)

        self.root.mainloop()

if __name__ == '__main__':
    app = MyApp()

But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

to have unit-testing AND integration-testing you can use maven-surefire-plugin and maven-failsafe-plugin with restricted includes/excludes. I was playing with CDI while getting in touch with sonar/jacoco, so i ended up in this project:

https://github.com/FibreFoX/cdi-sessionscoped-login/

Maybe it helps you a little bit. in my pom.xml i use "-javaagent" implicit by setting the argLine-option in the configuration-section of the specified testing-plugins. Explicit using ANT in MAVEN projects is something i would not give a try, for me its to much mixing two worlds.

I only have a single-module maven project, but maybe it helps you to adjust yours to work.

note: maybe not all maven-plugins are up2date, maybe some issues are fixed in later versions

JavaScript file not updating no matter what I do

You are sure you are linking to the same file and then editing that same file?

On some browser, you can use CTRL F5 to force a refresh (on the PC). On the Mac, it is Cmd Shift R

Firebug also has a net tab with "Disable Browser Cache".

But I want to give a warning here: even if you can hard refresh, how do you know your customers are getting the latest version? So you need to check, rather than just making sure you and your program manager can do a hard refresh and just go home and take the paycheck next month. If you want to do a job that change the world for the better, or leave the world a little bit better than you found it, you need to investigate more to make sure it works for your customers too (or else, sometimes the customer may call tech support, and tech support may read the script of "clear out the cookies and it will work", which is what happens to me sometimes). Some methods down at the bottom of this post can ensure the customers get the latest version.

Update 2020:

If you are using Chrome and the DevTools is open, you can click and hold the Refresh icon in front of the address bar, and a box will pop up, and you can choose to "Hard Reload" or even "Empty Cache and Hard Reload":

hard reload button

Update 2017:

If you use the Google Chrome debugger, it is the same, you can go to the Network section and make sure the "Disable cache (while DevTools is open)" is checked, in the Settings of the debugger panel.

Also, when you link the JavaScript file, use

<script src="my-js-file.js?v=1"></script>

or v=2, and so forth, when you definitely want to refresh the file. Or you can go to the console and do a Date.now() and get a timestamp, such as 1491313943549, and use

<script src="my-js-file.js?t=1491313943549"></script>

Some building tools will do that automatically for you, or can be configured to do that, making it something like:

<script src="main.742a4952.js"></script>

which essentially will bust the cache.

Note that when you use the v=2 or t=1491313943549, or main.742a4952.js, you also have the advantage that for your users, they definitely will get the newer version as well.

Use multiple css stylesheets in the same html page

Here is a simple alternative:

1/ Suppose we have two css files, say my1.css and my2.css. In the html document head type a link to one of them, within an element with an ID, say "demo":

2/ In the html document head body define two buttons calling two JS functions:

select css1
select css2

3/ Finally, in the JS file type the two functions as follows:

function select_css1() {
document.getElementById("demo").innerHTML = ''; }

function select_css2() {
document.getElementById("demo").innerHTML = ''; }

Is jQuery $.browser Deprecated?

From the official documentation at http://api.jquery.com/jQuery.browser/:

This property was removed in jQuery 1.9 and is available only through the jQuery.migrate plugin.

You can use for example jquery-migrate-1.4.1.js to keep your existing code or plugins that use $.browser still working while you find a way to totally get rid of $.browser from your code in the future.

Using git commit -a with vim

The better question is: How do I interrupt the commit when I quit vim?

There are 2 ways:

  1. :cq or :cquit
  2. Delete all lines of the commit message, including comments, and then :wq

Either way will give git an error code, so it will not proceed with the commit. This is particularly useful with git commit --amend.

Determine distance from the top of a div to top of window with javascript

Vanilla:

window.addEventListener('scroll', function(ev) {

   var someDiv = document.getElementById('someDiv');
   var distanceToTop = someDiv.getBoundingClientRect().top;

   console.log(distanceToTop);
});

Open your browser console and scroll your page to see the distance.

Mythical man month 10 lines per developer day - how close on large projects?

I like this quote:

If we wish to count lines of code, we should not regard them as "lines produced" but as "lines spent". - Edsger Dijkstra

Some times you have contributed more by removing code than adding

How can I revert multiple Git commits (already pushed) to a published repository?

The Problem

There are a number of work-flows you can use. The main point is not to break history in a published branch unless you've communicated with everyone who might consume the branch and are willing to do surgery on everyone's clones. It's best not to do that if you can avoid it.

Solutions for Published Branches

Your outlined steps have merit. If you need the dev branch to be stable right away, do it that way. You have a number of tools for Debugging with Git that will help you find the right branch point, and then you can revert all the commits between your last stable commit and HEAD.

Either revert commits one at a time, in reverse order, or use the <first_bad_commit>..<last_bad_commit> range. Hashes are the simplest way to specify the commit range, but there are other notations. For example, if you've pushed 5 bad commits, you could revert them with:

# Revert a series using ancestor notation.
git revert --no-edit dev~5..dev

# Revert a series using commit hashes.
git revert --no-edit ffffffff..12345678

This will apply reversed patches to your working directory in sequence, working backwards towards your known-good commit. With the --no-edit flag, the changes to your working directory will be automatically committed after each reversed patch is applied.

See man 1 git-revert for more options, and man 7 gitrevisions for different ways to specify the commits to be reverted.

Alternatively, you can branch off your HEAD, fix things the way they need to be, and re-merge. Your build will be broken in the meantime, but this may make sense in some situations.

The Danger Zone

Of course, if you're absolutely sure that no one has pulled from the repository since your bad pushes, and if the remote is a bare repository, then you can do a non-fast-forward commit.

git reset --hard <last_good_commit>
git push --force

This will leave the reflog intact on your system and the upstream host, but your bad commits will disappear from the directly-accessible history and won't propagate on pulls. Your old changes will hang around until the repositories are pruned, but only Git ninjas will be able to see or recover the commits you made by mistake.

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

  1. Download winutils.exe
  2. Create folder, say C:\winutils\bin
  3. Copy winutils.exe inside C:\winutils\bin
  4. Set environment variable HADOOP_HOME to C:\winutils

Angular2 router (@angular/router), how to set default route?

V2.0.0 and later

See also see https://angular.io/guide/router#the-default-route-to-heroes

RouterConfig = [
  { path: '', redirectTo: '/heroes', pathMatch: 'full' },
  { path: 'heroes', component: HeroComponent,
    children: [
      { path: '', redirectTo: '/detail', pathMatch: 'full' },
      { path: 'detail', component: HeroDetailComponent }
    ] 
  }
];

There is also the catch-all route

{ path: '**', redirectTo: '/heroes', pathMatch: 'full' },

which redirects "invalid" urls.

V3-alpha (vladivostok)

Use path / and redirectTo

RouterConfig = [
  { path: '/', redirectTo: 'heroes', terminal: true },
  { path: 'heroes', component: HeroComponent,
    children: [
      { path: '/', redirectTo: 'detail', terminal: true },
      { path: 'detail', component: HeroDetailComponent }
    ] 
  }
];

RC.1 @angular/router

The RC router doesn't yet support useAsDefault. As a workaround you can navigate explicitely.

In the root component

export class AppComponent {
  constructor(router:Router) {
    router.navigate(['/Merge']);
  }
}

for other components

export class OtherComponent {
  constructor(private router:Router) {}

  routerOnActivate(curr: RouteSegment, prev?: RouteSegment, currTree?: RouteTree, prevTree?: RouteTree) : void {
    this.router.navigate(['SomeRoute'], curr);
  }
}

React ignores 'for' attribute of the label element

For React you must use it's per-define keywords to define html attributes.

class -> className

is used and

for -> htmlFor

is used, as react is case sensitive make sure you must follow small and capital as required.

How do I indent multiple lines at once in Notepad++?

Capslock + Tab to indent multiple lines at once. Highlight the text first.

Where does PostgreSQL store the database?

The location of specific tables/indexes can be adjusted by TABLESPACEs:

CREATE TABLESPACE dbspace LOCATION '/data/dbs';
CREATE TABLE something (......) TABLESPACE dbspace;
CREATE TABLE otherthing (......) TABLESPACE dbspace;

Notify ObservableCollection when Item changes

One simple solution to this is to replace the item being changed in the ObservableCollection which notifies the collection of the changed item. In the sample code snippet below Artists is the ObservableCollection and artist is an item of the type in the ObservableCollection:

    var index = Artists.IndexOf(artist);
    Artists.RemoveAt(index);
    artist.IsFollowed = true; // change something in the item
    Artists.Insert(index, artist);

CSS: On hover show and hide different div's at the same time?

http://jsfiddle.net/MBLZx/

Here is the code

_x000D_
_x000D_
 .showme{ _x000D_
   display: none;_x000D_
 }_x000D_
 .showhim:hover .showme{_x000D_
   display : block;_x000D_
 }_x000D_
 .showhim:hover .ok{_x000D_
   display : none;_x000D_
 }
_x000D_
 <div class="showhim">_x000D_
     HOVER ME_x000D_
     <div class="showme">hai</div>_x000D_
     <div class="ok">ok</div>_x000D_
</div>_x000D_
_x000D_
   
_x000D_
_x000D_
_x000D_

How do you add an ActionListener onto a JButton in Java

I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?

Necessary to add link tag for favicon.ico?

Update Oct 2020:

So if you are on this page scratching your head why my favicon is not working , then read along. I tried all the things (which I supposedly thought I was doing right) yet favicon was not showing up on browser tabs.

Here is one line simple cracker code that worked flawlessly:

<link rel="icon" href="https://abcde.neocities.org/bla123.jpg" size="16x16" type="image/jpg">

enter image description here

Notes:

  1. Put the image in the ROOT folder ( In one of my unsuccessful attempts , I was not using root dir)
  2. Use direct favicon url link ( instead of href="images/bla123.jpg").
  3. I placed this tag just below the <title> tag in the <Header>
  4. I made the favicon size 64x64 px and size was 2.16 KB

I tested it on Firefox, Chrome, Edge, and opera. OS: Win 10, Mac OSX, ios and Android .Also I did not experience any cashing issues, worked pretty much as soon as I refreshed the page.

Oracle JDBC ojdbc6 Jar as a Maven Dependency

Since Oracle is the licensed product, there are issue in adding maven dependency directly. To add any version of the ojdbc.jar, below 2 steps could do.

  1. Run the below command to install ojdbc.jar into local maven repository.
/opt/apache-maven/bin/mvn install:install-file
    -Dfile=<path-to-file>/ojdbc7.jar
    -DgroupId=com.oracle
    -DartifactId=ojdbc7
    -Dversion=12.1.0.1.0
    -Dpackaging=jar

This will add the dependency into local repository.

  1. Now, add the dependency in the pom file
<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.1.0</version>
</dependency>

How to clear text area with a button in html using javascript?

Your Html

<input type="button" value="Clear" onclick="clearContent()"> 
<textarea id='output' rows=20 cols=90></textarea>

Your Javascript

function clearContent()
{
    document.getElementById("output").value='';
}

Calling a Sub and returning a value

Sub don't return values and functions don't have side effects.

Sometimes you want both side effect and return value.

This is easy to be done once you know that VBA passes arguments by default by reference so you can write your code in this way:

Sub getValue(retValue as Long)
    ...
    retValue = 42 
End SUb 

Sub Main()
    Dim retValue As Long
    getValue retValue 
    ... 
End SUb

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

If you use Gradle, it is probably a problem with Gradle caches. (Reference). Alas, even if you run

gradle --refresh-dependencies

, it is not refreshing really all dependencies. Some rubbish remains. (Reference).

So, the most sure (but drastic and long) variant is to clear all inside from the [user]/.gradle/caches. Or to find your problem project there and clear only its caches.

How do I capture SIGINT in Python?

Personally, I couldn't use try/except KeyboardInterrupt because I was using standard socket (IPC) mode which is blocking. So the SIGINT was cueued, but came only after receiving data on the socket.

Setting a signal handler behaves the same.

On the other hand, this only works for an actual terminal. Other starting environments might not accept Ctrl+C, or pre-handle the signal.

Also, there are "Exceptions" and "BaseExceptions" in Python, which differ in the sense that interpreter needs to exit cleanly itself, so some exceptions have a higher priority than others (Exceptions is derived from BaseException)

Converting NSString to NSDate (and back again)

The above examples aren't simply written for Swift 3.0+

Update - Swift 3.0+ - Convert Date To String

let date = Date() // insert your date data here
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" // add custom format if you'd like 
var dateString = dateFormatter.string(from: date)

How to dump raw RTSP stream to file?

If you are reencoding in your ffmpeg command line, that may be the reason why it is CPU intensive. You need to simply copy the streams to the single container. Since I do not have your command line I cannot suggest a specific improvement here. Your acodec and vcodec should be set to copy is all I can say.

EDIT: On seeing your command line and given you have already tried it, this is for the benefit of others who come across the same question. The command:

ffmpeg -i rtsp://@192.168.241.1:62156 -acodec copy -vcodec copy c:/abc.mp4

will not do transcoding and dump the file for you in an mp4. Of course this is assuming the streamed contents are compatible with an mp4 (which in all probability they are).

Python: find position of element in array

For your first question, find the position of some value in a list x using index(), like so:

x.index(value)

For your second question, to check for multiple same values you should split your list into chunks and use the same logic from above. They say divide and conquer. It works. Try this:

value = 1 
x = [1,2,3,4,5,6,2,1,4,5,6]

chunk_a = x[:int(len(x)/2)] # get the first half of x 
chunk_b = x[int(len(x)/2):] # get the rest half of x

print(chunk_a.index(value))
print(chunk_b.index(value))

Hope that helps!

Python convert decimal to hex

If you want to code this yourself instead of using the built-in function hex(), you can simply do the recursive call before you print the current digit:

def ChangeHex(n):
    if (n < 0):
        print(0)
    elif (n<=1):
        print n,
    else:
        ChangeHex( n / 16 )
        x =(n%16)
        if (x < 10):
            print(x), 
        if (x == 10):
            print("A"),
        if (x == 11):
            print("B"),
        if (x == 12):
            print("C"),
        if (x == 13):
            print("D"),
        if (x == 14):
            print("E"),
        if (x == 15):
            print ("F"),

Set background colour of cell to RGB value of data in cell

Sub AddColor()
    For Each cell In Selection
        R = Round(cell.Value)
        G = Round(cell.Offset(0, 1).Value)
        B = Round(cell.Offset(0, 2).Value)
        Cells(cell.Row, 1).Resize(1, 4).Interior.Color = RGB(R, G, B)
    Next cell
End Sub

Assuming that there are 3 columns R, G and B (in this order). Select first column ie R. press alt+F11 and run the above code. We have to select the first column (containing R or red values) and run the code every time we change the values to reflect the changes.

I hope this simpler code helps !

Saving Excel workbook to constant path with filename from two fields

try

Sub save()
ActiveWorkbook.SaveAS Filename:="C:\-docs\cmat\Desktop\New folder\" & Range("C5").Text & chr(32) & Range("C8").Text &".xls", FileFormat:= _
  xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
 , CreateBackup:=False
End Sub

If you want to save the workbook with the macros use the below code

Sub save()
ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
    "\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xlsm", FileFormat:= _
    xlOpenXMLWorkbookMacroEnabled, Password:=vbNullString, WriteResPassword:=vbNullString, _
    ReadOnlyRecommended:=False, CreateBackup:=False
End Sub

if you want to save workbook with no macros and no pop-up use this

Sub save()
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
    "\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xls", _
    FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    Application.DisplayAlerts = True
End Sub

maxReceivedMessageSize and maxBufferSize in app.config

Open app.config on client side and add maxBufferSize and maxReceivedMessageSize attributes if it is not available

Original

  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="Service1Soap"/>
      </basicHttpBinding>
    </bindings>

After Edit/Update

  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="Service1Soap" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"/>
      </basicHttpBinding>
    </bindings>

Python: CSV write by column rather than row

Let's assume that (1) you don't have a large memory (2) you have row headings in a list (3) all the data values are floats; if they're all integers up to 32- or 64-bits worth, that's even better.

On a 32-bit Python, storing a float in a list takes 16 bytes for the float object and 4 bytes for a pointer in the list; total 20. Storing a float in an array.array('d') takes only 8 bytes. Increasingly spectacular savings are available if all your data are int (any negatives?) that will fit in 8, 4, 2 or 1 byte(s) -- especially on a recent Python where all ints are longs.

The following pseudocode assumes floats stored in array.array('d'). In case you don't really have a memory problem, you can still use this method; I've put in comments to indicate the changes needed if you want to use a list.

# Preliminary:
import array # list: delete
hlist = []
dlist = []
for each row: 
    hlist.append(some_heading_string)
    dlist.append(array.array('d')) # list: dlist.append([])
# generate data
col_index = -1
for each column:
    col_index += 1
    for row_index in xrange(len(hlist)):
        v = calculated_data_value(row_index, colindex)
        dlist[row_index].append(v)
# write to csv file
for row_index in xrange(len(hlist)):
    row = [hlist[row_index]]
    row.extend(dlist[row_index])
    csv_writer.writerow(row)

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

You'll need to post your statement for more clarification. But...

That error means that the table you are inserting data into has a foreign key relationship with another table. Before data can be inserted, the value in the foreign key field must exist in the other table first.

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

What It Is

This is an arrow function. Arrow functions are a short syntax, introduced by ECMAscript 6, that can be used similarly to the way you would use function expressions. In other words, you can often use them in place of expressions like function (foo) {...}. But they have some important differences. For example, they do not bind their own values of this (see below for discussion).

Arrow functions are part of the ECMAscript 6 specification. They are not yet supported in all browsers, but they are partially or fully supported in Node v. 4.0+ and in most modern browsers in use as of 2018. (I’ve included a partial list of supporting browsers below).

You can read more in the Mozilla documentation on arrow functions.

From the Mozilla documentation:

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous. These function expressions are best suited for non-method functions and they can not be used as constructors.

A Note on How this Works in Arrow Functions

One of the most handy features of an arrow function is buried in the text above:

An arrow function... lexically binds the this value (does not bind its own this...)

What this means in simpler terms is that the arrow function retains the this value from its context and does not have its own this. A traditional function may bind its own this value, depending on how it is defined and called. This can require lots of gymnastics like self = this;, etc., to access or manipulate this from one function inside another function. For more info on this topic, see the explanation and examples in the Mozilla documentation.

Example Code

Example (also from the docs):

var a = [
  "We're up all night 'til the sun",
  "We're up all night to get some",
  "We're up all night for good fun",
  "We're up all night to get lucky"
];

// These two assignments are equivalent:

// Old-school:
var a2 = a.map(function(s){ return s.length });

// ECMAscript 6 using arrow functions
var a3 = a.map( s => s.length );

// both a2 and a3 will be equal to [31, 30, 31, 31]

Notes on Compatibility

You can use arrow functions in Node, but browser support is spotty.

Browser support for this functionality has improved quite a bit, but it still is not widespread enough for most browser-based usages. As of December 12, 2017, it is supported in current versions of:

  • Chrome (v. 45+)
  • Firefox (v. 22+)
  • Edge (v. 12+)
  • Opera (v. 32+)
  • Android Browser (v. 47+)
  • Opera Mobile (v. 33+)
  • Chrome for Android (v. 47+)
  • Firefox for Android (v. 44+)
  • Safari (v. 10+)
  • iOS Safari (v. 10.2+)
  • Samsung Internet (v. 5+)
  • Baidu Browser (v. 7.12+)

Not supported in:

  • IE (through v. 11)
  • Opera Mini (through v. 8.0)
  • Blackberry Browser (through v. 10)
  • IE Mobile (through v. 11)
  • UC Browser for Android (through v. 11.4)
  • QQ (through v. 1.2)

You can find more (and more current) information at CanIUse.com (no affiliation).

Greyscale Background Css Images

You can also use:

img{
   filter:grayscale(100%);
}


img:hover{
   filter:none;
}

How to pass the button value into my onclick event function?

You can pass the value to the function using this.value, where this points to the button

<input type="button" value="mybutton1" onclick="dosomething(this.value)">

And then access that value in the function

function dosomething(val){
  console.log(val);
}

How to upgrade Angular CLI to the latest version

In addition to @ShinDarth answer.

I did what he said but my package did not updated the angular version, and I know that this post is about angular-cli, but i think that this can help too.

  • so after doing what @ShinDarth said above, to fix my angular version I had to create a new project with -ng new projectname that generated a package.
  • copy the new package, then paste the new package on all projects packages needing update (remember to add the dependencies you had and change the name on first line) or you can just change the versions manualy without copy and paste.
  • then run -npm install.

Now my ng serve is working again, maybe there is a better way to do all that, if someone know, please share, because this is a pain to do with all projects that need update.

Javascript : natural sort of alphanumerical strings

To compare values you can use a comparing method-

function naturalSorter(as, bs){
    var a, b, a1, b1, i= 0, n, L,
    rx=/(\.\d+)|(\d+(\.\d+)?)|([^\d.]+)|(\.\D+)|(\.$)/g;
    if(as=== bs) return 0;
    a= as.toLowerCase().match(rx);
    b= bs.toLowerCase().match(rx);
    L= a.length;
    while(i<L){
        if(!b[i]) return 1;
        a1= a[i],
        b1= b[i++];
        if(a1!== b1){
            n= a1-b1;
            if(!isNaN(n)) return n;
            return a1>b1? 1:-1;
        }
    }
    return b[i]? -1:0;
}

But for speed in sorting an array, rig the array before sorting, so you only have to do lower case conversions and the regular expression once instead of in every step through the sort.

function naturalSort(ar, index){
    var L= ar.length, i, who, next, 
    isi= typeof index== 'number', 
    rx=  /(\.\d+)|(\d+(\.\d+)?)|([^\d.]+)|(\.(\D+|$))/g;
    function nSort(aa, bb){
        var a= aa[0], b= bb[0], a1, b1, i= 0, n, L= a.length;
        while(i<L){
            if(!b[i]) return 1;
            a1= a[i];
            b1= b[i++];
            if(a1!== b1){
                n= a1-b1;
                if(!isNaN(n)) return n;
                return a1>b1? 1: -1;
            }
        }
        return b[i]!= undefined? -1: 0;
    }
    for(i= 0; i<L; i++){
        who= ar[i];
        next= isi? ar[i][index] || '': who;
        ar[i]= [String(next).toLowerCase().match(rx), who];
    }
    ar.sort(nSort);
    for(i= 0; i<L; i++){
        ar[i]= ar[i][1];
    }
}

Calling Java from Python

If you're in Python 3, there's a fork of JPype called JPype1-py3

pip install JPype1-py3

This works for me on OSX / Python 3.4.3. (You may need to export JAVA_HOME=/Library/Java/JavaVirtualMachines/your-java-version)

from jpype import *
startJVM(getDefaultJVMPath(), "-ea")
java.lang.System.out.println("hello world")
shutdownJVM()

How can I set the font-family & font-size inside of a div?

You need a semicolon after font-family: Arial, Helvetica, sans-serif. This will make your updated code the following:

<!DOCTYPE>
<html>
    <head>
        <title>DIV Font</title>

        <style>
            .my_text
            {
                font-family:    Arial, Helvetica, sans-serif;
                font-size:      40px;
                font-weight:    bold;
            }
        </style>
    </head>

    <body>
        <div class="my_text">some text</div>
    </body>
</html>

How to remove numbers from string using Regex.Replace?

Try the following:

var output = Regex.Replace(input, @"[\d-]", string.Empty);

The \d identifier simply matches any digit character.

How to see query history in SQL Server Management Studio

I use the below query for tracing application activity on a SQL server that does not have trace profiler enabled. The method uses Query Store (SQL Server 2016+) instead of the DMV's. This gives better ability to look into historical data, as well as faster lookups. It is very efficient to capture short-running queries that can't be captured by sp_who/sp_whoisactive.

/* Adjust script to your needs.
    Run full script (F5) -> Interact with UI -> Run full script again (F5)
    Output will contain the queries completed in that timeframe.
*/

/* Requires Query Store to be enabled:
    ALTER DATABASE <db> SET QUERY_STORE = ON
    ALTER DATABASE <db> SET QUERY_STORE (OPERATION_MODE = READ_WRITE, MAX_STORAGE_SIZE_MB = 100000)
*/

USE <db> /* Select your DB */

IF OBJECT_ID('tempdb..#lastendtime') IS NULL
    SELECT GETUTCDATE() AS dt INTO #lastendtime
ELSE IF NOT EXISTS (SELECT * FROM #lastendtime)
    INSERT INTO #lastendtime VALUES (GETUTCDATE()) 

;WITH T AS (
SELECT 
    DB_NAME() AS DBName
    , s.name + '.' + o.name AS ObjectName
    , qt.query_sql_text
    , rs.runtime_stats_id
    , p.query_id
    , p.plan_id
    , CAST(p.last_execution_time AS DATETIME) AS last_execution_time
    , CASE WHEN p.last_execution_time > #lastendtime.dt THEN 'X' ELSE '' END AS New
    , CAST(rs.last_duration / 1.0e6 AS DECIMAL(9,3)) last_duration_s
    , rs.count_executions
    , rs.last_rowcount
    , rs.last_logical_io_reads
    , rs.last_physical_io_reads
    , q.query_parameterization_type_desc
FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY plan_id, runtime_stats_id ORDER BY runtime_stats_id DESC) AS recent_stats_in_current_priod
    FROM sys.query_store_runtime_stats 
    ) AS rs
INNER JOIN sys.query_store_runtime_stats_interval AS rsi ON rsi.runtime_stats_interval_id = rs.runtime_stats_interval_id
INNER JOIN sys.query_store_plan AS p ON p.plan_id = rs.plan_id
INNER JOIN sys.query_store_query AS q ON q.query_id = p.query_id
INNER JOIN sys.query_store_query_text AS qt ON qt.query_text_id = q.query_text_id
LEFT OUTER JOIN sys.objects AS o ON o.object_id = q.object_id
LEFT OUTER JOIN sys.schemas AS s ON s.schema_id = o.schema_id
CROSS APPLY #lastendtime
WHERE rsi.start_time <= GETUTCDATE() AND GETUTCDATE() < rsi.end_time
    AND recent_stats_in_current_priod = 1
    /* Adjust your filters: */
    -- AND (s.name IN ('<myschema>') OR s.name IS NULL)
UNION
SELECT NULL,NULL,NULL,NULL,NULL,NULL,dt,NULL,NULL,NULL,NULL,NULL,NULL, NULL
FROM #lastendtime
)
SELECT * FROM T
WHERE T.query_sql_text IS NULL OR T.query_sql_text NOT LIKE '%#lastendtime%' -- do not show myself
ORDER BY last_execution_time DESC

TRUNCATE TABLE #lastendtime
INSERT INTO #lastendtime VALUES (GETUTCDATE()) 

Error related to only_full_group_by when executing a query in MySql

This is what helped me to understand the entire issue:

  1. https://stackoverflow.com/a/20074634/1066234
  2. https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

And in the following another example of a problematic query.

Problematic:

SELECT COUNT(*) as attempts, SUM(elapsed) as elapsedtotal, userid, timestamp, questionid, answerid, SUM(correct) as correct, elapsed, ipaddress FROM `gameplay`
                        WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 1 DAY)
                        AND cookieid = #

Solved by adding this to the end:

  GROUP BY timestamp, userid, cookieid, questionid, answerid, elapsed, ipaddress

Note: See the error message in PHP, it tells you where the problem lies.

Example:

MySQL query error 1140: In aggregated query without GROUP BY, expression #4 of SELECT list contains nonaggregated column 'db.gameplay.timestamp'; this is incompatible with sql_mode=only_full_group_by - Query: SELECT COUNT(*) as attempts, SUM(elapsed) as elapsedtotal, userid, timestamp, questionid, answerid, SUM(correct) as correct, elapsed, ipaddress FROM gameplay WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 1 DAY) AND userid = 1

In this case, expression #4 was missing in the GROUP BY.

Select dropdown with fixed width cutting off content in IE

similar solution can be found here using jquery to set the auto width when focus (or mouseenter) and set the orignal width back when blur (or mouseleave) http://css-tricks.com/select-cuts-off-options-in-ie-fix/.

How to hide a div from code (c#)

u can also try from yours design

    <div <%=If(True = True, "style='display: none;'", "")%> >True</div>
<div <%=If(True = False, "style='display: none;'", "")%> >False</div>
<div <%=If(Session.Item("NameExist") IsNot Nothing, "style='display: none;'", "")%> >NameExist</div>
<div <%=If(Session.Item("NameNotExist") IsNot Nothing, "style='display: none;'", "")%> >NameNotExist</div>

Output html

    <div style='display: none;' > True</div>
<div  >False</div>
<div style='display: none;' >NameExist</div>
<div  >NameNotExist</div>

How do I set the background color of Excel cells using VBA?

or alternatively you could not bother coding for it and use the 'conditional formatting' function in Excel which will set the background colour and font colour based on cell value.

There are only two variables here so set the default to yellow and then overwrite when the value is greater than or less than your threshold values.

How to get IP address of running docker container

while read ctr;do
    sudo docker inspect --format "$ctr "'{{.Name}}{{ .NetworkSettings.IPAddress }}' $ctr
done < <(docker ps -a --filter status=running --format '{{.ID}}')

How to add a classname/id to React-Bootstrap Component?

If you look at the code for the component you can see that it uses the className prop passed to it to combine with the row class to get the resulting set of classes (<Row className="aaa bbb"... works).Also, if you provide the id prop like <Row id="444" ... it will actually set the id attribute for the element.

How To: Execute command line in C#, get STD OUT results

There one other parameter I found useful, which I use to eliminate the process window

pProcess.StartInfo.CreateNoWindow = true;

this helps to hide the black console window from user completely, if that is what you desire.

Foreach loop, determine which is the last iteration of the loop

The accepted answer will not work for duplicates in the collection. If you're set on the foreach, you can just add your own indexing variable(s).

int last = Model.Results.Count - 1;
int index = 0;
foreach (Item result in Model.Results)
{
    //Do Things

    if (index == last)
        //Do Things with the last result

    index++;
}

Alternative to header("Content-type: text/xml");

No. You can't send headers after they were sent. Try to use hooks in wordpress

Connecting to SQL Server Express - What is my server name?

This was provided after installation of Sql Express 2019

Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;

So just use 'localhost\SQLEXPRESS' in server name and windows authentication worked for me.

enter image description here

When to use the !important property in CSS

This is the real life scenario

Imagine this scenario

  1. You have a global CSS file that sets visual aspects of your site globally.
  2. You (or others) use inline styles on elements themselves which is usually very bad practice.

In this case you could set certain styles in your global CSS file as important, thus overriding inline styles set directly on elements.

Actual real world example?

This kind of scenario usually happens when you don't have total control over your HTML. Think of solutions in SharePoint for instance. You'd like your part to be globally defined (styled), but some inline styles you can't control are present. !important makes such situations easier to deal with.

Other real life scenarios would also include some badly written jQuery plugins that also use inline styles...

I suppose you got the idea by now and can come up with some others as well.

When do you decide to use !important?

I suggest you don't use !important unless you can't do it any other way. Whenever it's possible to avoid it, avoid it. Using lots of !important styles will make maintenance a bit harder, because you break the natural cascading in your stylesheets.

How to use patterns in a case statement?

if and grep -Eq

arg='abc'
if echo "$arg" | grep -Eq 'a.c|d.*'; then
  echo 'first'
elif echo "$arg" | grep -Eq 'a{2,3}'; then
  echo 'second'
fi

where:

  • -q prevents grep from producing output, it just produces the exit status
  • -E enables extended regular expressions

I like this because:

One downside is that this is likely slower than case since it calls an external grep program, but I tend to consider performance last when using Bash.

case is POSIX 7

Bash appears to follow POSIX by default without shopt as mentioned by https://stackoverflow.com/a/4555979/895245

Here is the quote: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_01 section "Case Conditional Construct":

The conditional construct case shall execute the compound-list corresponding to the first one of several patterns (see Pattern Matching Notation) [...] Multiple patterns with the same compound-list shall be delimited by the '|' symbol. [...]

The format for the case construct is as follows:

case word in
     [(] pattern1 ) compound-list ;;
     [[(] pattern[ | pattern] ... ) compound-list ;;] ...
     [[(] pattern[ | pattern] ... ) compound-list]
  esac

and then http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13 section "2.13. Pattern Matching Notation" only mentions ?, * and [].

X-Frame-Options on apache

  1. You can add to .htaccess, httpd.conf or VirtualHost section
  2. Header set X-Frame-Options SAMEORIGIN this is the best option

Allow from URI is not supported by all browsers. Reference: X-Frame-Options on MDN

How can I style even and odd elements?

Below is the example of even and odd css color apply

<html>
<head>
<style> 
p:nth-child(even) {
    background: red;
}
p:nth-child(odd) {
    background: green;
}
</style>
</head>
<body>

<p>The first Odd.</p>
<p>The second Even.</p>
<p>The third Odd.</p>
<p>The fourth Even.</p>


</body>
</html>