Programs & Examples On #Ws ex layered

Private Variables and Methods in Python

The double underscore. It mangles the name in such a way that it can't be accessed simply through __fieldName from outside the class, which is what you want to begin with if they're to be private. (Though it's still not very hard to access the field.)

class Foo:
    def __init__(self):
        self.__privateField = 4;
        print self.__privateField # yields 4 no problem

foo = Foo()
foo.__privateField
# AttributeError: Foo instance has no attribute '__privateField'

It will be accessible through _Foo__privateField instead. But it screams "I'M PRIVATE DON'T TOUCH ME", which is better than nothing.

"Android library projects cannot be launched"?

From Android's Developer Documentation on Managing Projects from Eclipse with ADT:

Setting up a Library Project

Next, set the project's Properties to indicate that it is a library project:

  1. In the Package Explorer, right-click the library project and select Properties.
  2. In the Properties window, select the "Android" properties group at left and locate the Library properties at right.
  3. Select the "is Library" checkbox and click Apply.
  4. Click OK to close the Properties window.

So, open your project properties, un-select the "Is Library" checkbox, and click Apply to make your project a normal Android project (not a library project).

Using PUT method in HTML form

Unfortunately, modern browsers do not provide native support for HTTP PUT requests. To work around this limitation, ensure your HTML form’s method attribute is “post”, then add a method override parameter to your HTML form like this:

<input type="hidden" name="_METHOD" value="PUT"/>

To test your requests you can use "Postman" a google chrome extension

Android Studio with Google Play Services

I copied the play libs files from the google-play-services_lib to my project libs directory:

  • google-play-services.jar
  • google-play-services.jar.properties.

Then selected them, right-click, "Add as libraries".

Copy Image from Remote Server Over HTTP

You've got about these four possibilities:

  • Remote files. This needs allow_url_fopen to be enabled in php.ini, but it's the easiest method.

  • Alternatively you could use cURL if your PHP installation supports it. There's even an example.

  • And if you really want to do it manually use the HTTP module.

  • Don't even try to use sockets directly.

Last Run Date on a Stored Procedure in SQL Server

I use this:

use YourDB;

SELECT 
    object_name(object_id), 
    last_execution_time, 
    last_elapsed_time, 
    execution_count
FROM   
     sys.dm_exec_procedure_stats ps 
where 
      lower(object_name(object_id)) like 'Appl-Name%'
order by 1

Fragment MyFragment not attached to Activity

if (getActivity() == null) return;

works also in some cases. Just breaks the code execution from it and make sure the app not crash

How do I change the hover over color for a hover over table in Bootstrap?

For me @pvskisteak5 answer has caused a "flicker-effect". To fix this, add the following:

            .table-hover tbody tr:hover,
            .table-hover tbody tr:hover td,
            .table-hover tbody tr:hover th{
                background:#22313F !important;
                color:#fff !important;
            }

how to compare two string dates in javascript?

You can use "Date.parse()" to properly compare the dates, but since in most of the comments people are trying to split the string and then trying to add up the digits and compare with obviously wrong logic -not completely.

Here's the trick. If you are breaking the string then compare the parts in nested format.

Compare year with year, month with month and day with day.

<pre><code>

var parts1 = "26/07/2020".split('/');
var parts2 = "26/07/2020".split('/');

var latest = false;

if (parseInt(parts1[2]) > parseInt(parts2[2])) {
    latest = true;
} else if (parseInt(parts1[2]) == parseInt(parts2[2])) {
    if (parseInt(parts1[1]) > parseInt(parts2[1])) {
        latest = true;
    } else if (parseInt(parts1[1]) == parseInt(parts2[1])) {
        if (parseInt(parts1[0]) >= parseInt(parts2[0])) {
            latest = true;
        } 
    }
}

return latest;

</code></pre>

How do you get the list of targets in a makefile?

This is an attempt to improve on Brent Bradburn's great approach as follows:

  • uses a more robust command to extract the target names, which hopefully prevents any false positives (and also does away with the unnecessary sh -c)
  • does not invariably target the makefile in the current directory; respects makefiles explicitly specified with -f <file>
  • excludes hidden targets - by convention, these are targets whose name starts neither with a letter nor a digit
  • makes do with a single phony target
  • prefixes the command with @ to prevent it from being echoed before execution

Curiously, GNU make has no feature for listing just the names of targets defined in a makefile. While the -p option produces output that includes all targets, it buries them in a lot of other information and also executes the default target (which could be suppressed with -f/dev/null).

Place the following rule in a makefile for GNU make to implement a target named list that simply lists all target names in alphabetical order - i.e.: invoke as make list:

.PHONY: list
list:
    @$(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | sort | egrep -v -e '^[^[:alnum:]]' -e '^$@$$'

Important: On pasting this, make sure that the last line is indented by exactly 1 actual tab char. (spaces do not work).

Note that sorting the resulting list of targets is the best option, since not sorting doesn't produce a helpful ordering in that the order in which the targets appear in the makefile is not preserved.
Also, the sub-targets of a rule comprising multiple targets are invariably output separately and will therefore, due to sorting, usually not appear next to one another; e.g., a rule starting with a z: will not have targets a and z listed next to each other in the output, if there are additional targets.

Explanation of the rule:

  • .PHONY: list

    • declares target list a phony target, i.e., one not referring to a file, which should therefore have its recipe invoked unconditionally
  • $(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null

    • Invokes make again in order to print and parse the database derived from the makefile:
      • -p prints the database
      • -Rr suppresses inclusion of built-in rules and variables
      • -q only tests the up-to-date-status of a target (without remaking anything), but that by itself doesn't prevent execution of recipe commands in all cases; hence:
      • -f $(lastword $(MAKEFILE_LIST)) ensures that the same makefile is targeted as in the original invocation, regardless of whether it was targeted implicitly or explicitly with -f ....
        Caveat: This will break if your makefile contains include directives; to address this, define variable THIS_FILE := $(lastword $(MAKEFILE_LIST)) before any include directives and use -f $(THIS_FILE) instead.
      • : is a deliberately invalid target that is meant to ensure that no commands are executed; 2>/dev/null suppresses the resulting error message. Note: This relies on -p printing the database nonetheless, which is the case as of GNU make 3.82. Sadly, GNU make offers no direct option to just print the database, without also executing the default (or given) task; if you don't need to target a specific Makefile, you may use make -p -f/dev/null, as recommended in the man page.
  • -v RS=

    • This is an awk idiom that breaks the input into blocks of contiguous non-empty lines.
  • /^# File/,/^# Finished Make data base/

    • Matches the range of lines in the output that contains all targets (true as of GNU make 3.82) - by limiting parsing to this range, there is no need to deal with false positives from other output sections.
  • if ($$1 !~ "^[#.]")

    • Selectively ignores blocks:
      • # ... ignores non-targets, whose blocks start with # Not a target:
      • . ... ignores special targets
    • All other blocks should each start with a line containing only the name of an explicitly defined target followed by :
  • egrep -v -e '^[^[:alnum:]]' -e '^$@$$' removes unwanted targets from the output:

    • '^[^[:alnum:]]' ... excludes hidden targets, which - by convention - are targets that start neither with a letter nor a digit.
    • '^$@$$' ... excludes the list target itself

Running make list then prints all targets, each on its own line; you can pipe to xargs to create a space-separated list instead.

What datatype should be used for storing phone numbers in SQL Server 2005?

Use data type long instead.. dont use int because it only allows whole numbers between -32,768 and 32,767 but if you use long data type you can insert numbers between -2,147,483,648 and 2,147,483,647.

Expand a div to fill the remaining width

I don't understand why people are willing to work so hard to find a pure-CSS solution for simple columnar layouts that are SO EASY using the old TABLE tag.

All Browsers still have the table layout logic... Call me a dinosaur perhaps, but I say let it help you.

_x000D_
_x000D_
<table WIDTH=100% border=0 cellspacing=0 cellpadding=2>_x000D_
  <tr>_x000D_
    <td WIDTH="1" NOWRAP bgcolor="#E0E0E0">Tree</td>_x000D_
    <td bgcolor="#F0F0F0">View</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Much less risky in terms of cross-browser compatibility too.

How to to send mail using gmail in Laravel?

All you have to do is just edit in you.env file, that's it.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=<your_email_address>
MAIL_PASSWORD=<your_gmail_app_password_>
MAIL_ENCRYPTION=ssl

for app password goto https://support.google.com/accounts/answer/185833?hl=en

and genearate your app pasword and save for future use. because once you generate app password you cannot re-edit password or change same app password.(you can create multiple app password)

database vs. flat files

  1. Databases can handle querying tasks, so you don't have to walk over files manually. Databases can handle very complicated queries.
  2. Databases can handle indexing tasks, so if tasks like get record with id = x can be VERY fast
  3. Databases can handle multiprocess/multithreaded access.
  4. Databases can handle access from network
  5. Databases can watch for data integrity
  6. Databases can update data easily (see 1) )
  7. Databases are reliable
  8. Databases can handle transactions and concurrent access
  9. Databases + ORMs let you manipulate data in very programmer friendly way.

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

Value Change Listener to JTextField

Add a listener to the underlying Document, which is automatically created for you.

// Listen for changes in the text
textField.getDocument().addDocumentListener(new DocumentListener() {
  public void changedUpdate(DocumentEvent e) {
    warn();
  }
  public void removeUpdate(DocumentEvent e) {
    warn();
  }
  public void insertUpdate(DocumentEvent e) {
    warn();
  }

  public void warn() {
     if (Integer.parseInt(textField.getText())<=0){
       JOptionPane.showMessageDialog(null,
          "Error: Please enter number bigger than 0", "Error Message",
          JOptionPane.ERROR_MESSAGE);
     }
  }
});

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this http://api.jquery.com/load/

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

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

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }

   $("#refresh-btn").on("click", RefreshTable);

   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


});
</script>

Undefined reference to sqrt (or other mathematical functions)

You may find that you have to link with the math libraries on whatever system you're using, something like:

gcc -o myprog myprog.c -L/path/to/libs -lm
                                       ^^^ - this bit here.

Including headers lets a compiler know about function declarations but it does not necessarily automatically link to the code required to perform that function.

Failing that, you'll need to show us your code, your compile command and the platform you're running on (operating system, compiler, etc).

The following code compiles and links fine:

#include <math.h>
int main (void) {
    int max = sqrt (9);
    return 0;
}

Just be aware that some compilation systems depend on the order in which libraries are given on the command line. By that, I mean they may process the libraries in sequence and only use them to satisfy unresolved symbols at that point in the sequence.

So, for example, given the commands:

gcc -o plugh plugh.o -lxyzzy
gcc -o plugh -lxyzzy plugh.o

and plugh.o requires something from the xyzzy library, the second may not work as you expect. At the point where you list the library, there are no unresolved symbols to satisfy.

And when the unresolved symbols from plugh.o do appear, it's too late.

No assembly found containing an OwinStartupAttribute Error

Add below code to your web.config file then run the project...

    <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
    </dependentAssembly>
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
    </dependentAssembly>
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
    </dependentAssembly>
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
    </dependentAssembly>
    </runtime>

How to configure custom PYTHONPATH with VM and PyCharm?

In Intellij v2017.2 you can go to:

run > edit configurations > click ... next to the field 'Environment variables' > click the green + sign

Name= PYTHONPATH

value= your_python_path

How do I show the value of a #define at compile-time?

Looking at the output of the preprocessor is the closest thing to the answer you ask for.

I know you've excluded that (and other ways), but I'm not sure why. You have a specific enough problem to solve, but you have not explained why any of the "normal" methods don't work well for you.

Adding Google Play services version to your app's manifest?

In my case, I needed to copy the google-play-services_lib FOLDER in the same DRIVE of the source codes of my apps

  • F:\Products\Android\APP*.java <- My Apps are here so I copied to folder below
  • F:\Products\Android\libs\google-play-services_lib

How to generate keyboard events?

It can be done using ctypes:

import ctypes
from ctypes import wintypes
import time

user32 = ctypes.WinDLL('user32', use_last_error=True)

INPUT_MOUSE    = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2

KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP       = 0x0002
KEYEVENTF_UNICODE     = 0x0004
KEYEVENTF_SCANCODE    = 0x0008

MAPVK_VK_TO_VSC = 0

# msdn.microsoft.com/en-us/library/dd375731
VK_TAB  = 0x09
VK_MENU = 0x12

# C struct definitions

wintypes.ULONG_PTR = wintypes.WPARAM

class MOUSEINPUT(ctypes.Structure):
    _fields_ = (("dx",          wintypes.LONG),
                ("dy",          wintypes.LONG),
                ("mouseData",   wintypes.DWORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

class KEYBDINPUT(ctypes.Structure):
    _fields_ = (("wVk",         wintypes.WORD),
                ("wScan",       wintypes.WORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

    def __init__(self, *args, **kwds):
        super(KEYBDINPUT, self).__init__(*args, **kwds)
        # some programs use the scan code even if KEYEVENTF_SCANCODE
        # isn't set in dwFflags, so attempt to map the correct code.
        if not self.dwFlags & KEYEVENTF_UNICODE:
            self.wScan = user32.MapVirtualKeyExW(self.wVk,
                                                 MAPVK_VK_TO_VSC, 0)

class HARDWAREINPUT(ctypes.Structure):
    _fields_ = (("uMsg",    wintypes.DWORD),
                ("wParamL", wintypes.WORD),
                ("wParamH", wintypes.WORD))

class INPUT(ctypes.Structure):
    class _INPUT(ctypes.Union):
        _fields_ = (("ki", KEYBDINPUT),
                    ("mi", MOUSEINPUT),
                    ("hi", HARDWAREINPUT))
    _anonymous_ = ("_input",)
    _fields_ = (("type",   wintypes.DWORD),
                ("_input", _INPUT))

LPINPUT = ctypes.POINTER(INPUT)

def _check_count(result, func, args):
    if result == 0:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

user32.SendInput.errcheck = _check_count
user32.SendInput.argtypes = (wintypes.UINT, # nInputs
                             LPINPUT,       # pInputs
                             ctypes.c_int)  # cbSize

# Functions

def PressKey(hexKeyCode):
    x = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wVk=hexKeyCode))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def ReleaseKey(hexKeyCode):
    x = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wVk=hexKeyCode,
                            dwFlags=KEYEVENTF_KEYUP))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def AltTab():
    """Press Alt+Tab and hold Alt key for 2 seconds
    in order to see the overlay.
    """
    PressKey(VK_MENU)   # Alt
    PressKey(VK_TAB)    # Tab
    ReleaseKey(VK_TAB)  # Tab~
    time.sleep(2)
    ReleaseKey(VK_MENU) # Alt~

if __name__ == "__main__":
    AltTab()

hexKeyCode is the virtual keyboard mapping as defined by the Windows API. The list of codes is available on MSDN: Virtual-Key Codes (Windows)

What is the difference between char array and char pointer in C?

From APUE, Section 5.14 :

char    good_template[] = "/tmp/dirXXXXXX"; /* right way */
char    *bad_template = "/tmp/dirXXXXXX";   /* wrong way*/

... For the first template, the name is allocated on the stack, because we use an array variable. For the second name, however, we use a pointer. In this case, only the memory for the pointer itself resides on the stack; the compiler arranges for the string to be stored in the read-only segment of the executable. When the mkstemp function tries to modify the string, a segmentation fault occurs.

The quoted text matches @Ciro Santilli 's explanation.

How to analyze a JMeter summary report?

A Jmeter Test Plan must have listener to showcase the result of performance test execution.

  • Listeners capture the response coming back from Server while Jmeter runs and showcase in the form of – tree, tables, graphs and log files.

  • It also allows you to save the result in a file for future reference. There are many types of listeners Jmeter provides. Some of them are: Summary Report, Aggregate Report, Aggregate Graph, View Results Tree, View Results in Table etc.

Here is the detailed understanding of each parameter in Summary report.

By referring to the figure:

image

Label: It is the name/URL for the specific HTTP(s) Request. If you have selected “Include group name in label?” option then the name of the Thread Group is applied as the prefix to each label.

Samples: This indicates the number of virtual users per request.

Average: It is the average time taken by all the samples to execute specific label. In our case, the average time for Label 1 is 942 milliseconds & total average time is 584 milliseconds.

Min: The shortest time taken by a sample for specific label. If we look at Min value for Label 1 then, out of 20 samples shortest response time one of the sample had was 584 milliseconds.

Max: The longest time taken by a sample for specific label. If we look at Max value for Label 1 then, out of 20 samples longest response time one of the sample had was 2867 milliseconds.

Std. Dev.: This shows the set of exceptional cases which were deviating from the average value of sample response time. The lesser this value more consistent the data. Standard deviation should be less than or equal to half of the average time for a label.

Error%: Percentage of Failed requests per Label.

Throughput: Throughput is the number of request that are processed per time unit(seconds, minutes, hours) by the server. This time is calculated from the start of first sample to the end of the last sample. Larger throughput is better.

KB/Sec: This indicates the amount of data downloaded from server during the performance test execution. In short, it is the Throughput measured in Kilobytes per second.

For more information: http://www.testingjournals.com/understand-summary-report-jmeter/

mysqldump with create database line

By default mysqldump always creates the CREATE DATABASE IF NOT EXISTS db_name; statement at the beginning of the dump file.

[EDIT] Few things about the mysqldump file and it's options:

--all-databases, -A

Dump all tables in all databases. This is the same as using the --databases option and naming all the databases on the command line.

--add-drop-database

Add a DROP DATABASE statement before each CREATE DATABASE statement. This option is typically used in conjunction with the --all-databases or --databases option because no CREATE DATABASE statements are written unless one of those options is specified.

--databases, -B

Dump several databases. Normally, mysqldump treats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names. CREATE DATABASE and USE statements are included in the output before each new database.

--no-create-db, -n

This option suppresses the CREATE DATABASE statements that are otherwise included in the output if the --databases or --all-databases option is given.

Some time ago, there was similar question actually asking about not having such statement on the beginning of the file (for XML file). Link to that question is here.

So to answer your question:

  • if you have one database to dump, you should have the --add-drop-database option in your mysqldump statement.
  • if you have multiple databases to dump, you should use the option --databases or --all-databases and the CREATE DATABASE syntax will be added automatically

More information at MySQL Reference Manual

TypeError: expected string or buffer

readlines() will return a list of all the lines in the file, so lines is a list. You probably want something like this:

for line in f.readlines(): # Iterates through every line and looks for a match
#or
#for line in f:
    match = re.findall('[A-Z]+', line)
    print match

Or, if the file isn't too large you can grab it as as single string:

lines = f.read() # Warning: reads the FULL FILE into memory. This can be bad.
match = re.findall('[A-Z]+', lines)
print match

How to read if a checkbox is checked in PHP?

You can check the corresponding value as being set and non-empty in either the $_POST or $_GET array depending on your form's action.

i.e.: With a POST form using a name of "test" (i.e.: <input type="checkbox" name="test"> , you'd use:

if(isset($_POST['test']) {
   // The checkbox was enabled...

}

SQL keys, MUL vs PRI vs UNI

It means that the field is (part of) a non-unique index. You can issue

show create table <table>;

To see more information about the table structure.

What’s the best RESTful method to return total number of items in an object?

As of "X-"-Prefix was deprecated. (see: https://tools.ietf.org/html/rfc6648)

We found the "Accept-Ranges" as being the best bet to map the pagination ranging: https://tools.ietf.org/html/rfc7233#section-2.3 As the "Range Units" may either be "bytes" or "token". Both do not represent a custom data type. (see: https://tools.ietf.org/html/rfc7233#section-4.2) Still, it is stated that

HTTP/1.1 implementations MAY ignore ranges specified using other units.

Which indicates: using custom Range Units is not against the protocol, but it MAY be ignored.

This way, we would have to set the Accept-Ranges to "members" or whatever ranged unit type, we'd expect. And in addition, also set the Content-Range to the current range. (see: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.12)

Either way, I would stick to the recommendation of RFC7233 (https://tools.ietf.org/html/rfc7233#page-8) to send a 206 instead of 200:

If all of the preconditions are true, the server supports the Range
header field for the target resource, and the specified range(s) are
valid and satisfiable (as defined in Section 2.1), the server SHOULD
send a 206 (Partial Content) response with a payload containing one
or more partial representations that correspond to the satisfiable
ranges requested, as defined in Section 4.

So, as a result, we would have the following HTTP header fields:

For Partial Content:

206 Partial Content
Accept-Ranges: members
Content-Range: members 0-20/100

For full Content:

200 OK
Accept-Ranges: members
Content-Range: members 0-20/20

Node.js: How to send headers with form data using request module?

Just remember set method to POST in options. Here is my code

var options = {
    url: 'http://www.example.com',
    method: 'POST', // Don't forget this line
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-MicrosoftAjax': 'Delta=true', // blah, blah, blah...
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36',
    },
    form: {
        'key-1':'value-1',
        'key-2':'value-2',
        ...
    }
};

//console.log('options:', options);

// Create request to get data
request(options, (err, response, body) => {
    if (err) {
        //console.log(err);
    } else {
        console.log('body:', body);
    }
});

java.lang.UnsupportedClassVersionError: Bad version number in .class file?

Another scenario where this could happen is when you are launching an instance of eclipse (for debug etc.) from a host eclipse - in which case, altering the project's level or JRE library on the project's classpath alone doesn't help. What matters is the JRE used to launch the target eclipse environment.

Java Pass Method as Parameter

Last time I checked, Java is not capable of natively doing what you want; you have to use 'work-arounds' to get around such limitations. As far as I see it, interfaces ARE an alternative, but not a good alternative. Perhaps whoever told you that was meaning something like this:

public interface ComponentMethod {
  public abstract void PerfromMethod(Container c);
}

public class ChangeColor implements ComponentMethod {
  @Override
  public void PerfromMethod(Container c) {
    // do color change stuff
  }
}

public class ChangeSize implements ComponentMethod {
  @Override
  public void PerfromMethod(Container c) {
    // do color change stuff
  }
}

public void setAllComponents(Component[] myComponentArray, ComponentMethod myMethod) {
    for (Component leaf : myComponentArray) {
        if (leaf instanceof Container) { //recursive call if Container
            Container node = (Container) leaf;
            setAllComponents(node.getComponents(), myMethod);
        } //end if node
        myMethod.PerfromMethod(leaf);
    } //end looping through components
}

Which you'd then invoke with:

setAllComponents(this.getComponents(), new ChangeColor());
setAllComponents(this.getComponents(), new ChangeSize());

Flexbox Not Centering Vertically in IE

The original answer from https://github.com/philipwalton/flexbugs/issues/231#issuecomment-362790042

.flex-container{
min-height:100px;
display:flex;
align-items:center;
}

.flex-container:after{
content:'';
min-height:inherit;
font-size:0;
}

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

My guess is that you are trying to restore in lower versions which wont work

Laravel Escaping All HTML in Blade Template

use this tag {!! description text !!}

How to make for loops in Java increase by increments other than 1

It should be like this

for(int j = 0; j<=90; j += 3) 

but watch out for

for(int j = 0; j<=90; j =+ 3) 

or

for(int j = 0; j<=90; j = j + 3)

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

In addition to bchhun's great answer, if you want absoulte positioning, you can do this

var options = {
    placement: function (context, source) {
         setTimeout(function () {
               $(context).css('top',(source.getBoundingClientRect().top+ 500) + 'px')
         },0)
         return "top";
    },
    trigger: "click"
};
$(".infopoint").popover(options);

Reading int values from SqlDataReader

Use the GetInt method.

reader.GetInt32(3);

How to open mail app from Swift

Here how it looks for Swift 4:

import MessageUI

if MFMailComposeViewController.canSendMail() {
    let mail = MFMailComposeViewController()
    mail.mailComposeDelegate = self
    mail.setToRecipients(["[email protected]"])
    mail.setSubject("Bla")
    mail.setMessageBody("<b>Blabla</b>", isHTML: true)
    present(mail, animated: true, completion: nil)
} else {
    print("Cannot send mail")
    // give feedback to the user
}

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        switch result.rawValue {
        case MFMailComposeResult.cancelled.rawValue:
            print("Cancelled")
        case MFMailComposeResult.saved.rawValue:
            print("Saved")
        case MFMailComposeResult.sent.rawValue:
            print("Sent")
        case MFMailComposeResult.failed.rawValue:
            print("Error: \(String(describing: error?.localizedDescription))")
        default:
            break
        }
        controller.dismiss(animated: true, completion: nil)
    }

Create instance of generic type in Java?

If you want not to type class name twice during instantiation like in:

new SomeContainer<SomeType>(SomeType.class);

You can use factory method:

<E> SomeContainer<E> createContainer(Class<E> class); 

Like in:

public class Container<E> {

    public static <E> Container<E> create(Class<E> c) {
        return new Container<E>(c);
    }

    Class<E> c;

    public Container(Class<E> c) {
        super();
        this.c = c;
    }

    public E createInstance()
            throws InstantiationException,
            IllegalAccessException {
        return c.newInstance();
    }

}

How to checkout in Git by date?

Going further with the rev-list option, if you want to find the most recent merge commit from your master branch into your production branch (as a purely hypothetical example):

git checkout `git rev-list -n 1 --merges --first-parent --before="2012-01-01" production`

I needed to find the code that was on the production servers as of a given date. This found it for me.

How do I autoindent in Netbeans?

Shift + Alt + F indents the whole file.

ISO time (ISO 8601) in Python

For those who are looking for a date-only solution, it is:

import datetime

datetime.date.today().isoformat()

TypeScript typed array usage

The translation is correct, the typing of the expression isn't. TypeScript is incorrectly typing the expression new Thing[100] as an array. It should be an error to index Thing, a constructor function, using the index operator. In C# this would allocate an array of 100 elements. In JavaScript this calls the value at index 100 of Thing as if was a constructor. Since that values is undefined it raises the error you mentioned. In JavaScript and TypeScript you want new Array(100) instead.

You should report this as a bug on CodePlex.

How to show code but hide output in RMarkdown?

The results = 'hide' option doesn't prevent other messages to be printed. To hide them, the following options are useful:

  • {r, error=FALSE}
  • {r, warning=FALSE}
  • {r, message=FALSE}

In every case, the corresponding warning, error or message will be printed to the console instead.

Recommended add-ons/plugins for Microsoft Visual Studio

If you are looking for a better code editor, vim comes with VisVim, a plugin to replace the VS code editor with vim.

Java Scanner String input

If you use the nextLine() method immediately following the nextInt() method, nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty). So we read can read the empty space to another string might work. Check below code.

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int i = scan.nextInt();
        Double d = scan.nextDouble();
        String f = scan.nextLine();
        String s = scan.nextLine();


        // Write your code here.

        System.out.println("String: " + s);
        System.out.println("Double: " + d);
         System.out.println("Int: " + i);
    }
}

How to align matching values in two columns in Excel, and bring along associated values in other columns

Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.

Can someone explain mappedBy in JPA and Hibernate?

Table relationship vs. entity relationship

In a relational database system, a one-to-many table relationship looks as follows:

one-to-many table relationship

Note that the relationship is based on the Foreign Key column (e.g., post_id) in the child table.

So, there is a single source of truth when it comes to managing a one-to-many table relationship.

Now, if you take a bidirectional entity relationship that maps on the one-to-many table relationship we saw previously:

Bidirectional One-To-Many entity association

If you take a look at the diagram above, you can see that there are two ways to manage this relationship.

In the Post entity, you have the comments collection:

@OneToMany(
    mappedBy = "post",
    cascade = CascadeType.ALL,
    orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();

And, in the PostComment, the post association is mapped as follows:

@ManyToOne(
    fetch = FetchType.LAZY
)
@JoinColumn(name = "post_id")
private Post post;

Because there are two ways to represent the Foreign Key column, you must define which is the source of truth when it comes to translating the association state change into its equivalent Foreign Key column value modification.

MappedBy

The mappedBy attribute tells that the @ManyToOne side is in charge of managing the Foreign Key column, and the collection is used only to fetch the child entities and to cascade parent entity state changes to children (e.g., removing the parent should also remove the child entities).

Synchronize both sides of a bidirectional association

Now, even if you defined the mappedBy attribute and the child-side @ManyToOne association manages the Foreign Key column, you still need to synchronize both sides of the bidirectional association.

The best way to do that is to add these two utility methods:

public void addComment(PostComment comment) {
    comments.add(comment);
    comment.setPost(this);
}

public void removeComment(PostComment comment) {
    comments.remove(comment);
    comment.setPost(null);
}

The addComment and removeComment methods ensure that both sides are synchronized. So, if we add a child entity, the child entity needs to point to the parent and the parent entity should have the child contained in the child collection.

How can I count the number of elements with same class?

document.getElementsByClassName("classstringhere").length

The document.getElementsByClassName("classstringhere") method returns an array of all the elements with that class name, so .length gives you the amount of them.

What does %w(array) mean?

I think of %w() as a "word array" - the elements are delimited by spaces and it returns an array of strings.

There are other % literals:

  • %r() is another way to write a regular expression.
  • %q() is another way to write a single-quoted string (and can be multi-line, which is useful)
  • %Q() gives a double-quoted string
  • %x() is a shell command
  • %i() gives an array of symbols (Ruby >= 2.0.0)
  • %s() turns foo into a symbol (:foo)

I don't know any others, but there may be some lurking around in there...

How to print React component on click of a button?

The solution provided by Emil Ingerslev is working fine, but CSS is not applied to the output. Here I found a good solution given by Andrewlimaza. It prints the contents of a given div, as it uses the window object's print method, the CSS is not lost. And there is no need for an extra iframe also.

var printContents = document.getElementById("divcontents").innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;

Update 1: There is unusual behavior, in chrome/firefox/opera/edge, the print or other buttons stopped working after the execution of this code.

Update 2: The solution given is there on the above link in comments:

.printme { display: none;}
@media print { 
    .no-printme  { display: none;}
    .printme  { display: block;}
}

<h1 class = "no-printme"> do not print this </h1>    
<div class='printme'>
  Print this only 
</div>    
<button onclick={window.print()}>Print only the above div</button>

Cannot delete or update a parent row: a foreign key constraint fails

You need to delete it by order There are dependency in the tables

Joining pandas dataframes by column names

you can use the left_on and right_on options as follows:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')

MySQL Select Date Equal to Today

This query will use index if you have it for signup_date field

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
    FROM users 
    WHERE signup_date >= CURDATE() && signup_date < (CURDATE() + INTERVAL 1 DAY)

How to get UTC time in Python?

import datetime
import pytz

# datetime object with timezone awareness:
datetime.datetime.now(tz=pytz.utc)

# seconds from epoch:
datetime.datetime.now(tz=pytz.utc).timestamp() 

# ms from epoch:
int(datetime.datetime.now(tz=pytz.utc).timestamp() * 1000) 

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

CSS Disabled scrolling

I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype

no suitable HttpMessageConverter found for response type

If you are using Spring Boot, you might want to make sure you have the Jackson dependency in your classpath. You can do this manually via:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>

Or you can use the web starter:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

How to place the ~/.composer/vendor/bin directory in your PATH?

The Composer bin directory is set and stored in bin-dir config variable and can be different depending on your setup. Running the command composer global config bin-dir --absolute will tell you the absolute path to your global composer bin directory. Using this command you can modify your .bash_profile to add it to your PATH exactly how it is configured.

# Add Composer bin-dir to PATH if it is installed.
command -v composer >/dev/null 2>&1 && {
        COMPOSER_BIN_DIR=$(composer global config bin-dir --absolute 2> /dev/null)
        PATH="$PATH:$COMPOSER_BIN_DIR";
}
export PATH

Remove files from Git commit

git checkout HEAD~ path/to/file
git commit --amend

get current page from url

The class you need is System.Uri

Dim url As System.Uri = Request.UrlReferrer 
Debug.WriteLine(url.AbsoluteUri)   ' => http://www.mysite.com/default.aspx
Debug.WriteLine(url.AbsolutePath)  ' => /default.aspx
Debug.WriteLine(url.Host)          ' => http:/www.mysite.com
Debug.WriteLine(url.Port)          ' => 80
Debug.WriteLine(url.IsLoopback)    ' => False

http://www.devx.com/vb2themax/Tip/18709

How to check if another instance of the application is running

The Process static class has a method GetProcessesByName() which you can use to search through running processes. Just search for any other process with the same executable name.

Update a local branch with the changes from a tracked remote branch

You have set the upstream of that branch

(see:

git branch -f --track my_local_branch origin/my_remote_branch
# OR (if my_local_branch is currently checked out):
$ git branch --set-upstream-to my_local_branch origin/my_remote_branch

(git branch -f --track won't work if the branch is checked out: use the second command git branch --set-upstream-to instead, or you would get "fatal: Cannot force update the current branch.")

That means your branch is already configured with:

branch.my_local_branch.remote origin
branch.my_local_branch.merge my_remote_branch

Git already has all the necessary information.
In that case:

# if you weren't already on my_local_branch branch:
git checkout my_local_branch 
# then:
git pull

is enough.


If you hadn't establish that upstream branch relationship when it came to push your 'my_local_branch', then a simple git push -u origin my_local_branch:my_remote_branch would have been enough to push and set the upstream branch.
After that, for the subsequent pulls/pushes, git pull or git push would, again, have been enough.

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

If your data has changed every once,you will notice dont tracing the table.for example some table update id ([key]) using tigger.If you tracing ,you will get same id and get the issue.

Get total number of items on Json object?

Is that your actual code? A javascript object (which is what you've given us) does not have a length property, so in this case exampleArray.length returns undefined rather than 5.

This stackoverflow explains the length differences between an object and an array, and this stackoverflow shows how to get the 'size' of an object.

Install tkinter for Python

Fedora release 25 (Twenty Five)

dnf install python3-tkinter

This worked for me.

How to convert C# nullable int to int

If you know that v1 has a value, you can use the Value property:

v2 = v1.Value;

Using the GetValueOrDefault method will assign the value if there is one, otherwise the default for the type, or a default value that you specify:

v2 = v1.GetValueOrDefault(); // assigns zero if v1 has no value

v2 = v1.GetValueOrDefault(-1); // assigns -1 if v1 has no value

You can use the HasValue property to check if v1 has a value:

if (v1.HasValue) {
  v2 = v1.Value;
}

There is also language support for the GetValueOrDefault(T) method:

v2 = v1 ?? -1;

How to have git log show filenames like svn log -v

git show is also a great command.

It's kind of like svn diff, but you can pass it a commit guid and see that diff.

How can I find all of the distinct file extensions in a folder hierarchy?

Since there's already another solution which uses Perl:

If you have Python installed you could also do (from the shell):

python -c "import os;e=set();[[e.add(os.path.splitext(f)[-1]) for f in fn]for _,_,fn in os.walk('/home')];print '\n'.join(e)"

How to hide status bar in Android

We cannot prevent the status appearing in full screen mode in (4.4+) kitkat or above devices, so try a hack to block the status bar from expanding.

Solution is pretty big, so here's the link of SO:

StackOverflow : Hide status bar in android 4.4+ or kitkat with Fullscreen

jQuery UI Color Picker

Make sure you have jQuery UI base and the color picker widget included on your page (as well as a copy of jQuery 1.3):

<link rel="stylesheet" href="http://dev.jquery.com/view/tags/ui/latest/themes/flora/flora.all.css" type="text/css" media="screen" title="Flora (Default)">

<script type="text/javascript" src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.core.js"></script>

<script type="text/javascript" src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.colorpicker.js"></script>

If you have those included, try posting your source so we can see what's going on.

RVM is not a function, selecting rubies with 'rvm use ...' will not work

If RVM was installed with dedicated ubuntu RVM installer https://github.com/rvm/ubuntu_rvm the path to RVM scripts will be different /usr/share/rvm/scripts/rvm. So to add it to your .bashrc run the following command:

echo 'source "/usr/share/rvm/scripts/rvm"' >> ~/.bashrc

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

Save classifier to disk in scikit-learn

sklearn.externals.joblib has been deprecated since 0.21 and will be removed in v0.23:

/usr/local/lib/python3.7/site-packages/sklearn/externals/joblib/init.py:15: FutureWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+.
warnings.warn(msg, category=FutureWarning)


Therefore, you need to install joblib:

pip install joblib

and finally write the model to disk:

import joblib
from sklearn.datasets import load_digits
from sklearn.linear_model import SGDClassifier


digits = load_digits()
clf = SGDClassifier().fit(digits.data, digits.target)

with open('myClassifier.joblib.pkl', 'wb') as f:
    joblib.dump(clf, f, compress=9)

Now in order to read the dumped file all you need to run is:

with open('myClassifier.joblib.pkl', 'rb') as f:
    my_clf = joblib.load(f)

keycloak Invalid parameter: redirect_uri

Check that the value of the redirect_uri parameter is whitelisted for the client that you are using. You can manage the configuration of the client via the admin console.

The redirect uri should match exactly with one of the whitelisted redirect uri's, or you can use a wildcard at the end of the uri you want to whitelist. See: https://www.keycloak.org/docs/latest/server_admin/#_clients

Note that using wildcards to whitelist redirect uri's is allowed by Keycloak, but is actually a violation of the OpenId Connect specification. See the discussion on this at https://lists.jboss.org/pipermail/keycloak-dev/2018-December/011440.html

How to style a clicked button in CSS

There are three states of button

  • Normal : You can select like this button
  • Hover : You can select like this button:hover
  • Pressed/Clicked : You can select like this button:active

Normal:

.button
 {
     //your css
 }

Active

 .button:active
{
        //your css
}

Hover

 .button:hover
{
        //your css
}

SNIPPET:

Use :active to style the active state of button.

_x000D_
_x000D_
button:active{_x000D_
   background-color:red;_x000D_
}
_x000D_
<button>Click Me</button>
_x000D_
_x000D_
_x000D_

doGet and doPost in Servlets

Could it be that you are passing the data through get, not post?

<form method="get" ..>
..
</form>

make image( not background img) in div repeat?

You have use to repeat-y as style="background-repeat:repeat-y;width: 200px;" instead of style="repeat-y".

Try this inside the image tag or you can use the below css for the div

.div_backgrndimg
{
    background-repeat: repeat-y;
    background-image: url("/image/layout/lotus-dreapta.png");
    width:200px;
}

Java JTextField with input hint

Here is a fully working example based on Adam Gawne-Cain's earlier Posting. His solution is simple and actually works exceptionally well.

I've used the following text in a Grid of multiple Fields:

H__|__WWW__+__XXXX__+__WWW__|__H

this makes it possible to easily verify the x/y alignment of the hinted text.

A couple of observations:
- there are any number of solutions out there, but many only work superficially and/or are buggy
- sun.tools.jconsole.ThreadTab.PromptingTextField is a simple solution, but it only shows the prompting text when the Field doesn't have the focus & it's private, but nothing a little cut-and-paste won't fix.

The following works on JDK 8 and upwards:

import java.awt.*;
import java.util.stream.*;
import javax.swing.*;
/**
 * @author DaveTheDane, based on a suggestion from Adam Gawne-Cain
 */
public final class JTextFieldPromptExample extends JFrame {

    private static JTextField newPromptedJTextField (final String text, final String prompt) {

        final String promptPossiblyNullButNeverWhitespace = prompt == null || prompt.trim().isEmpty()  ?  null  :  prompt;

        return new JTextField(text) {
            @Override
            public void paintComponent(final Graphics    USE_g2d_INSTEAD) {
                final Graphics2D     g2d =  (Graphics2D) USE_g2d_INSTEAD;

                super.paintComponent(g2d);

//              System.out.println("Paint.: " + g2d);

                if (getText().isEmpty()
                &&  promptPossiblyNullButNeverWhitespace != null) {
                    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

                    final Insets      ins = getInsets();
                    final FontMetrics fm  = g2d.getFontMetrics();

                    final int cB = getBackground().getRGB();
                    final int cF = getForeground().getRGB();
                    final int m  = 0xfefefefe;
                    final int c2 = ((cB & m) >>> 1) + ((cF & m) >>> 1); // "for X in (A, R, G, B) {Xnew = (Xb + Xf) / 2}"
                    /*
                     * The hint text color should be halfway between the foreground and background colors so it is always gently visible.
                     * The variables c0,c1,m,c2 calculate the halfway color's ARGB fields simultaneously without overflowing 8 bits.
                     * Swing sets the Graphics' font to match the JTextField's font property before calling the "paint" method,
                     * so the hint font will match the JTextField's font.
                     * Don't think there are any side effects because Swing discards the Graphics after painting.
                     * Adam Gawne-Cain, Aug 6 2019 at 15:55
                     */
                    g2d.setColor(new Color(c2, true));
                    g2d.drawString(promptPossiblyNullButNeverWhitespace, ins.left, getHeight() - fm.getDescent() - ins.bottom);
                    /*
                     * y Coordinate based on Descent & Bottom-inset seems to align Text spot-on.
                     * DaveTheDane, Apr 10 2020
                     */
                }
            }
        };
    }

    private static final GridBagConstraints GBC_LEFT  = new GridBagConstraints();
    private static final GridBagConstraints GBC_RIGHT = new GridBagConstraints();
    /**/    static {
        GBC_LEFT .anchor    = GridBagConstraints.LINE_START;
        GBC_LEFT .fill      = GridBagConstraints.HORIZONTAL;
        GBC_LEFT .insets    = new Insets(8, 8, 0, 0);

        GBC_RIGHT.gridwidth = GridBagConstraints.REMAINDER;
        GBC_RIGHT.fill      = GridBagConstraints.HORIZONTAL;
        GBC_RIGHT.insets    = new Insets(8, 8, 0, 8);
    }

    private <C extends Component> C addLeft (final C component) {
        this    .add           (component);
        this.gbl.setConstraints(component, GBC_LEFT);
        return                  component;
    }
    private <C extends Component> C addRight(final C component) {
        this    .add           (component);
        this.gbl.setConstraints(component, GBC_RIGHT);
        return                  component;
    }

    private static final String ALIGN = "H__|__WWW__+__XXXX__+__WWW__|__H";

    private final GridBagLayout gbl = new GridBagLayout();

    public JTextFieldPromptExample(final String title) {
        super(title);
        this.setLayout(gbl);

        final java.util.List<JTextField> texts = Stream.of(
                addLeft (newPromptedJTextField(ALIGN + ' ' + "Top-Left"    , ALIGN)),
                addRight(newPromptedJTextField(ALIGN + ' ' + "Top-Right"   , ALIGN)),

                addLeft (newPromptedJTextField(ALIGN + ' ' + "Middle-Left" , ALIGN)),
                addRight(newPromptedJTextField(                       null , ALIGN)),

                addLeft (new        JTextField("x"        )),
                addRight(newPromptedJTextField("x",   ""  )),

                addLeft (new        JTextField(null       )),
                addRight(newPromptedJTextField(null,  null)),

                addLeft (newPromptedJTextField(ALIGN + ' ' + "Bottom-Left" , ALIGN)),
                addRight(newPromptedJTextField(ALIGN + ' ' + "Bottom-Right", ALIGN)) ).collect(Collectors.toList());

        final JButton button = addRight(new JButton("Get texts"));
        /**/                   addRight(Box.createVerticalStrut(0)); // 1 last time forces bottom inset

        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setPreferredSize(new Dimension(740, 260));
        this.pack();
        this.setResizable(false);
        this.setVisible(true);

        button.addActionListener(e -> {
            texts.forEach(text -> System.out.println("Text..: " + text.getText()));
        });
    }

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(() -> new JTextFieldPromptExample("JTextField with Prompt"));
    }
}

AFNetworking Post Request

For AFNetworking 3.0 (iOS9 or greter)

 NSString *strURL = @"https://exampleWeb.com/webserviceOBJ";
    NSDictionary *dictParamiters = @{@"user[height]": height,@"user[weight]": weight};

    NSString *aStrParams = [self getFormDataStringWithDictParams:dictParamiters];

    NSData *aData = [aStrParams dataUsingEncoding:NSUTF8StringEncoding];

    NSMutableURLRequest *aRequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:strURL]];
    [aRequest setHTTPMethod:@"POST"];
    [aRequest setHTTPBody:aData];

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
    [aRequest setHTTPBody:aData];

    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:aRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        //
        if (error ==nil) {
            NSString *aStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"ResponseString:%@",aStr);
            NSMutableDictionary *aMutDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                    completionBlock(aMutDict);

                NSLog(@"responce:%@",aMutDict)

            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"error:%@",error.locali)
            });
        }
    }];

    [postDataTask resume];

and Add

-(NSString *)getFormDataStringWithDictParams:(NSDictionary *)aDict
{
    NSMutableString *aMutStr = [[NSMutableString alloc]initWithString:@""];
    for (NSString *aKey in aDict.allKeys) {
        [aMutStr appendFormat:@"%@=%@&",aKey,aDict[aKey]];
    }
    NSString *aStrParam;
    if (aMutStr.length>2) {
        aStrParam = [aMutStr substringWithRange:NSMakeRange(0, aMutStr.length-1)];

    }
    else
        aStrParam = @"";

    return aStrParam;
}

How to convert a UTF-8 string into Unicode?

I have string that displays UTF-8 encoded characters

There is no such thing in .NET. The string class can only store strings in UTF-16 encoding. A UTF-8 encoded string can only exist as a byte[]. Trying to store bytes into a string will not come to a good end; UTF-8 uses byte values that don't have a valid Unicode codepoint. The content will be destroyed when the string is normalized. So it is already too late to recover the string by the time your DecodeFromUtf8() starts running.

Only handle UTF-8 encoded text with byte[]. And use UTF8Encoding.GetString() to convert it.

Getting Current time to display in Label. VB.net

try

total.Text = DateTime.Now.ToString()

or

Dim theDate As DateTime = System.DateTime.Now
total.Text = theDate.ToString()

You declare Start as an Integer, while you are trying to put a DateTime in it, which is not possible.

Mergesort with Python

def merge_sort(x):

    if len(x) < 2:return x

    result,mid = [],int(len(x)/2)

    y = merge_sort(x[:mid])
    z = merge_sort(x[mid:])

    while (len(y) > 0) and (len(z) > 0):
            if y[0] > z[0]:result.append(z.pop(0))   
            else:result.append(y.pop(0))

    result.extend(y+z)
    return result

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

Bootstrap 3 Glyphicons CDN

With the recent release of bootstrap 3, and the glyphicons being merged back to the main Bootstrap repo, Bootstrap CDN is now serving the complete Bootstrap 3.0 css including Glyphicons. The Bootstrap css reference is all you need to include: Glyphicons and its dependencies are on relative paths on the CDN site and are referenced in bootstrap.min.css.

In html:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">

In css:

 @import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");

Here is a working demo.

Note that you have to use .glyphicon classes instead of .icon:

Example:

<span class="glyphicon glyphicon-heart"></span>

Also note that you would still need to include bootstrap.min.js for usage of Bootstrap JavaScript components, see Bootstrap CDN for url.


If you want to use the Glyphicons separately, you can do that by directly referencing the Glyphicons css on Bootstrap CDN.

In html:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">

In css:

@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css");

Since the css file already includes all the needed Glyphicons dependencies (which are in a relative path on the Bootstrap CDN site), adding the css file is all there is to do to start using Glyphicons.

Here is a working demo of the Glyphicons without Bootstrap.

Converting double to string with N decimals, dot as decimal separator, and no thousand separator

You can simply use decimal.ToString()

For two decimals

myDecimal.ToString("0.00");

For four decimals

myDecimal.ToString("0.0000");

This gives dot as decimal separator, and no thousand separator regardless of culture.

How to increase timeout for a single test case in mocha

For test navegation on Express:

const request = require('supertest');
const server = require('../bin/www');

describe('navegation', () => {
    it('login page', function(done) {
        this.timeout(4000);
        const timeOut = setTimeout(done, 3500);

        request(server)
            .get('/login')
            .expect(200)
            .then(res => {
                res.text.should.include('Login');
                clearTimeout(timeOut);
                done();
            })
            .catch(err => {
                console.log(this.test.fullTitle(), err);
                clearTimeout(timeOut);
                done(err);
            });
    });
});

In the example the test time is 4000 (4s).

Note: setTimeout(done, 3500) is minor for than done is called within the time of the test but clearTimeout(timeOut) it avoid than used all these time.

Finding the median of an unsorted array

Quickselect works in O(n), this is also used in the partition step of Quicksort.

Does return stop a loop?

The return statement stops a loop only if it's inside the function (i.e. it terminates both the loop and the function). Otherwise, you will get this error:

Uncaught SyntaxError: Illegal return statement(…)

To terminate a loop you should use break.

How to call a shell script from python code?

Please Try the following codes :

Import Execute 

Execute("zbx_control.sh")

Which Eclipse version should I use for an Android app?

**June 2012 **

Google Recommends Eclipse Helios, Eclipse Classic or Eclipse RCP. For details, read the below post.

URL: http://developer.android.com/sdk/eclipse-adt.html

Look under ADT 18.0.0 (April 2012).

Eclipse Helios (Version 3.6.2) or higher is required for ADT 18.0.0.

Look under Installing the ADT Plugin.

If you need to install or update Eclipse, you can download it from http://www.eclipse.org/downloads/. The "Eclipse Classic" version is recommended. Otherwise, a Java or RCP version of Eclipse is recommended.

April 2014 Updated

Eclipse Indigo (Version 3.7.2) or higher is required. I'll suggest you to use Eclipse Kepler.

ADT 22.6.0 (March 2014)

Detect If Browser Tab Has Focus

Cross Browser jQuery Solution! Raw available at GitHub

Fun & Easy to Use!

The following plugin will go through your standard test for various versions of IE, Chrome, Firefox, Safari, etc.. and establish your declared methods accordingly. It also deals with issues such as:

  • onblur|.blur/onfocus|.focus "duplicate" calls
  • window losing focus through selection of alternate app, like word
    • This tends to be undesirable simply because, if you have a bank page open, and it's onblur event tells it to mask the page, then if you open calculator, you can't see the page anymore!
  • Not triggering on page load

Use is as simple as: Scroll Down to 'Run Snippet'

$.winFocus(function(event, isVisible) {
    console.log("Combo\t\t", event, isVisible);
});

//  OR Pass False boolean, and it will not trigger on load,
//  Instead, it will first trigger on first blur of current tab_window
$.winFocus(function(event, isVisible) {
    console.log("Combo\t\t", event, isVisible);
}, false);

//  OR Establish an object having methods "blur" & "focus", and/or "blurFocus"
//  (yes, you can set all 3, tho blurFocus is the only one with an 'isVisible' param)
$.winFocus({
    blur: function(event) {
        console.log("Blur\t\t", event);
    },
    focus: function(event) {
        console.log("Focus\t\t", event);
    }
});

//  OR First method becoms a "blur", second method becoms "focus"!
$.winFocus(function(event) {
    console.log("Blur\t\t", event);
},
function(event) {
    console.log("Focus\t\t", event);
});

_x000D_
_x000D_
/*    Begin Plugin    */_x000D_
;;(function($){$.winFocus||($.extend({winFocus:function(){var a=!0,b=[];$(document).data("winFocus")||$(document).data("winFocus",$.winFocus.init());for(x in arguments)"object"==typeof arguments[x]?(arguments[x].blur&&$.winFocus.methods.blur.push(arguments[x].blur),arguments[x].focus&&$.winFocus.methods.focus.push(arguments[x].focus),arguments[x].blurFocus&&$.winFocus.methods.blurFocus.push(arguments[x].blurFocus),arguments[x].initRun&&(a=arguments[x].initRun)):"function"==typeof arguments[x]?b.push(arguments[x]):_x000D_
"boolean"==typeof arguments[x]&&(a=arguments[x]);b&&(1==b.length?$.winFocus.methods.blurFocus.push(b[0]):($.winFocus.methods.blur.push(b[0]),$.winFocus.methods.focus.push(b[1])));if(a)$.winFocus.methods.onChange()}}),$.winFocus.init=function(){$.winFocus.props.hidden in document?document.addEventListener("visibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="mozHidden")in document?document.addEventListener("mozvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden=_x000D_
"webkitHidden")in document?document.addEventListener("webkitvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="msHidden")in document?document.addEventListener("msvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="onfocusin")in document?document.onfocusin=document.onfocusout=$.winFocus.methods.onChange:window.onpageshow=window.onpagehide=window.onfocus=window.onblur=$.winFocus.methods.onChange;return $.winFocus},$.winFocus.methods={blurFocus:[],blur:[],focus:[],_x000D_
exeCB:function(a){$.winFocus.methods.blurFocus&&$.each($.winFocus.methods.blurFocus,function(b,c){this.apply($.winFocus,[a,!a.hidden])});a.hidden&&$.winFocus.methods.blur&&$.each($.winFocus.methods.blur,function(b,c){this.apply($.winFocus,[a])});!a.hidden&&$.winFocus.methods.focus&&$.each($.winFocus.methods.focus,function(b,c){this.apply($.winFocus,[a])})},onChange:function(a){var b={focus:!1,focusin:!1,pageshow:!1,blur:!0,focusout:!0,pagehide:!0};if(a=a||window.event)a.hidden=a.type in b?b[a.type]:_x000D_
document[$.winFocus.props.hidden],$(window).data("visible",!a.hidden),$.winFocus.methods.exeCB(a);else try{$.winFocus.methods.onChange.call(document,new Event("visibilitychange"))}catch(c){}}},$.winFocus.props={hidden:"hidden"})})(jQuery);_x000D_
/*    End Plugin      */_x000D_
_x000D_
// Simple example_x000D_
$(function() {_x000D_
 $.winFocus(function(event, isVisible) {_x000D_
  $('td tbody').empty();_x000D_
  $.each(event, function(i) {_x000D_
   $('td tbody').append(_x000D_
    $('<tr />').append(_x000D_
     $('<th />', { text: i }),_x000D_
     $('<td />', { text: this.toString() })_x000D_
    )_x000D_
   )_x000D_
  });_x000D_
  if (isVisible) _x000D_
   $("#isVisible").stop().delay(100).fadeOut('fast', function(e) {_x000D_
    $('body').addClass('visible');_x000D_
    $(this).stop().text('TRUE').fadeIn('slow');_x000D_
   });_x000D_
  else {_x000D_
   $('body').removeClass('visible');_x000D_
   $("#isVisible").text('FALSE');_x000D_
  }_x000D_
 });_x000D_
})
_x000D_
body { background: #AAF; }_x000D_
table { width: 100%; }_x000D_
table table { border-collapse: collapse; margin: 0 auto; width: auto; }_x000D_
tbody > tr > th { text-align: right; }_x000D_
td { width: 50%; }_x000D_
th, td { padding: .1em .5em; }_x000D_
td th, td td { border: 1px solid; }_x000D_
.visible { background: #FFA; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<h3>See Console for Event Object Returned</h3>_x000D_
<table>_x000D_
    <tr>_x000D_
        <th><p>Is Visible?</p></th>_x000D_
        <td><p id="isVisible">TRUE</p></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan="2">_x000D_
            <table>_x000D_
                <thead>_x000D_
                    <tr>_x000D_
                        <th colspan="2">Event Data <span style="font-size: .8em;">{ See Console for More Details }</span></th>_x000D_
                    </tr>_x000D_
                </thead>_x000D_
                <tbody></tbody>_x000D_
            </table>_x000D_
        </td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Getting Python error "from: can't read /var/mail/Bio"

for Mac OS just go to applications and just run these Scripts Install Certificates.command and Update Shell Profile.command, now it will work.

How do I split a string on a delimiter in Bash?

There are some cool answers here (errator esp.), but for something analogous to split in other languages -- which is what I took the original question to mean -- I settled on this:

IN="[email protected];[email protected]"
declare -a a="(${IN/;/ })";

Now ${a[0]}, ${a[1]}, etc, are as you would expect. Use ${#a[*]} for number of terms. Or to iterate, of course:

for i in ${a[*]}; do echo $i; done

IMPORTANT NOTE:

This works in cases where there are no spaces to worry about, which solved my problem, but may not solve yours. Go with the $IFS solution(s) in that case.

Chrome Extension: Make it run every page load

This code should do it:

manifest.json

   {
      "name": "Alert 'hello world!' on page opening",
      "version": "1.0",
      "manifest_version": 2,
      "content_scripts": [
        {
          "matches": [
            "<all_urls>"
          ],
          "js": ["content.js"]
        }
      ]
    }

content.js

alert('Hello world!')

ASP.NET Web Application Message Box

Just add the namespace:

System.Windows.forms 

to your web application reference or what ever, and you have the access to your:

MessageBox.Show("Here is my message");

I tried it and it worked.

Good luck.

Scrollview can host only one direct child

Wrap all the children inside of another LinearLayout with wrap_content for both the width and the height as well as the vertical orientation.

Getting value of selected item in list box as string

To retreive the value of all selected item in à listbox you can cast selected item in DataRowView and then select column where your data is:

foreach(object element in listbox.SelectedItems) {
    DataRowView row = (DataRowView)element;
    MessageBox.Show(row[0]);
}

"google is not defined" when using Google Maps V3 in Firefox remotely

Add the type for the script

<script src="https://maps.googleapis.com/maps/api/js" type="text/javascript"></script>

So the important part is the type text/javascript.

How can I add reflection to a C++ application?

If you're looking for relatively simple C++ reflection - I have collected from various sources macro / defines, and commented them out how they works. You can download header files from here:

https://github.com/tapika/TestCppReflect/blob/master/MacroHelpers.h

set of defines, plus functionality on top of it:

https://github.com/tapika/TestCppReflect/blob/master/CppReflect.h https://github.com/tapika/TestCppReflect/blob/master/CppReflect.cpp https://github.com/tapika/TestCppReflect/blob/master/TypeTraits.h

Sample application resides in git repository as well, in here: https://github.com/tapika/TestCppReflect/

I'll partly copy it here with explanation:

#include "CppReflect.h"
using namespace std;


class Person
{
public:

    // Repack your code into REFLECTABLE macro, in (<C++ Type>) <Field name>
    // form , like this:

    REFLECTABLE( Person,
        (CString)   name,
        (int)       age,
...
    )
};

void main(void)
{
    Person p;
    p.name = L"Roger";
    p.age = 37;
...

    // And here you can convert your class contents into xml form:

    CStringW xml = ToXML( &p );
    CStringW errors;

    People ppl2;

    // And here you convert from xml back to class:

    FromXml( &ppl2, xml, errors );
    CStringA xml2 = ToXML( &ppl2 );
    printf( xml2 );

}

REFLECTABLE define uses class name + field name with offsetof - to identify at which place in memory particular field is located. I have tried to pick up .NET terminology for as far as possible, but C++ and C# are different, so it's not 1 to 1. Whole C++ reflection model resides in TypeInfo and FieldInfo classes.

I have used pugi xml parser to fetch demo code into xml and restore it back from xml.

So output produced by demo code looks like this:

<?xml version="1.0" encoding="utf-8"?>
<People groupName="Group1">
    <people>
        <Person name="Roger" age="37" />
        <Person name="Alice" age="27" />
        <Person name="Cindy" age="17" />
    </people>
</People>

It's also possible to enable any 3-rd party class / structure support via TypeTraits class, and partial template specification - to define your own TypeTraitsT class, in similar manner to CString or int - see example code in

https://github.com/tapika/TestCppReflect/blob/master/TypeTraits.h#L195

This solution is applicable for Windows / Visual studio. It's possible to port it to other OS/compilers, but haven't done that one. (Ask me if you really like solution, I might be able to help you out)

This solution is applicable for one shot serialization of one class with multiple subclasses.

If you however are searching for mechanism to serialize class parts or even to control what functionality reflection calls produce, you could take a look on following solution:

https://github.com/tapika/cppscriptcore/tree/master/SolutionProjectModel

More detailed information can be found from youtube video:

C++ Runtime Type Reflection https://youtu.be/TN8tJijkeFE

I'm trying to explain bit deeper on how c++ reflection will work.

Sample code will look like for example this:

https://github.com/tapika/cppscriptcore/blob/master/SolutionProjectModel/testCppApp.cpp

c.General.IntDir = LR"(obj\$(ProjectName)_$(Configuration)_$(Platform)\)";
c.General.OutDir = LR"(bin\$(Configuration)_$(Platform)\)";
c.General.UseDebugLibraries = true;
c.General.LinkIncremental = true;
c.CCpp.Optimization = optimization_Disabled;
c.Linker.System.SubSystem = subsystem_Console;
c.Linker.Debugging.GenerateDebugInformation = debuginfo_true;

But each step here actually results in function call Using C++ properties with __declspec(property(get =, put ... ).

which receives full information on C++ Data Types, C++ property names and class instance pointers, in form of path, and based on that information you can generate xml, json or even serialize that one over internet.

Examples of such virtual callback functions can be found here:

https://github.com/tapika/cppscriptcore/blob/master/SolutionProjectModel/VCConfiguration.cpp

See functions ReflectCopy, and virtual function ::OnAfterSetProperty.

But since topic is really advanced - I recommend to check through video first.

If you have some improvement ideas, feel free to contact me.

Create a data.frame with m columns and 2 rows

Does m really need to be a data.frame() or will a matrix() suffice?

m <- matrix(0, ncol = 30, nrow = 2)

You can wrap a data.frame() around that if you need to:

m <- data.frame(m)

or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

Looks like your buttons are not declared correctly (according to the latest jQuery UI documentation anyway).

try the following:

$( ".selector" ).dialog({ 
   buttons: [{ 
      text: "Ok", 
      click: function() { 
         $( this ).dialog( "close" ); 
      }
   }]
});

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

Have you tried (from a command line)

java -jar jbpm-installer-3.2.7.jar

or double clicking it with the mouse ?

Found this and this by googling.

Hope it helps

Pandas sum by groupby, but exclude certain columns

The agg function will do this for you. Pass the columns and function as a dict with column, output:

df.groupby(['Country', 'Item_Code']).agg({'Y1961': np.sum, 'Y1962': [np.sum, np.mean]})  # Added example for two output columns from a single input column

This will display only the group by columns, and the specified aggregate columns. In this example I included two agg functions applied to 'Y1962'.

To get exactly what you hoped to see, included the other columns in the group by, and apply sums to the Y variables in the frame:

df.groupby(['Code', 'Country', 'Item_Code', 'Item', 'Ele_Code', 'Unit']).agg({'Y1961': np.sum, 'Y1962': np.sum, 'Y1963': np.sum})

What does it mean when Statement.executeUpdate() returns -1?

I haven't seen this anywhere, either, but my instinct would be that this means that the IF prevented the whole statement from executing.

Try to run the statement with a database where the IF passes.

Also check if there are any triggers involved which might change the result.

[EDIT] When the standard says that this function should never return -1, that doesn't enforce this. Java doesn't have pre and post conditions. A JDBC driver could return a random number and there was no way to stop it.

If it's important to know why this happens, run the statement against different database until you have tried all execution paths (i.e. one where the IF returns false and one where it returns true).

If it's not that important, mark it off as a "clever trick" by a Microsoft engineer and remember how much you liked it when you feel like being clever yourself next time.

Make var_dump look pretty

I wrote a function (debug_display) which can print, arrays, objects, and file info in pretty way.

<?php
function debug_display($var,$show = false) {
    if($show) { $dis = 'block'; }else { $dis = 'none'; }
    ob_start();
    echo '<div style="display:'.$dis.';text-align:left; direction:ltr;"><b>Idea Debug Method : </b>
        <pre>';
    if(is_bool($var)) {
        echo $var === TRUE ? 'Boolean(TRUE)' : 'Boolean(FALSE)';
    }else {
        if(FALSE == empty($var) && $var !== NULL && $var != '0') {
            if(is_array($var)) {
                echo "Number of Indexes: " . count($var) . "\n";
                print_r($var);
            } elseif(is_object($var)) {
                print_r($var);
            } elseif(@is_file($var)){
                $stat = stat($var);
                $perm = substr(sprintf('%o',$stat['mode']), -4);
                $accesstime = gmdate('Y/m/d H:i:s', $stat['atime']);
                $modification = gmdate('Y/m/d H:i:s', $stat['mtime']);
                $change = gmdate('Y/m/d H:i:s', $stat['ctime']);
                echo "
    file path : $var
    file size : {$stat['size']} Byte
    device number : {$stat['dev']}
    permission : {$perm}
    last access time was : {$accesstime}
    last modified time was : {$modification}
    last change time was : {$change}
    ";
            }elseif(is_string($var)) {
                print_r(htmlentities(str_replace("\t", '  ', $var)));
            }  else {
                print_r($var);
            }
        }else {
            echo 'Undefined';
        }
    }
    echo '</pre>
    </div>';
    $output = ob_get_contents();
    ob_end_clean();
    echo $output;
    unset($output);
}

Can a java file have more than one class?

If you want to implement a public class, you must implement it in a file with the same name as that class. A single file can contain one public and optionally some private classes. This is useful if the classes are only used internally by the public class. Additionally the public class can also contain inner classes.

Although it is fine to have one or more private classes in a single source file, I would say that is more readable to use inner and anonymous classes instead. For example one can use an anonymous class to define a Comparator class inside a public class:

  public static Comparator MyComparator = new Comparator() {
    public int compare(Object obj, Object anotherObj) {

    }
  };

The Comparator class will normally require a separate file in order to be public. This way it is bundled with the class that uses it.

HTML entity for check mark

There is HTML entity &#10003 but it doesn't work in some older browsers.

How to get the current time as datetime

Swift makes it really easy to create and use extensions. I create a sharedCode.swift file and put enums, extensions, and other fun stuff in it. I created a NSDate extension to add some typical functionality which is laborious and ugly to type over and over again:

extension NSDate
{
    func hour() -> Int
    {
        //Get Hour
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Hour, fromDate: self)
        let hour = components.hour

        //Return Hour
        return hour
    }


    func minute() -> Int
    {
        //Get Minute
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Minute, fromDate: self)
        let minute = components.minute

        //Return Minute
        return minute
    }

    func toShortTimeString() -> String
    {
        //Get Short Time String
        let formatter = NSDateFormatter()
        formatter.timeStyle = .ShortStyle
        let timeString = formatter.stringFromDate(self)

        //Return Short Time String
        return timeString
    }
}

using this extension you can now do something like:

        //Get Current Date
        let currentDate = NSDate()

        //Test Extensions in Log
        NSLog("(Current Hour = \(currentDate.hour())) (Current Minute = \(currentDate.minute())) (Current Short Time String = \(currentDate.toShortTimeString()))")

Which for 11:51 AM would write out:

(Current Hour = 11) (Current Minute = 51) (Current Short Time String = 11:51 AM)

Subtracting 2 lists in Python

A slightly different Vector class.

class Vector( object ):
    def __init__(self, *data):
        self.data = data
    def __repr__(self):
        return repr(self.data) 
    def __add__(self, other):
        return tuple( (a+b for a,b in zip(self.data, other.data) ) )  
    def __sub__(self, other):
        return tuple( (a-b for a,b in zip(self.data, other.data) ) )

Vector(1, 2, 3) - Vector(1, 1, 1)

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

Try changing

$client = new SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl', ['trace' => true]);

to

$client = new SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl', ['trace' => true, 'cache_wsdl' => WSDL_CACHE_MEMORY]);

Also (whether that works or not), check to make sure that /tmp is writeable by your web server and that it isn't full.

How do I use Ruby for shell scripting?

The above answer are interesting and very helpful when using Ruby as shell script. For me, I does not use Ruby as my daily language and I prefer to use ruby as flow control only and still use bash to do the tasks.

Some helper function can be used for testing execution result

#!/usr/bin/env ruby
module ShellHelper
  def test(command)
    `#{command} 2> /dev/null`
    $?.success?
  end

  def execute(command, raise_on_error = true)
    result = `#{command}`
    raise "execute command failed\n" if (not $?.success?) and raise_on_error
    return $?.success?
  end

  def print_exit(message)
    print "#{message}\n"
    exit
  end

  module_function :execute, :print_exit, :test
end

With helper, the ruby script could be bash alike:

#!/usr/bin/env ruby
require './shell_helper'
include ShellHelper

print_exit "config already exists" if test "ls config"

things.each do |thing|
  next if not test "ls #{thing}/config"
  execute "cp -fr #{thing}/config_template config/#{thing}"
end

scroll up and down a div on button click using jquery

Scrolling div on click of button.

Html Code:-

 <div id="textBody" style="height:200px; width:600px; overflow:auto;">
    <!------Your content---->
 </div>

JQuery code for scrolling div:-

$(function() {
   $( "#upBtn" ).click(function(){
      $('#textBody').scrollTop($('#textBody').scrollTop()-20);
 }); 

 $( "#downBtn" ).click(function(){
     $('#textBody').scrollTop($('#textBody').scrollTop()+20);;
 }); 

});

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

If your jar file already has an absolute pathname as shown, it is particularly easy:

cd /where/you/want/it; jar xf /path/to/jarfile.jar

That is, you have the shell executed by Python change directory for you and then run the extraction.

If your jar file does not already have an absolute pathname, then you have to convert the relative name to absolute (by prefixing it with the path of the current directory) so that jar can find it after the change of directory.

The only issues left to worry about are things like blanks in the path names.

How to pass variable number of arguments to printf/sprintf

I should have read more on existing questions in stack overflow.

C++ Passing Variable Number of Arguments is a similar question. Mike F has the following explanation:

There's no way of calling (eg) printf without knowing how many arguments you're passing to it, unless you want to get into naughty and non-portable tricks.

The generally used solution is to always provide an alternate form of vararg functions, so printf has vprintf which takes a va_list in place of the .... The ... versions are just wrappers around the va_list versions.

This is exactly what I was looking for. I performed a test implementation like this:

void Error(const char* format, ...)
{
    char dest[1024 * 16];
    va_list argptr;
    va_start(argptr, format);
    vsprintf(dest, format, argptr);
    va_end(argptr);
    printf(dest);
}

Swift add icon/image in UITextField

2020 - reasonable solution

Regarding this insanity from Apple.

Here is perhaps the "clearest", simplest, way to do it:

enter image description here

First, you must correctly move the text.

Note this critical QA: https://stackoverflow.com/a/27066764/294884

class TidyTextField: UITextField {
    
    @IBInspectable var leftImage: UIImage? = nil
    @IBInspectable var leftPadding: CGFloat = 0
    @IBInspectable var gapPadding: CGFloat = 0
    
    private var textPadding: UIEdgeInsets {
        let p: CGFloat = leftPadding + gapPadding + (leftView?.frame.width ?? 0)
        return UIEdgeInsets(top: 0, left: p, bottom: 0, right: 5)
    }
    
    override open func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: textPadding)
    }
    
    override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: textPadding)
    }
    
    override open func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: textPadding)
    }
    

continuing, we now have to make and move the left image:

    override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
        var r = super.leftViewRect(forBounds: bounds)
        r.origin.x += leftPadding
        return r
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        setup()
    }
    
    private func setup() {
        if let image = leftImage {
            if leftView != nil { return } // critical!
            
            let im = UIImageView()
            im.contentMode = .scaleAspectFit
            im.image = image
            
            leftViewMode = UITextField.ViewMode.always
            leftView = im
            
        } else {
            leftViewMode = UITextField.ViewMode.never
            leftView = nil
        }
    }
}

This seems to be about the clearest, most reliable way to do it.

Understanding ibeacon distancing

Distances to the source of iBeacon-formatted advertisement packets are estimated from the signal path attenuation calculated by comparing the measured received signal strength to the claimed transmit power which the transmitter is supposed to encode in the advertising data.

A path loss based scheme like this is only approximate and is subject to variation with things like antenna angles, intervening objects, and presumably a noisy RF environment. In comparison, systems really designed for distance measurement (GPS, Radar, etc) rely on precise measurements of propagation time, in same cases even examining the phase of the signal.

As Jiaru points out, 160 ft is probably beyond the intended range, but that doesn't necessarily mean that a packet will never get through, only that one shouldn't expect it to work at that distance.

How to change default timezone for Active Record in Rails?

On rails 4.2.2, go to application.rb and use config.time_zone='city' (e.g.:'London' or 'Bucharest' or 'Amsterdam' and so on).

It should work just fine. It worked for me.

What does double question mark (??) operator mean in PHP

$myVar = $someVar ?? 42;

Is equivalent to :

$myVar = isset($someVar) ? $someVar : 42;

For constants, the behaviour is the same when using a constant that already exists :

define("FOO", "bar");
define("BAR", null);

$MyVar = FOO ?? "42";
$MyVar2 = BAR ?? "42";

echo $MyVar . PHP_EOL;  // bar
echo $MyVar2 . PHP_EOL; // 42

However, for constants that don't exist, this is different :

$MyVar3 = IDONTEXIST ?? "42"; // Raises a warning
echo $MyVar3 . PHP_EOL;       // IDONTEXIST

Warning: Use of undefined constant IDONTEXIST - assumed 'IDONTEXIST' (this will throw an Error in a future version of PHP)

Php will convert the non-existing constant to a string.

You can use constant("ConstantName") that returns the value of the constant or null if the constant doesn't exist, but it will still raise a warning. You can prepended the function with the error control operator @ to ignore the warning message :

$myVar = @constant("IDONTEXIST") ?? "42"; // No warning displayed anymore
echo $myVar . PHP_EOL; // 42

how to convert rgb color to int in java

Use getRGB(), it helps ( no complicated programs )

Returns an array of integer pixels in the default RGB color model (TYPE_INT_ARGB) and default sRGB color space, from a portion of the image data.

How to prove that a problem is NP complete?

To show a problem is NP complete, you need to:

Show it is in NP

In other words, given some information C, you can create a polynomial time algorithm V that will verify for every possible input X whether X is in your domain or not.

Example

Prove that the problem of vertex covers (that is, for some graph G, does it have a vertex cover set of size k such that every edge in G has at least one vertex in the cover set?) is in NP:

  • our input X is some graph G and some number k (this is from the problem definition)

  • Take our information C to be "any possible subset of vertices in graph G of size k"

  • Then we can write an algorithm V that, given G, k and C, will return whether that set of vertices is a vertex cover for G or not, in polynomial time.

Then for every graph G, if there exists some "possible subset of vertices in G of size k" which is a vertex cover, then G is in NP.

Note that we do not need to find C in polynomial time. If we could, the problem would be in `P.

Note that algorithm V should work for every G, for some C. For every input there should exist information that could help us verify whether the input is in the problem domain or not. That is, there should not be an input where the information doesn't exist.

Prove it is NP Hard

This involves getting a known NP-complete problem like SAT, the set of boolean expressions in the form:

(A or B or C) and (D or E or F) and ...

where the expression is satisfiable, that is there exists some setting for these booleans, which makes the expression true.

Then reduce the NP-complete problem to your problem in polynomial time.

That is, given some input X for SAT (or whatever NP-complete problem you are using), create some input Y for your problem, such that X is in SAT if and only if Y is in your problem. The function f : X -> Y must run in polynomial time.

In the example above, the input Y would be the graph G and the size of the vertex cover k.

For a full proof, you'd have to prove both:

  • that X is in SAT => Y in your problem

  • and Y in your problem => X in SAT.

marcog's answer has a link with several other NP-complete problems you could reduce to your problem.

Footnote: In step 2 (Prove it is NP-hard), reducing another NP-hard (not necessarily NP-complete) problem to the current problem will do, since NP-complete problems are a subset of NP-hard problems (that are also in NP).

Read a zipped file as a pandas DataFrame

For "zip" files, you can use import zipfile and your code will be working simply with these lines:

import zipfile
import pandas as pd
with zipfile.ZipFile("Crime_Incidents_in_2013.zip") as z:
   with z.open("Crime_Incidents_in_2013.csv") as f:
      train = pd.read_csv(f, header=0, delimiter="\t")
      print(train.head())    # print the first 5 rows

And the result will be:

X,Y,CCN,REPORT_DAT,SHIFT,METHOD,OFFENSE,BLOCK,XBLOCK,YBLOCK,WARD,ANC,DISTRICT,PSA,NEIGHBORHOOD_CLUSTER,BLOCK_GROUP,CENSUS_TRACT,VOTING_PRECINCT,XCOORD,YCOORD,LATITUDE,LONGITUDE,BID,START_DATE,END_DATE,OBJECTID
0  -77.054968548763071,38.899775938598317,0925135...                                                                                                                                                               
1  -76.967309569035052,38.872119553647011,1003352...                                                                                                                                                               
2  -76.996184958456539,38.927921847721443,1101010...                                                                                                                                                               
3  -76.943077541353617,38.883686046653935,1104551...                                                                                                                                                               
4  -76.939209158039446,38.892278093281632,1125028...

MVC Redirect to View from jQuery with parameters

If your click handler is successfully called then this should work:

$('#results').on('click', '.item', function () {
            var NestId = $(this).data('id');
            var url = "/Artists/Details?NestId=" + NestId; 
            window.location.href = url; 
        })

EDIT: In this particular case given that the action method parameter is a string which is nullable, then if NestId == null, won't cause any exception at all, given that the ModelBinder won't complain about it.

Convert byte to string in Java

you can use

the character equivalent to 0x63 is 'c' but byte equivalent to it is 99

System.out.println("byte "+(char)0x63); 

What is the most useful script you've written for everyday life?

alias snoot='find . ! -path "*/.svn*" -print0 | xargs -0 egrep '

Visual Studio 2015 doesn't have cl.exe

For me that have Visual Studio 2015 this works:
Search this in the start menu: Developer Command Prompt for VS2015 and run the program in the search result.
You can now execute your command in it, for example: cl /?

how to get files from <input type='file' .../> (Indirect) with javascript

Based on Ray Nicholus's answer :

inputElement.onchange = function(event) {
   var fileList = inputElement.files;
   //TODO do something with fileList.  
}

using this will also work :

inputElement.onchange = function(event) {
   var fileList = event.target.files;
   //TODO do something with fileList.  
}

When correctly use Task.Run and when just async-await

One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get

public class PageViewModel : IHandle<SomeMessage>
{
   ...

   public async void Handle(SomeMessage message)
   {
      ShowLoadingAnimation();

      // makes UI very laggy, but still not dead
      await this.contentLoader.LoadContentAsync(); 

      HideLoadingAnimation();   
   }
}

public class ContentLoader 
{
    public async Task LoadContentAsync()
    {
        var tasks = new List<Task>();
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoIoBoundWorkAsync());
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoSomeOtherWorkAsync());

        await Task.WhenAll(tasks).ConfigureAwait(false);
    }
}

Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.

How to create a shared library with cmake?

Always specify the minimum required version of cmake

cmake_minimum_required(VERSION 3.9)

You should declare a project. cmake says it is mandatory and it will define convenient variables PROJECT_NAME, PROJECT_VERSION and PROJECT_DESCRIPTION (this latter variable necessitate cmake 3.9):

project(mylib VERSION 1.0.1 DESCRIPTION "mylib description")

Declare a new library target. Please avoid the use of file(GLOB ...). This feature does not provide attended mastery of the compilation process. If you are lazy, copy-paste output of ls -1 sources/*.cpp :

add_library(mylib SHARED
    sources/animation.cpp
    sources/buffers.cpp
    [...]
)

Set VERSION property (optional but it is a good practice):

set_target_properties(mylib PROPERTIES VERSION ${PROJECT_VERSION})

You can also set SOVERSION to a major number of VERSION. So libmylib.so.1 will be a symlink to libmylib.so.1.0.0.

set_target_properties(mylib PROPERTIES SOVERSION 1)

Declare public API of your library. This API will be installed for the third-party application. It is a good practice to isolate it in your project tree (like placing it include/ directory). Notice that, private headers should not be installed and I strongly suggest to place them with the source files.

set_target_properties(mylib PROPERTIES PUBLIC_HEADER include/mylib.h)

If you work with subdirectories, it is not very convenient to include relative paths like "../include/mylib.h". So, pass a top directory in included directories:

target_include_directories(mylib PRIVATE .)

or

target_include_directories(mylib PRIVATE include)
target_include_directories(mylib PRIVATE src)

Create an install rule for your library. I suggest to use variables CMAKE_INSTALL_*DIR defined in GNUInstallDirs:

include(GNUInstallDirs)

And declare files to install:

install(TARGETS mylib
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})

You may also export a pkg-config file. This file allows a third-party application to easily import your library:

Create a template file named mylib.pc.in (see pc(5) manpage for more information):

prefix=@CMAKE_INSTALL_PREFIX@
exec_prefix=@CMAKE_INSTALL_PREFIX@
libdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@

Name: @PROJECT_NAME@
Description: @PROJECT_DESCRIPTION@
Version: @PROJECT_VERSION@

Requires:
Libs: -L${libdir} -lmylib
Cflags: -I${includedir}

In your CMakeLists.txt, add a rule to expand @ macros (@ONLY ask to cmake to not expand variables of the form ${VAR}):

configure_file(mylib.pc.in mylib.pc @ONLY)

And finally, install generated file:

install(FILES ${CMAKE_BINARY_DIR}/mylib.pc DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig)

You may also use cmake EXPORT feature. However, this feature is only compatible with cmake and I find it difficult to use.

Finally the entire CMakeLists.txt should looks like:

cmake_minimum_required(VERSION 3.9)
project(mylib VERSION 1.0.1 DESCRIPTION "mylib description")
include(GNUInstallDirs)
add_library(mylib SHARED src/mylib.c)
set_target_properties(mylib PROPERTIES
    VERSION ${PROJECT_VERSION}
    SOVERSION 1
    PUBLIC_HEADER api/mylib.h)
configure_file(mylib.pc.in mylib.pc @ONLY)
target_include_directories(mylib PRIVATE .)
install(TARGETS mylib
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(FILES ${CMAKE_BINARY_DIR}/mylib.pc
    DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig)

Remove object from a list of objects in python

You could try this to dynamically remove an object from an array without looping through it? Where e and t are just random objects.

>>> e = {'b':1, 'w': 2}
>>> t = {'b':1, 'w': 3}
>>> p = [e,t]
>>> p
[{'b': 1, 'w': 2}, {'b': 1, 'w': 3}]
>>>
>>> p.pop(p.index({'b':1, 'w': 3}))
{'b': 1, 'w': 3}
>>> p
[{'b': 1, 'w': 2}]
>>>

Split List into Sublists with LINQ

I find this little snippet does the job quite nicely.

public static IEnumerable<List<T>> Chunked<T>(this List<T> source, int chunkSize)
{
    var offset = 0;

    while (offset < source.Count)
    {
        yield return source.GetRange(offset, Math.Min(source.Count - offset, chunkSize));
        offset += chunkSize;
    }
}

Get the last item in an array

How about something like below:

if ('index.html' === array[array.length - 1]) {  
   //do this 
} else { 
   //do that 
}

If using Underscore or Lodash, you can use _.last(), so something like:

if ('index.html' === _.last(array)) {  
   //do this 
} else { 
   //do that 
}

Or you can create your own last function:

const _last = arr => arr[arr.length - 1];

and use it like:

if ('index.html' === _last(array)) {  
   //do this 
} else { 
   //do that 
}

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

Print in one line dynamically

for Python 2.7

for x in range(0, 3):
    print x,

for Python 3

for x in range(0, 3):
    print(x, end=" ")

Can I use a case/switch statement with two variables?

I don't believe a switch/case is any faster than a series of if/elseif's. They do the same thing, but if/elseif's you can check multiple variables. You cannot use a switch/case on more than one value.

How should I use Outlook to send code snippets?

If you attach your code as a text file and your recipient(s) have "show attachments inline" option set (I believe it's set by default), Outlook should not mangle your code but it will be copy/paste-able directly from email.

Best way to pretty print a hash

For large nested hashes this script could be helpful for you. It prints a nested hash in a nice python/like syntax with only indents to make it easy to copy.

module PrettyHash
  # Usage: PrettyHash.call(nested_hash)
  # Prints the nested hash in the easy to look on format
  # Returns the amount of all values in the nested hash

  def self.call(hash, level: 0, indent: 2)
    unique_values_count = 0
    hash.each do |k, v|
      (level * indent).times { print ' ' }
      print "#{k}:"
      if v.is_a?(Hash)
        puts
        unique_values_count += call(v, level: level + 1, indent: indent)
      else
        puts " #{v}"
        unique_values_count += 1
      end
    end
    unique_values_count
  end
end

Example usage:

  h = {a: { b: { c: :d }, e: :f }, g: :i }
  PrettyHash.call(h)

a:
  b:
    c: d
  e: f
g: i
=> 3

The returned value is the count (3) of all the end-level values of the nested hash.

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

You need to add the "Maven Dependency" in the Deployment Assembly

  • right click on your project and choose properties.
  • click on Deployment Assembly.
  • click add
  • click on "Java Build Path Entries"
  • select Maven Dependencies"
  • click Finish.

Rebuild and deploy again

Note: This is also applicable for non maven project.

How to mount a single file in a volume

You can also use a relative path in your docker-compose.yml file like this (tested on Windows host, Linux container):

volumes:
    - ./test.conf:/fluentd/etc/test.conf

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

How do I set the maximum line length in PyCharm?

Here is screenshot of my Pycharm. Required settings is in following path: File -> Settings -> Editor -> Code Style -> General: Right margin (columns)

Pycharm 4 Settings Screenshot

How can I convert an HTML table to CSV?

Based on audiodude's answer, but simplified by using the built-in CSV library

require 'nokogiri'
require 'csv'

doc = Nokogiri::HTML(table_string)
csv = CSV.open("output.csv", 'w')

doc.xpath('//table//tr').each do |row|
    tarray = [] #temporary array
    row.xpath('td').each do |cell|
        tarray << cell.text #Build array of that row of data.
    end
    csv << tarray #Write that row out to csv file
end

csv.close

I did wonder if there was any way to take the Nokogiri NodeSet (row.xpath('td')) and write this out as an array to the csv file in one step. But I could only figure out doing it by iterating over each cell and building the temporary array of each cell's content.

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

TL;DR. You can get around this by expressing your queries as MyModel::query()->find(10); instead of MyModel::find(10);.

To the best of my knowledge, starting PhpStorm 2017.2 code inspection fails for methods such as MyModel::where(), MyModel::find(), etc (check this thread). This could get quite annoying, when you try let's say to use PhpStorm's Git integration before committing your code, PhpStorm won't stop complaining about these static method call warnings.

One elegant way (IMOO) to get around this is to explicitly call ::query() wherever it makes sense to. This will let you benefit from a free auto-completion and a nice query formatting.

Examples

Snippet where inspection complains about static method calls

$myModel = MyModel::find(10); // static call complaint

// another poorly formatted query with code inspection complaints
$myFilteredModels = MyModel::where('is_beautiful', true)
    ->where('is_not_smart', false)
    ->get();

Well formatted code with no complaints

$myModel = MyModel::query()->find(10);

// a nicely formatted query with no complaints
$myFilteredModels = MyModel::query()
    ->where('is_beautiful', true)
    ->where('is_not_smart', false)
    ->get();

How to get the class of the clicked element?

$("li").click(function(){
    alert($(this).attr("class"));
});

How to change color of the back arrow in the new material theme?

The answer by Carles is the correct answer, but few of the methods like getDrawable(), getColor() got deprecated at the time I am writing this answer. So the updated answer would be

Drawable upArrow = ContextCompat.getDrawable(context, R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(ContextCompat.getColor(context, R.color.white), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);

Following some other stackoverflow queries I found that calling ContextCompat.getDrawable() is similar to

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    return resources.getDrawable(id, context.getTheme());
} else {
    return resources.getDrawable(id);
}

And ContextCompat.getColor() is similar to

public static final int getColor(Context context, int id) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= 23) {
        return ContextCompatApi23.getColor(context, id);
    } else {
        return context.getResources().getColor(id);
    }
}

Link 1: ContextCompat.getDrawable()

Link 2: ContextCompat.getColor()

Creating an empty list in Python

list() is inherently slower than [], because

  1. there is symbol lookup (no way for python to know in advance if you did not just redefine list to be something else!),

  2. there is function invocation,

  3. then it has to check if there was iterable argument passed (so it can create list with elements from it) ps. none in our case but there is "if" check

In most cases the speed difference won't make any practical difference though.

Load different application.yml in SpringBoot Test

See this: Spring @PropertySource using YAML

I think the 3rd answer has what you're looking for, i.e have a separate POJO to map your yaml values into:

@ConfigurationProperties(path="classpath:/appprops.yml", name="db")
public class DbProperties {
    private String url;
    private String username;
    private String password;
...
}

Then annotate your test class with this:

@EnableConfigurationProperties(DbProperties.class)
public class PropertiesUsingService {

    @Autowired private DbProperties dbProperties;

}

Start/Stop and Restart Jenkins service on Windows

To Start Jenkins through Command Line

  1. Run CMD with admin

  2. You can run following commands

    "net start servicename" to start

    "net restart servicename" to restart

    "net stop servicename" to stop service

for more reference https://www.windows-commandline.com/start-stop-service-command-line/

Does file_get_contents() have a timeout setting?

As @diyism mentioned, "default_socket_timeout, stream_set_timeout, and stream_context_create timeout are all the timeout of every line read/write, not the whole connection timeout." And the top answer by @stewe has failed me.

As an alternative to using file_get_contents, you can always use curl with a timeout.

So here's a working code that works for calling links.

$url='http://example.com/';
$ch=curl_init();
$timeout=5;

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

$result=curl_exec($ch);
curl_close($ch);
echo $result;

How to check the version before installing a package using apt-get?

Also, according to the man page:

apt-cache showpkg <package_name>

can also be used to:

...display information about the packages listed on the command line. Remaining arguments are package names. The available versions and reverse dependencies of each package listed are listed, as well as forward dependencies for each version. Forward (normal) dependencies are those packages upon which the package in question depends; reverse dependencies are those packages that depend upon the package in question. Thus, forward dependencies must be satisfied for a package, but reverse dependencies need not be.

Ex:

apt-cache policy conky

conky:
  Installed: (none)
  Candidate: 1.10.3-1
  Version table:
     1.10.3-1 500
        500 http://us.archive.ubuntu.com/ubuntu yakkety/universe amd64 Packages
        500 http://us.archive.ubuntu.com/ubuntu yakkety/universe i386 Packages

response.sendRedirect() from Servlet to JSP does not seem to work

Since you already have sent some data,

System.out.println("going to demo.jsp");

you won't be able to send a redirect.

Make selected block of text uppercase

Creator of the change-case extension here. I've updated the extension to support spanning lines.

To map the upper case command to a keybinding (e.g. CTRL+T+U), click File -> Preferences -> Keyboard shortcuts, and insert the following into the json config:

{
  "key": "ctrl+t ctrl+u",
  "command": "extension.changeCase.upper",
  "when": "editorTextFocus"
}

EDIT:

With the November 2016 (release notes) update of VSCode, there is built-in support for converting to upper case and lower case via the commands editor.action.transformToUppercase and editor.action.transformToLowercase. These don't have default keybindings. They also work with multi-line blocks.

The change-case extension is still useful for other text transformations, e.g. camelCase, PascalCase, snake_case, kebab-case, etc.

How to create JSON string in C#

If you need complex result (embedded) create your own structure:

class templateRequest
{
    public String[] registration_ids;
    public Data data;
    public class Data
    {
        public String message;
        public String tickerText;
        public String contentTitle;
        public Data(String message, String tickerText, string contentTitle)
        {
            this.message = message;
            this.tickerText = tickerText;
            this.contentTitle = contentTitle;
        }                
    };
}

and then you can obtain JSON string with calling

List<String> ids = new List<string>() { "id1", "id2" };
templateRequest request = new templeteRequest();
request.registration_ids = ids.ToArray();
request.data = new templateRequest.Data("Your message", "Your ticker", "Your content");

string json = new JavaScriptSerializer().Serialize(request);

The result will be like this:

json = "{\"registration_ids\":[\"id1\",\"id2\"],\"data\":{\"message\":\"Your message\",\"tickerText\":\"Your ticket\",\"contentTitle\":\"Your content\"}}"

Hope it helps!

SSH configuration: override the default username

You can use a shortcut. Create a .bashrc file in your home directory. In there, you can add the following:

alias sshb="ssh buck@host"

To make the alias available in your terminal, you can either close and open your terminal, or run

source ~/.bashrc

Then you can connect by just typing in:

sshb

java: ArrayList - how can I check if an index exists?

Since java-9 there is a standard way of checking if an index belongs to the array - Objects#checkIndex() :

List<Integer> ints = List.of(1,2,3);
System.out.println(Objects.checkIndex(1,ints.size())); // 1
System.out.println(Objects.checkIndex(10,ints.size())); //IndexOutOfBoundsException

How to do a simple file search in cmd

dir /s *foo* searches in current folder and sub folders.

It finds directories as well as files.

where /s means(documentation):

/s Lists every occurrence of the specified file name within the specified directory and all subdirectories.

Return a value of '1' a referenced cell is empty

Since required quite often it might as well be brief:

=1*(A1="")

This will not return 1 if the cell appears empty but contains say a space or a formula of the kind =IF(B1=3,"Yes","") where B1 does not contain 3.

=A1="" will return either TRUE or FALSE but those in an equation are treated as 1 and 0 respectively so multiplying TRUE by 1 returns 1.

Much the same can be achieved with the double unary --:

=--(A1="")  

where when A1 is empty one minus negates TRUE into -1 and the other negates that to 1 (just + in place of -- however does not change TRUE to 1).

Trying to fire the onload event on script tag

I faced a similar problem, trying to test if jQuery is already present on a page, and if not force it's load, and then execute a function. I tried with @David Hellsing workaround, but with no chance for my needs. In fact, the onload instruction was immediately evaluated, and then the $ usage inside this function was not yet possible (yes, the huggly "$ is not a function." ^^).

So, I referred to this article : https://developer.mozilla.org/fr/docs/Web/Events/load and attached a event listener to my script object.

var script = document.createElement('script');
script.type = "text/javascript";
script.addEventListener("load", function(event) {
    console.log("script loaded :)");
    onjqloaded();
});
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);

For my needs, it works fine now. Hope this can help others :)

How to generate a unique hash code for string input in android...?

A few line of java code.

public static void main(String args[]) throws Exception{
       String str="test string";
       MessageDigest messageDigest=MessageDigest.getInstance("MD5");
       messageDigest.update(str.getBytes(),0,str.length());
       System.out.println("MD5: "+new BigInteger(1,messageDigest.digest()).toString(16));
}

c# Image resizing to different size while preserving aspect ratio

To get a faster result, the function that obtains the size could be found in resultSize:

Size original = new Size(640, 480);

int maxSize = 100;

float percent = (new List<float> { (float)maxSize / (float)original.Width , (float)maxSize  / (float)original.Height }).Min();

Size resultSize = new Size((int)Math.Floor(original.Width * percent), (int)Math.Floor(original.Height * percent));

Uses Linq to minimize variable and recalculations, as well as unnecesary if/else statements

How to scroll to an element?

I might be late to the party but I was trying to implement dynamic refs to my project the proper way and all the answer I have found until know aren't quiet satisfying to my liking, so I came up with a solution that I think is simple and uses the native and recommended way of react to create the ref.

sometimes you find that the way documentation is wrote assumes that you have a known amount of views and in most cases this number is unknown so you need a way to solve the problem in this case, create dynamic refs to the unknown number of views you need to show in the class

so the most simple solution i could think of and worked flawlessly was to do as follows

class YourClass extends component {

state={
 foo:"bar",
 dynamicViews:[],
 myData:[] //get some data from the web
}

inputRef = React.createRef()

componentDidMount(){
  this.createViews()
}


createViews = ()=>{
const trs=[]
for (let i = 1; i < this.state.myData.lenght; i++) {

let ref =`myrefRow ${i}`

this[ref]= React.createRef()

  const row = (
  <tr ref={this[ref]}>
<td>
  `myRow ${i}`
</td>
</tr>
)
trs.push(row)

}
this.setState({dynamicViews:trs})
}

clickHandler = ()=>{

//const scrollToView = this.inputRef.current.value
//That to select the value of the inputbox bt for demostrate the //example

value=`myrefRow ${30}`

  this[value].current.scrollIntoView({ behavior: "smooth", block: "start" });
}


render(){

return(
<div style={{display:"flex", flexDirection:"column"}}>
<Button onClick={this.clickHandler}> Search</Button>
<input ref={this.inputRef}/>
<table>
<tbody>
{this.state.dynamicViews}
<tbody>
<table>
</div>


)

}

}

export default YourClass

that way the scroll will go to whatever row you are looking for..

cheers and hope it helps others

Clear Cache in Android Application programmatically

If you are looking for delete cache of your own application then simply delete your cache directory and its all done !

public static void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        deleteDir(dir);
    } catch (Exception e) { e.printStackTrace();}
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
        return dir.delete();
    } else if(dir!= null && dir.isFile()) {
        return dir.delete();
    } else {
        return false;
    }
}

Callback functions in Java

For simplicity, you can use a Runnable:

private void runCallback(Runnable callback)
{
    // Run callback
    callback.run();
}

Usage:

runCallback(new Runnable()
{
    @Override
    public void run()
    {
        // Running callback
    }
});

How do I get which JRadioButton is selected from a ButtonGroup

I would just loop through your JRadioButtons and call isSelected(). If you really want to go from the ButtonGroup you can only get to the models. You could match the models to the buttons, but then if you have access to the buttons, why not use them directly?

Can local storage ever be considered secure?

Well, the basic premise here is: no, it is not secure yet.

Basically, you can't run crypto in JavaScript: JavaScript Crypto Considered Harmful.

The problem is that you can't reliably get the crypto code into the browser, and even if you could, JS isn't designed to let you run it securely. So until browsers have a cryptographic container (which Encrypted Media Extensions provide, but are being rallied against for their DRM purposes), it will not be possible to do securely.

As far as a "Better way", there isn't one right now. Your only alternative is to store the data in plain text, and hope for the best. Or don't store the information at all. Either way.

Either that, or if you need that sort of security, and you need local storage, create a custom application...

Symfony2 : How to get form validation errors after binding the request to the form

The function for symfony 2.1 and newer, without any deprecated function:

/**
 * @param \Symfony\Component\Form\Form $form
 *
 * @return array
 */
private function getErrorMessages(\Symfony\Component\Form\Form $form)
{
    $errors = array();

    if ($form->count() > 0) {
        foreach ($form->all() as $child) {
            /**
             * @var \Symfony\Component\Form\Form $child
             */
            if (!$child->isValid()) {
                $errors[$child->getName()] = $this->getErrorMessages($child);
            }
        }
    } else {
        /**
         * @var \Symfony\Component\Form\FormError $error
         */
        foreach ($form->getErrors() as $key => $error) {
            $errors[] = $error->getMessage();
        }
    }

    return $errors;
}

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

Robert Love's book LINUX System Programming 2nd Edition, specifically addresses your question at the beginning of Chapter 11, pg 363:

The important aspect of a monotonic time source is NOT the current value, but the guarantee that the time source is strictly linearly increasing, and thus useful for calculating the difference in time between two samplings

That said, I believe he is assuming the processes are running on the same instance of an OS, so you might want to have a periodic calibration running to be able to estimate drift.

Plot correlation matrix using pandas

Try this function, which also displays variable names for the correlation matrix:

def plot_corr(df,size=10):
    '''Function plots a graphical correlation matrix for each pair of columns in the dataframe.

    Input:
        df: pandas DataFrame
        size: vertical and horizontal size of the plot'''

    corr = df.corr()
    fig, ax = plt.subplots(figsize=(size, size))
    ax.matshow(corr)
    plt.xticks(range(len(corr.columns)), corr.columns);
    plt.yticks(range(len(corr.columns)), corr.columns);

How do I change the default schema in sql developer?

Just create a new connection (hit the green plus sign) and enter the schema name and password of the new default schema your DBA suggested. You can switch between your old schema and the new schema with the pull down menu at the top right end of your window.

How to set True as default value for BooleanField on Django?

In DJango 3.0 the default value of a BooleanField in model.py is set like this:

class model_name(models.Model):
example_name = models.BooleanField(default=False)

Is there a way to reset IIS 7.5 to factory settings?

What worked for me was going to the article someone else had already mentioned, but keying on this piece:

application.config.backup is not created by automatic backup. The backup files are in %systemdrive%\inetpub\history directory. Automatic backup is also a Vista SP1 and above feature. More information can be found in this blog post, http://blogs.iis.net/bills/archive/2008/03/24/how-to-backup-restore-iis7-configuration.aspx

I was able to find backups of my settings from when I had first installed IIS, and just copy and replace the files in the inetsrv\config directory.

Source: http://forums.iis.net/t/1085990.aspx

Keystore type: which one to use?

Here is a post which introduces different types of keystore in Java and the differences among different types of keystore. http://www.pixelstech.net/article/1408345768-Different-types-of-keystore-in-Java----Overview

Below are the descriptions of different keystores from the post:

JKS, Java Key Store. You can find this file at sun.security.provider.JavaKeyStore. This keystore is Java specific, it usually has an extension of jks. This type of keystore can contain private keys and certificates, but it cannot be used to store secret keys. Since it's a Java specific keystore, so it cannot be used in other programming languages.

JCEKS, JCE key store. You can find this file at com.sun.crypto.provider.JceKeyStore. This keystore has an extension of jceks. The entries which can be put in the JCEKS keystore are private keys, secret keys and certificates.

PKCS12, this is a standard keystore type which can be used in Java and other languages. You can find this keystore implementation at sun.security.pkcs12.PKCS12KeyStore. It usually has an extension of p12 or pfx. You can store private keys, secret keys and certificates on this type.

PKCS11, this is a hardware keystore type. It servers an interface for the Java library to connect with hardware keystore devices such as Luna, nCipher. You can find this implementation at sun.security.pkcs11.P11KeyStore. When you load the keystore, you no need to create a specific provider with specific configuration. This keystore can store private keys, secret keys and cetrificates. When loading the keystore, the entries will be retrieved from the keystore and then converted into software entries.

Android change SDK version in Eclipse? Unable to resolve target android-x

This Problem is because of Path so you need to build the path using following Steps

Goto project ----->Right Click on Project Name ---->properties ---->click on Than Java Build Path option than ---> click Android 4.2.2---->Ok

Chrome refuses to execute an AJAX script due to wrong MIME type

For the record and Google search users, If you are a .NET Core developer, you should set the content-types manually, because their default value is null or empty:

var provider = new FileExtensionContentTypeProvider();
app.UseStaticFiles(new StaticFileOptions
{
    ContentTypeProvider = provider
});

How to convert a Kotlin source file to a Java source file

As @louis-cad mentioned "Kotlin source -> Java's byte code -> Java source" is the only solution so far.

But I would like to mention the way, which I prefer: using Jadx decompiler for Android.

It allows to see the generates code for closures and, as for me, resulting code is "cleaner" then one from IntelliJ IDEA decompiler.

Normally when I need to see Java source code of any Kotlin class I do:

  • Generate apk: ./gradlew assembleDebug
  • Open apk using Jadx GUI: jadx-gui ./app/build/outputs/apk/debug/app-debug.apk

In this GUI basic IDE functionality works: class search, click to go declaration. etc.

Also all the source code could be saved and then viewed using other tools like IntelliJ IDEA.

Javascript Print iframe contents only

If you are setting the contents of IFrame using javascript document.write() then you must close the document by newWin.document.close(); otherwise the following code will not work and print will print the contents of whole page instead of only the IFrame contents.

var frm = document.getElementById(id).contentWindow;
frm.focus();// focus on contentWindow is needed on some ie versions
frm.print();

How many characters can you store with 1 byte?

1 byte may hold 1 character. For Example: Refer Ascii values for each character & convert into binary. This is how it works.

enter image description here value 255 is stored as (11111111) base 2. Visit this link for knowing more about binary conversion. http://acc6.its.brooklyn.cuny.edu/~gurwitz/core5/nav2tool.html

Size of Tiny Int = 1 Byte ( -128 to 127)

Int = 4 Bytes (-2147483648 to 2147483647)

How can I enable auto complete support in Notepad++?

The link provided by Mark no longer works, but you can go to:

Notpad++ 6.6.9

  • Settings -> Preferences -> Auto-Completion -> Enable auto-completion on each input.

I find it very annoying though, since a big autocomplete block is always coming up and I would just like to see autocomplete when I press tab or a key combination. I am fairly new to Notepad++ though. If you know of such a key combination, please feel free to reply. I found this question via Google, so we can always help others.enter image description here

Link a .css on another folder

I think what you want to do is

_x000D_
_x000D_
<link rel="stylesheet" type="text/css" href="font/font-face/my-font-face.css">
_x000D_
_x000D_
_x000D_

#1071 - Specified key was too long; max key length is 1000 bytes

I have just made bypass this error by just changing the values of the "length" in the original database to the total of around "1000" by changing its structure, and then exporting the same, to the server. :)

SQL join on multiple columns in same tables

You want to join on condition 1 AND condition 2, so simply use the AND keyword as below

ON a.userid = b.sourceid AND a.listid = b.destinationid;

Setting the JVM via the command line on Windows

yes I often need to have 3 or more JVM's installed. For example, I've noticed that sometimes the JRE is slightly different to the JDK version of the JRE.

My go to solution on Windows for a bit of 'packaging' is something like this:

@echo off
setlocal
@rem  _________________________
@rem
@set  JAVA_HOME=b:\lang\java\jdk\v1.6\u45\x64\jre
@rem
@set  JAVA_EXE=%JAVA_HOME%\bin\java
@set  VER=test
@set  WRK=%~d0%~p0%VER%
@rem
@pushd %WRK%
cd 
@echo.
@echo  %JAVA_EXE%  -jar %WRK%\openmrs-standalone.jar
       %JAVA_EXE%  -jar %WRK%\openmrs-standalone.jar 
@rem
@rem  _________________________
popd
endlocal
@exit /b

I think it is straightforward. The main thing is the setlocal and endlocal give your app a "personal environment" for what ever it does -- even if there's other programs to run.

RegExp in TypeScript

I think you want to test your RegExp in TypeScript, so you have to do like this:

var trigger = "2",
    regexp = new RegExp('^[1-9]\d{0,2}$'),
    test = regexp.test(trigger);
alert(test + ""); // will display true

You should read MDN Reference - RegExp, the RegExp object accepts two parameters pattern and flags which is nullable(can be omitted/undefined). To test your regex you have to use the .test() method, not passing the string you want to test inside the declaration of your RegExp!

Why test + ""? Because alert() in TS accepts a string as argument, it is better to write it this way. You can try the full code here.

Javascript can't find element by id?

Run the code either in onload event, either just before you close body tag. You try to find an element wich is not there at the moment you do it.

How to change the name of a Django app?

New in Django 1.7 is a app registry that stores configuration and provides introspection. This machinery let's you change several app attributes.

The main point I want to make is that renaming an app isn't always necessary: With app configuration it is possible to resolve conflicting apps. But also the way to go if your app needs friendly naming.

As an example I want to name my polls app 'Feedback from users'. It goes like this:

Create a apps.py file in the polls directory:

from django.apps import AppConfig

class PollsConfig(AppConfig):
    name = 'polls'
    verbose_name = "Feedback from users"

Add the default app config to your polls/__init__.py:

default_app_config = 'polls.apps.PollsConfig'

For more app configuration: https://docs.djangoproject.com/en/1.7/ref/applications/

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

Python, Unicode, and the Windows console

Note: This answer is sort of outdated (from 2008). Please use the solution below with care!!


Here is a page that details the problem and a solution (search the page for the text Wrapping sys.stdout into an instance):

PrintFails - Python Wiki

Here's a code excerpt from that page:

$ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \
    sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \
    line = u"\u0411\n"; print type(line), len(line); \
    sys.stdout.write(line); print line'
  UTF-8
  <type 'unicode'> 2
  ?
  ?

  $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \
    sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \
    line = u"\u0411\n"; print type(line), len(line); \
    sys.stdout.write(line); print line' | cat
  None
  <type 'unicode'> 2
  ?
  ?

There's some more information on that page, well worth a read.

SQL Query with Join, Count and Where

SELECT COUNT(*), table1.category_id, table2.category_name 
FROM table1 
INNER JOIN table2 ON table1.category_id=table2.category_id 
WHERE table1.colour <> 'red'
GROUP BY table1.category_id, table2.category_name 

How to calculate md5 hash of a file using javascript

Apart from the impossibility to get file system access in JS, I would not put any trust at all in a client-generated checksum. So generating the checksum on the server is mandatory in any case. – Tomalak Apr 20 '09 at 14:05

Which is useless in most cases. You want the MD5 computed at client side, so that you can compare it with the code recomputed at server side and conclude the upload went wrong if they differ. I have needed to do that in applications working with large files of scientific data, where receiving uncorrupted files were key. My cases was simple, cause users had the MD5 already computed from their data analysis tools, so I just needed to ask it to them with a text field.

Import JavaScript file and call functions using webpack, ES6, ReactJS

Named exports:

Let's say you create a file called utils.js, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:

export function add(x, y) {
  return x + y
}

export function mutiply(x, y) {
  return x * y
}

Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:

import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.

Or if you prefer, place the entire module's contents under a common namespace:

import * as utils from './utils.js'; 
...
utils.multiply(2,3)

Default exports:

If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js, with only one function that logs out whatever argument it's called with:

export default function log(message) {
  console.log(message);
}

This can now be used like this:

import log from './log.js';
...
log('test') // Would print 'test' in the console.

You don't have to call it log when you import it, you could actually call it whatever you want:

import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.

Combined:

A module can have both a default export (max 1), and named exports (imported either one by one, or using * with an alias). React actually has this, consider:

import React, { Component, PropTypes } from 'react';

Javascript Array of Functions

This is correct

var array_of_functions = {
            "all": function(flag) { 
                console.log(1+flag); 
              },
                "cic": function(flag) { 
                console.log(13+flag); 
              }                     
        };

array_of_functions.all(27);
array_of_functions.cic(7);

Why I get 411 Length required error?

Google search

2nd result

System.Net.WebException: The remote server returned an error: (411) Length Required.

This is a pretty common issue that comes up when trying to make call a REST based API method through POST. Luckily, there is a simple fix for this one.

This is the code I was using to call the Windows Azure Management API. This particular API call requires the request method to be set as POST, however there is no information that needs to be sent to the server.

var request = (HttpWebRequest) HttpWebRequest.Create(requestUri);
request.Headers.Add("x-ms-version", "2012-08-01"); request.Method =
"POST"; request.ContentType = "application/xml";

To fix this error, add an explicit content length to your request before making the API call.

request.ContentLength = 0;

How to extract hours and minutes from a datetime.datetime object?

Don't know how you want to format it, but you can do:

print("Created at %s:%s" % (t1.hour, t1.minute))

for example.

Is it possible to dynamically compile and execute C# code fragments?

Found this useful - ensures the compiled Assembly references everything you currently have referenced, since there's a good chance you wanted the C# you're compiling to use some classes etc in the code that's emitting this:

(string code is the dynamic C# being compiled)

        var refs = AppDomain.CurrentDomain.GetAssemblies();
        var refFiles = refs.Where(a => !a.IsDynamic).Select(a => a.Location).ToArray();
        var cSharp = (new Microsoft.CSharp.CSharpCodeProvider()).CreateCompiler();
        var compileParams = new System.CodeDom.Compiler.CompilerParameters(refFiles);
        compileParams.GenerateInMemory = true;
        compileParams.GenerateExecutable = false;

        var compilerResult = cSharp.CompileAssemblyFromSource(compileParams, code);
        var asm = compilerResult.CompiledAssembly;

In my case I was emitting a class, whose name was stored in a string, className, which had a single public static method named Get(), that returned with type StoryDataIds. Here's what calling that method looks like:

        var tempType = asm.GetType(className);
        var ids = (StoryDataIds)tempType.GetMethod("Get").Invoke(null, null);

Warning: Compilation can be surprisingly, extremely slow. A small, relatively simple 10-line chunk of code compiles at normal priority in 2-10 seconds on our relatively fast server. You should never tie calls to CompileAssemblyFromSource() to anything with normal performance expectations, like a web request. Instead, proactively compile code you need on a low-priority thread and have a way of dealing with code that requires that code to be ready, until it's had a chance to finish compiling. For example you could use it in a batch job process.

How do I call a Django function on button click?

The following answer could be helpful for the first part of your question:

Django: How can I call a view function from template?