Q:

Reading console input in Kotlin

I am attempting to accept input from the console in Kotlin but it is difficult because I am not too sure about the syntax.
I begin with the main
fun main(args: Array<String>) {

}

WHAT should I enter after this? I am aware that the println() and readline() are involved but I do not know how to structure them.
Objective: prompt user to enter a number, the number entered is multiplied by 6, program returns the result to the console display.

A:

Here are A+B examples in Kotlin reading from stdin:
fun main() {
  val (a, b) = readLine()!!.split(' ')
  println(a.toInt() + b.toInt())
}

or
fun main(vararg args: String) {
  val (a, b) = readLine()!!.split(' ').map(String::toInt)
  println(a + b)
}

or
fun readInts() = readLine()!!.split(' ').map { it.toInt() }

fun main(vararg args: String) {
  val (a, b) = readInts()
  println(a + b)
}

or
import java.util.Scanner

fun main() {
  val input = Scanner(System.`in`)
  val a = input.nextInt()
  val b = input.nextInt()
  println(a + b)
}

or
with(Scanner(System.`in`)) {
    val a = nextInt()
    val b = nextInt()
    println(a + b)
}

Competitive programming
Must-read intro: https://kotlinlang.org/docs/tutorials/competitive-programming.html
Must-watch Kotlin productivity videos: https://www.jetbrains.com/icpc/
Here is an (inspired by the article) extended bunch of helper functions for reading all possible types, lists, arrays, 2d-arrays, etc:
private fun readln() = readLine()!!
private fun readlnByte() = readln().toByte()
private fun readlnShort() = readln().toShort()
private fun readlnInt() = readln().toInt()
private fun readlnLong() = readln().toLong()
private fun readlnFloat() = readln().toFloat()
private fun readlnDouble() = readln().toDouble()
private fun readlnBigInt(radix: Int = 10) = readln().toBigInteger(radix)
private fun readlnBigDecimal() = readln().toBigDecimal()

private fun lineSequence(limit: Int = Int.MAX_VALUE) = generateSequence { readLine() }.constrainOnce().take(limit)
private fun readlnStrings() = readln().split(' ')
private fun readlnBytes() = readlnStrings().map { it.toByte() }
private fun readlnShorts() = readlnStrings().map { it.toShort() }
private fun readlnInts() = readlnStrings().map { it.toInt() }
private fun readlnLongs() = readlnStrings().map { it.toLong() }
private fun readlnFloats() = readlnStrings().map { it.toFloat() }
private fun readlnDoubles() = readlnStrings().map { it.toDouble() }

private fun readByteArray() = readlnStrings().run { ByteArray(size) { get(it).toByte() } }
private fun readShortArray() = readlnStrings().run { ShortArray(size) { get(it).toShort() } }
private fun readIntArray() = readlnStrings().run { IntArray(size) { get(it).toInt() } }
private fun readLongArray() = readlnStrings().run { LongArray(size) { get(it).toLong() } }
private fun readFloatArray() = readlnStrings().run { FloatArray(size) { get(it).toFloat() } }
private fun readDoubleArray() = readlnStrings().run { DoubleArray(size) { get(it).toDouble() } }

private fun readlnByteArray(n: Int) = ByteArray(n) { readlnByte() }
private fun readlnShortArray(n: Int) = ShortArray(n) { readlnShort() }
private fun readlnIntArray(n: Int) = IntArray(n) { readlnInt() }
private fun readlnLongArray(n: Int) = LongArray(n) { readlnLong() }
private fun readlnFloatArray(n: Int) = FloatArray(n) { readlnFloat() }
private fun readlnDoubleArray(n: Int) = DoubleArray(n) { readlnDouble() }

private fun readByteArray2d(rows: Int, cols: Int) = Array(rows) { readByteArray().also { require(it.size == cols) } }
private fun readShortArray2d(rows: Int, cols: Int) = Array(rows) { readShortArray().also { require(it.size == cols) } }
private fun readLongArray2d(rows: Int, cols: Int) = Array(rows) { readLongArray().also { require(it.size == cols) } }
private fun readIntArray2d(rows: Int, cols: Int) = Array(rows) { readIntArray().also { require(it.size == cols) } }
private fun readFloatArray2d(rows: Int, cols: Int) = Array(rows) { readFloatArray().also { require(it.size == cols) } }
private fun readDoubleArray2d(rows: Int, cols: Int) = Array(rows) { readDoubleArray().also { require(it.size == cols) } }

private fun isWhiteSpace(c: Char) = c in " \r\n\t"

// JVM-only targeting code follows next

// readString() via sequence is still slightly faster than Scanner
private fun readString() = generateSequence { System.`in`.read().toChar() }
        .dropWhile { isWhiteSpace(it) }.takeWhile { !isWhiteSpace(it) }.joinToString("")
private fun readByte() = readString().toByte()
private fun readShort() = readString().toShort()
private fun readInt() = readString().toInt()
private fun readLong() = readString().toLong()
private fun readFloat() = readString().toFloat()
private fun readDouble() = readString().toDouble()
private fun readBigInt(radix: Int = 10) = readString().toBigInteger(radix)
private fun readBigDecimal() = readString().toBigDecimal()

private fun readBytes(n: Int) = generateSequence { readByte() }.take(n)
private fun readShorts(n: Int) = generateSequence { readShort() }.take(n)
private fun readInts(n: Int) = generateSequence { readInt() }.take(n)
private fun readLongs(n: Int) = generateSequence { readLong() }.take(n)
private fun readFloats(n: Int) = generateSequence { readFloat() }.take(n)
private fun readDoubles(n: Int) = generateSequence { readDouble() }.take(n)

Beware that Scanner is somewhat slow. This may be important in some cases like competitive programming where program's execution on large inputs could be made up to two times faster just by replacing Scanner with plain readLine. Even my suboptimal readString() implementation tokenizing via sequence is slightly faster. It allows to read input tokens until any next whitespace unlike Kotlin's built-in readLine().
I hope someday a concise, crossplatform, performant, universal for both console and files input parsing support would be introduced in Kotlin stdlib. Like readInt, readLong, etc global and Reader extension functions.
This would be very userful not only for competitive programming but also for learning Kotlin as first language.
A concept of reading a number shouldn't require first explaining collections, lambdas and monads.

Bonus
Sometimes you start with console input/output but then need to switch to files.
It becomes too tedious to prepend every read or write call with file stream variable.
Here is a peace of Kotlin magic that allows to just wrap unchanged console code with a couple of lines to force it read and write to files also ensuring they are closed properly:
fun <T : Closeable, R> T.useWith(block: T.() -> R): R = use { with(it, block) }

File("a.in").bufferedReader().useWith {
    File("a.out").printWriter().useWith {
        val (a, b) = readLine()!!.split(' ').map(String::toInt)
        println(a + b)
    }
}

Scanner(File("b.in")).useWith {
    PrintWriter("b.out").useWith {
        val a = nextInt()
        val b = nextInt()
        println(a + b)
    }
}

Wrapping lines can be quickly commented out when happens a need to switch back to console.

A:

Use readLine() to take input from user,
  ATQ:
fun main(args:Array<String>){
    print("Enter a number")
    var variableName:Int = readLine()!!.toInt()  // readLine() is used to accept the String value and ".toInt()" will convert the string to  Int.
    var result:Int= variableName*6
    print("The output is:$result")
}


Q:

Drop down menu with sub category using R and Shiny

I want to create a dropdown menu with sub-categories using R - how is a sub-category supposed to be introduced?
`if (interactive()) {
 ui <- fluidPage(
selectInput("variable", "Variable:",
            c("HTML Code tester", "Font Styler", "CSS3 Generator", "Box Shadow", "Border Radius"))

)

server <- function(input, output) {

}

shinyApp(ui, server)
}`

Actual output: Actual Output
Desired Output: Desired Output
How do I create something like what's in desired output?
Thanks!

A:

This might work for you:
 selectInput("variable", "Variable:",
              list("HTML Code tester",
                   "Font Styler",
                   "CSS3 Generator"=c( "Box Shadow", "Border Radius")))


Q:

Project doesn't build when setting a View id of 1 or 100

I have added a Button and TextView using the Design view of Android Studio. I set the id for the Button to be 1 and the TextView to 100. When I try to build the project it errors out with error:  expected and error illegal start of type. This works if I programmatically set the id by using setId(1).
<Button
    android:id="@+id/1"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="44dp"
    android:text="1"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/locationBox" />

<TextView
    android:id="@+id/101"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_marginStart="16dp"
    android:text="0"
    android:textAlignment="center"
    android:textSize="24sp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/1" />

Any help would be appreciated

A:

This is because value for android:id can't be an integer. The value of android:id will be converted as an integer variable name in R.java. An integer can't be used as variable name.
Instead of setId() you need to use setTag() and findViewWithTag().

UPDATE
if you look at the setId() source code:
/**
 * Sets the identifier for this view. The identifier does not have to be
 * unique in this view's hierarchy. The identifier should be a positive
 * number.
 *
 * @see #NO_ID
 * @see #getId()
 * @see #findViewById(int)
 *
 * @param id a number used to identify the view
 *
 * @attr ref android.R.styleable#View_id
 */
public void setId(@IdRes int id) {
    mID = id;
    if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
        mID = generateViewId();
    }
}

You will find that setId() is not setting the id of View but the value id of the View. This is related with generateViewId():

Generate a value suitable for use in setId(int). This value will not
  collide with ID values generated at build time by aapt for R.id.


Q:

Change language from dynamically content using Javascript

My project should support different languages for the GUI (spanish, english, german, etc). I'm using CodeIgniter, so I haven't got any problem with PHP views using Language Class. I can load some previously defined vars on PHP to create views in different languages.
The problem comes here:
Some features (a lot of them actually) use Javascript: personalized context menu for some items, differents DIVs created dynamically, etc. The most of this features are created dynamically, so I can't know the language selected (I can create a lot of duplicated code, one for each language, but this is too redundant).
I need to find a way to translate this content into the new language previously selected by user.
For example:
The user right-click and the context menu have the following options (created dynamically using Javascript):

Hi
Goodbye

When the user change the page language to 'Spanish', the context menu should show:

Hola
Adios

Is there any way to save some variables with all the names in different languages, and then load to create the menus?
Sorry for the big post. I hope everyone can help me or bring me a little tip.

A:

there are several systems to use when you want i18n (short for "internationalization") to work in a server side language as well as in client side Javascript.
this is an example I found for PHP and JavaScript: http://doc.silverstripe.org/sapphire/en/topics/i18n
I've done this in PHP, Ruby and Python. In general there is one way this is done. You create a library of text. this library has pointers to specific pieces of that text. In your code you use that pointer to refer to that piece of text. What the example above does provide you a way to create a library in PHP that can be compiled to a JavaScript equivalent that you can call in JavaScript. Basically it completely separates copywriting and other text from the code.
I hope this helps you on your way.


Q:

How to have Linux ls command show second in time stamp

Something annoying about ls -l command is it shows only hour and minute for a file(like 08:30). How can I see the second portion(like 08:30:44)?
man 1 ls and search for 'second' does not give any clue.

A:

Does your version of ls support the --time-style option?  If so:
ls -la --time-style=full-iso blah

-rw-r--r-- 1 root root 0 2011-11-08 18:02:08.954092000 -0700 blah

A:

The more simple way is:
ls --full-time

which is equal to
ls -l --time-style=full-iso

If you want to show entries as hidden files starting with ., add -a:
ls --full-time -a

A:

For OS X, it looks like the best you get is:
ls -l -T

From the ls(1) manpage on 10.10.5:

-T When used with the -l (lowercase letter ``ell'') option, display complete time information for the file, including month, day, hour, minute, second, and year.


Q:

What does mean by port is open and close on a server?

I've got a reply from my server admin as "Do you need any ports open?"
On this server one website is hosted which is not getting loaded. So I conveyed him that the website is not getting loaded though I'm able to login to the given IP address through FTP client (File Zilla) and ssh (using terminal).
Actually I want to access the files at the said IP address through FTP client and its working fine. My main issue is that the website is not loading.
I'm not getting what does this question mean and what should I reply to it? I'm not aware of any such thing.

A:

Services on the network use different "ports" to distinguish between different endpoints. You can imagine a port number as a "sub-address". For successful connection you need to know an IP address and also the port number.
For example FTP protocol uses port 21. You can find more detailed list of commonly used ports on Wikipedia http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
The common phrase "open some port" means the access to that particular port will be enabled on firewall (usually all ports are "closed" because of security).
For your website you need ports 80 and 443 to be opened


Q:

How to display unique records without using distinct?

I'm using Oracle SQL. I have Table as Test and columns are A, B, C. In column A values are like:
1000,
1000,
1000,
2000,
2000,
3000

Result would be from column A:
  A
1000
2000
3000

Note: Except using Distinct syntax,.
Select Distinct A from Test;

A:

Use GROUP BY:
Select A from Test GROUP BY A

Group by, groups all the similar values of a specified column into one value (group).
Oracle Demo
Although, Group By is a standard sql and it doesn't matter what database you use.


Q:

What's the easiest way to get an equivalent to GNU grep that supports negative lookbehinds?

I'm trying to grep through a bunch of files in nested subdirectories to look for regular expression matches; my regex requires negative lookbehind.
Perl has negative lookbehind, but as far as I can tell GNU grep doesn't support negative lookbehinds.
What's the easiest way to get an equivalent to GNU grep that supports negative lookbehinds?
(I guess I could write my own mini-grep in Perl, but that doesn't seem like it should be necessary.  My copy of the Perl Cookbook includes source for tcgrep; is that what I should use?  If so, where's the latest version?  Don't tell me I have to type this entire program!)

A:

Use ack! Ack is written in Perl so it uses Perl's regex engine (by default).
The negative look-behind is ack "(?<!bad)boy" (per willert's comment)

A:

Thanks to a comment from other question. I've found that negative lookbehind is experimentally supported in grep with the -P/--perl-regexp option, so you may still not need to use a different tool if you prefer to keep using grep.
By the way, my preferred alternative to grep is grin (which is written in python).


Q:

Event pages and background pages

Since there's no clear explanation in Chrome Extensions documentation, I came here for help.
I learned that background pages are basically invented to extend the extension's lifetime, and designed to hold values or keep the "engine" running in background so no one notices it. Because once you click on the extension's icon, you get what they call it, a "popup", and once you click outside the "popup" it disappears immediately and most important the extension "dies" (its lifetime ends).
So far we are good and everything is nice but: event pages are invented after that
and they are basically background pages that only work when they are called (to provide more memory space).
If that's the case, then wouldn't that be contradictory? What's the use of event pages if they only work when they're called?

A:

Sometimes background pages only need to respond to events outside them (messages, web requests, button clicks, etc.)
In that case, an event page makes sense. It's not completely unloaded as if the extension is stopped - it defines its event handlers (what it wants to listen to) and then it's shut down until needed. Consider this to be "I'm going to sleep; don't wake me up unless A happens."
The difference with your example: closed popup ceases to exist completely, while Chrome remembers it needs to call a particular extension on particular events. If that event happens, the background page is started again an the event is fired in it.
This saves resources, but not always appropriate. Shutting down background page's context wipes its local state; it must be saved in various storage APIs instead of variables. If the local state is complex, it may not be worth the effort. Also, if your extension needs to react really fast or really often, suspend/resume may prove to be a performance hit.
All in all, event pages are not a complete replacement for background pages; that's why they are optional and not default. There are many things to consider when making an event page.
P.S. Regarding your "popup as most important part of the extension": this is exactly why it can't be the most important part in most cases. Usually, a background page is also used alongside a popup to keep event listeners and local state.


Q:

Phonegap Android with PushPlugin compilation failure

I'm trying to run a phonegap application with the PushPlugin installed.
I adde the plugin with this command:
$ phonegap local plugin add https://github.com/phonegap-build/PushPlugin

and it went through ok.
I added the PushNotification.js file to my "www" folder and referenced it in index.html.
Then I added some code to handle notifications in my index.js file.
I tried to run the application:
$ phonegap local run android

and got this:
-compile:
[javac] Compiling 8 source files to /Users/nadavelyashiv/Code/PushNotificationSample/platforms/android/bin/classes
[javac] /Users/nadavelyashiv/Code/PushNotificationSample/platforms/android/src/com/plugin/gcm/GCMIntentService.java:96: cannot find symbol
[javac] symbol  : method getString(java.lang.String)
[javac] location: class com.plugin.gcm.GCMIntentService
[javac]                 .setTicker(getString("title"))
[javac]                            ^
[javac] /Users/nadavelyashiv/Code/PushNotificationSample/platforms/android/src/com/plugin/gcm/GCMIntentService.java:95: cannot find symbol
[javac] symbol  : method getString(java.lang.String)
[javac] location: class com.plugin.gcm.GCMIntentService
[javac]                 .setContentTitle(getString("title"))
[javac]                                  ^
[javac] 2 errors
BUILD FAILED
/usr/local/Cellar/android-sdk/r22.0.4/tools/ant/build.xml:720: The following error occurred while executing this line:
/usr/local/Cellar/android-sdk/r22.0.4/tools/ant/build.xml:734: Compile failed; see the compiler error output for details.

What seems to be the problem here?
Thank you.

A:

Found issue, created a PullRequest on project :
https://github.com/phonegap-build/PushPlugin/pull/83/files
You should update the code of line 95 and 96 of android/com/plugin/gcm/GCMIntentService.java
            .setContentTitle(extras.getString("title"))
            .setTicker(extras.getString("title"))


Q:

LazyEnum with validation

Motivation
In the standard Python library enum, a subclass of Enum would create all its members upon class creation. This can be a huge waste of time and memory, especially if the class contains lots of members but only a fraction of them would ever get called.
As a practice project on metaclasses, I decided to implement a lazy version of Enum. This is not intended to be a full-fledged library, so I didn't implement most of the features in the standard enum library, just some basic functionalities.
In LazyEnum, a member would be created only when we ask to and it would be created only once. For example, let say MyClass is a subclass of LazyEnum. The first time we call MyClass(1) an object of type MyClass is created. Any subsequent call to MyClass(1) simply return the same object. Moreover, I want to put some validation on member creation, say we may only allow n to be a positive integer when calling MyClass(n).
This idea is inspired by Ethan Furman's reply to my previous question here and also a discussion on Udemy with Fred Baptiste, who is the instructor of the Python 3 Deep Dive series.
Before looking at the code, let me provide an example of how to use LazyEnum.
Example
from lazyenum import LazyEnum

class Product(LazyEnum):
    def _validate_identifier_value(product_id):
        # special method used by metaclass for validation
        return isinstance(product_id, int) and (1001 <= product_id <= 9999)

    COMPANY_NAME = 'Our Example Company'

    def __init__(self, product_id, product_title):
        # no need to store 'product_id' as instance attribute
        self.product_title = product_title

    def __repr__(self):
        return f'Product({self.product_id!r}, {self.product_title!r})'

Remark:

LazyEnum is created by a private metaclass _LazyEnumMeta.
The first non-self parameter of __init__ is automatically grabbed by the metaclass and cached, so we don't need to set it as an instance attribute. If we write self.product_id = product_id, it would raise an error when we try to initialize a new member. This parameter is called the identifier field and its value is called the identifier value, which uniquely identify each member.
The metaclass would look for a method named _validate_identifier_value and use it for validation. It can be defined as a static method or a class method, but if we define it as a class method, we would need to decorate it with @classmethod. Here we just define it as a static method.

Let us see some example outputs. First, we can initialize a member as usual and call it by its identifier value.
>>> prod1 = Product(1001, 'Our Nice First Product')
>>> Product(1001)
Product(1001, 'Our Nice First Product')
>>> prod1 is Product(1001)
True

We can get the identifier value by using .identifier_field or directly calling the instance attribute (.product_id in this case). The .identifier_field would give us a nametuple called Identifier, whose first entry is the attribute name and the second entry is the value.
>>> prod1.identifier_field
Identifier(field_name='product_id', value=1001)
>>> prod1.product_id
1001

Error would be raised if we attempt to create a new member with an existing identifier value. Of course, the same thing would happen if we use an invalid identifier value.
>>> Product(1001, 'This Is Still The First Product')
ValueError: Member with identifier value 1001 already exists. Cannont pass additional arguments ('This Is Still The First Product',) or {}.
>>> Product(1, 'Product With Invaild ID')
ValueError: Identifier field 'product_id' has invalid value 1.

In the regular Enum, you can set aliases to a member. Right now we didn't set any alias, but we can do so using dot notation and see all aliases of a member using .all_aliases. We can also simultaneously create a new member and set an alias to it.
>>> prod1.all_aliases
[]
>>> Product.product_one = prod1
>>> Product.first_product = Product.product_one
>>> prod1.all_aliases
['product_one', 'first_product']
>>>
>>> Product.product_two = Product(1002, 'The Amazing Second Product')
>>> Product.product_two
Product(1002, 'The Amazing Second Product')
>>> Product(1002).all_aliases
['product_two']

But be careful, we may accidentally overwrite other class attributes.
>>> Product.COMPANY_NAME
'Our Example Company'
>>> Product.COMPANY_NAME = prod1
>>> prod1.all_aliases
['product_one', 'first_product', 'COMPANY_NAME']
>>> Product.COMPANY_NAME
Product(1001, 'Our Nice First Product')
>>>
>>> Product.COMPANY_NAME = 'Our Example Company'
>>> prod1.all_aliases
['product_one', 'first_product']

We can change instance attributes that are not the identifier field. Attempting to change the identifier field would raise an error.
>>> prod1.product_title = 'First Product With New Name'
>>> prod1
Product(1001, 'First Product With New Name')
>>> prod1.product_id = 2001
AttributeError: can't set attribute

We can iterate over the class members.
>>> Product(1003, 'Even More Amazing Third Product')
Product(1003, 'Even More Amazing Third Product')
>>> for prod in Product: print(prod)
Product(1001, 'First Product With New Name')
Product(1002, 'The Amazing Second Product')
Product(1003, 'Even More Amazing Third Product')
>>> len(Product)
3

Finally, the class has properties .identifier_value_map and .alias_to_member_map, which help inspect all members. Note that we didn't set any alias to Product(1003).
>>> Product.identifier_value_map
mappingproxy({
    1001: Product(1001, 'First Product With New Name'),
    1002: Product(1002, 'The Amazing Second Product'),
    1003: Product(1003, 'Even More Amazing Third Product')
})
>>> Product.alias_to_member_map
mappingproxy(OrderedDict([
    ('product_one', Product(1001, 'First Product With New Name')),
    ('first_product', Product(1001, 'First Product With New Name')),
    ('product_two', Product(1002, 'The Amazing Second Product'))
]))

The Code
Here is the code.
# lazyenum.py
from collections import namedtuple, OrderedDict
from types import MappingProxyType

_Identifier = namedtuple('Identifier', 'field_name value')

def _get_identifier_value(self):
    # use this function to monkey patch the class
    id_map = type(self)._object_id_to_value_map
    return id_map[id(self)]

class _LazyEnumMeta(type):
    def __new__(mcls, name, bases, attrs):
        attrs['_object_id_to_value_map'] = {}
        attrs['_identifier_value_map'] = {}
        attrs['_alias_to_member_map'] = OrderedDict()
        cls = super().__new__(mcls, name, bases, attrs)

        # grab the first parameter name from the __init__ method
        # then inject it to the class as a read-only property
        id_name = cls.__init__.__code__.co_varnames[1]
        cls._identifier_field_name = id_name
        setattr(cls, id_name, property(_get_identifier_value))

        return cls

    def __call__(cls, value, *args, **kwargs):
        # rely on the class to provide the validation method
        if not cls._validate_identifier_value(value):
            raise ValueError(f'Identifier field {cls._identifier_field_name!r} '
                            f'has invalid value {value!r}.')

        # create a new memeber iff no existing member has the same identifier value
        if value not in cls._identifier_value_map:
            new_member = super().__call__(value, *args, **kwargs)
            cls._object_id_to_value_map[id(new_member)] = value
            cls._identifier_value_map[value] = new_member
        elif args or kwargs:
            raise ValueError(f'Member with identifier value {value!r} already exists. '
                            f'Cannont pass additional arguments {args} or {kwargs}.')

        return cls._identifier_value_map[value]

    def __contains__(cls, other):
        return other in cls._identifier_value_map.values()

    def __len__(cls):
        return len(cls._identifier_value_map)

    def __iter__(cls):
        yield from cls._identifier_value_map.values()

    def __setattr__(cls, attr_name, attr_value):
        if attr_name in cls._alias_to_member_map:
            del cls._alias_to_member_map[attr_name]

        # check if we are setting name to a class member
        if attr_value in cls:
            cls._alias_to_member_map[attr_name] = attr_value

        super().__setattr__(attr_name, attr_value)

    def __delattr__(cls, attr_name):
        if attr_name in cls._alias_to_member_map:
            del cls._alias_to_member_map[attr_name]

        super().__delattr__(attr_name)

    @property
    def identifier_value_map(cls):
        return MappingProxyType(cls._identifier_value_map)

    @property
    def alias_to_member_map(cls):
        return MappingProxyType(cls._alias_to_member_map)

class LazyEnum(metaclass=_LazyEnumMeta):
    # the first two methods serve as the defaults if a subclass didn't provide them
    # to avoid error when _LazyEnumMeta attempts to use those two methods
    def _validate_identifier_value(value):
        return True

    def __init__(self, identifier_value):
        pass

    @property
    def identifier_field(self):
        id_name = type(self)._identifier_field_name
        return _Identifier(id_name, getattr(self, id_name))

    @property
    def all_aliases(self):
        pairs = type(self)._alias_to_member_map.items()
        return [alias for alias, member in pairs if member is self]

Questions
1.
The above code doesn't work well with dataclasses. If we write
from lazyenum import LazyEnum
from dataclasses import dataclass

@dataclass
class Product(LazyEnum):
    def _validate_identifier_value(product_id):
        return isinstance(product_id, int) and (1001 <= product_id <= 9999)

    product_id : int
    product_title : str

then type the following in the console:
>>> prod1 = Product(1001, 'First Product')
>>> prod1.product_id = 2001
>>> Product(2001)
TypeError: __init__() missing 1 required positional argument: 'product_title'
>>> Product(1001)
Product(product_id=2001, product_title='First Product')

We can change the product_id but the member is still identified by the old value! How can I fix this?

Apart from the issue of dataclasses, is there any problem in the above code? Where can I make improvements?

A:

This right here is where I would start asking myself if this is a good idea or if there isn't a better way to achieve this:

The first non-self parameter of __init__ is automatically grabbed by
  the metaclass and cached, so we don't need to set it as an instance
  attribute. If we write self.product_id = product_id, it would raise an
  error when we try to initialize a new member.

This behavior is not obvious and it is not even properly documented, because your class does not have a docstring.
Honestly, I don't quite get your enum story, either. At face value you just have a class that you can inherit from to make your class a singleton class depending on the arguments. For this I might use something like this:
class UniqueInstances:
    """Makes sure that each instance exists only once.
    Subclasses must implement __hash__ and __eq__ for this to work.
    Note that new instances are being created,
    but get discarded if they already exist.
    """
    __instances = {}
    def __new__(cls, *args, **kwargs):
        self = super().__new__(cls)
        self.__init__(*args, **kwargs)
        return self.__instances.setdefault(self, self)

    def __hash__(self):
        raise NotImplementedError

    def __eq__(self, other):
        raise NotImplementedError

class Product(UniqueInstances):
    def __init__(self, product_id, name):
        self.product_id = product_id
        self.name = name

    def __hash__(self):
        return self.product_id

    def __eq__(self, other):
        return self.product_id == other.product_id

p1 = Product(1001, "Test")
p2 = Product(1001, "Foo")
print(p1 is p2, p1.name, p2.name)
# True Foo Foo

This is cheating a bit, because it does create a new instance, but it gets discarded if an equal instance already exists. If this still qualifies as lazy, I'm not sure.
It does however have the advantage that it is more obvious what happens, since you have to define __hash__ and __eq__ which is used to determine if an instance already exists.

A:

High-level

LazyEnum should be separate from the underlying datatype.
You should allow a similar interface like the following:
@dataclasses.dataclass
class Product:
    id: int
    name: str

class Products(metaclass=LazyEnumMeta, type=Product):
    pass

Products(1001, 'foo')

This can alleviate the following problem. If, however, you still run into this problem, it's because your using Products for something it shouldn't be used for.

But be careful, we may accidentally overwrite other class attributes.

You should allow the enum class to function similarly to how Python's does.
class Products(metaclass=LazyEnumMeta, type=Product):
    product_one = first_product = 1001
    product_two = 1002

By only using the ID we can allow the the Product to not be constructed yet, but still define the mapping.
You should re-decide where the following exception is handled.

Member with identifier value {value!r} already exists.

If you handle it on Products then you could theoretically allow people to create multiple Products with different values that aren't in the enum.
If you go Graipher's route then you're locking down Product when you may want to use it in two enums.
It boils down to, where do you want the singleton Products to be scoped?
I'm not a fan of having the __call__ function as a __getitem__.

Here's a proof of concept for the above suggestions.
import dataclasses
import inspect

class LazyEnumMeta(type):
    def __new__(mcls, name, bases, attrs, type):
        _attrs = {}
        for key in list(attrs.keys()):
            if not (key.startswith('__') and key.endswith('__')):
                _attrs[key] = attrs.pop(key)

        attrs['_type'] = type
        arguments = inspect.signature(type).parameters.values()
        attrs['_id'] = next(iter(arguments)).name
        attrs['_attrs'] = _attrs
        attrs['_items'] = {}
        return super().__new__(mcls, name, bases, attrs)

    def __call__(self, *args, **kwargs):
        id = args[0] if args else kwargs[self._id]
        if id in self._items:
            return self._items[id]
        self._items[id] = item = self._type(*args, **kwargs)
        return item

    def __getitem__(self, id):
        return self._items[id]

    def __getattr__(self, name):
        return self._items[self._attrs[name]]

@dataclasses.dataclass
class Product:
    id: int
    name: str

class Products(metaclass=LazyEnumMeta, type=Product):
    FIRST = 1001

print(Products(id=1001, name='foo'))
print(Products[1001])
print(Products.FIRST)

Granular

Many of your names are long and needlessly use Hungarian notation _object_id_to_value_map. This can just be _id_to_value or _by_ids.
You should notice that many of my names above are really short. type, id, attrs, items. You don't need long names, and when you do it's normally a good idea to refactor the code to prevent a god class.
I'd much prefer to use inspect than the low level cls.__init__.__code__.co_varnames[1].
Your hanging indents are not 'correct'. You should change:

raise ValueError(f'Identifier field {cls._identifier_field_name!r} '
                f'has invalid value {value!r}.')

To:
raise ValueError(f'Identifier field {cls._identifier_field_name!r} '
                 f'has invalid value {value!r}.')

Alternately you can change your style and use:
raise ValueError(
    f'Identifier field {cls._identifier_field_name!r} '
    f'has invalid value {value!r}.'
)

I don't really see any gain from using id(new_member). If anything it makes the code more annoying.
I don't think exposing identifier_value_map, alias_to_member_map, identifier_field or all_aliases publicly are good design choices.


Q:

What does php's CURLOPT_USERPWD do

I was wondering what CURLOPT_USERPWD is actually doing to the url, header or data of a request. Is it INSTEAD OF the Authorization: Basic <base64 of user:pass> or does it work along side this?
Is it modifying the url to this?:
username:password@someurl.com
I saw some code like this so I am wondering, as it seems if I request that url in a NodeJS equivalent request it is not working with just an Authorization header (I have a theory the server is broken and ignoring the Auth header and using the username:password in the url):
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $encodedAuth = base64_encode(self::$pfAdapterUser.":".self::$pfAdapterPasswd);

    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authentication : Basic ".$encodedAuth));
    curl_setopt($ch, CURLOPT_USERPWD, self::$pfAdapterUser.":".self::$pfAdapterPasswd);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);

Thanks

A:

Is it modifying the url to this?:
username:password@someurl.com

No, the url still the same. You can check with
curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

This
$encodedAuth = base64_encode(self::$pfAdapterUser.":".self::$pfAdapterPasswd);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Basic ".$encodedAuth));

And this
curl_setopt($ch, CURLOPT_USERPWD, self::$pfAdapterUser.":".self::$pfAdapterPasswd);

are doing the same thing so there's no need to use them together (although it won't break), use one and it will work fine.


Q:

HoltWinters Nested Seasons in R

I have a dataset of daily demand over the last 2 years. The data has weekly seasons and nested daily seasons. I converted the data into a time series using ts function with frequency=365. When using HoltWinters method now, he interprets every day as an own season, resulting in non-robust outcomes. How can I tell him to only include 59 seasons (52 weekly and 7 daily seasons)?

A:

First of all, weekly seasonality means that a pattern may repeats itself every week. Daily seasonality means that a pattern may repeat itself every day. To allow your model to contain daily seasonality you need a higher frequency time series than daily. I assume that with the '52 weekly and 7 daily seasons' you mean that you want to specify 52 seasonal factors for your annual seasonality and 7 seasonal factors (logically) for your weekly seasonality.
The frequency specifies the number of observations per cycle (season).
With daily data a weekly seasonality is introduced by:
ts(x, frequency = 7)

You might want to restrict yourself to use just that. (https://robjhyndman.com/hyndsight/dailydata/)
Instead of the ts object, you can use the msts (Multi-Seasonal Time Series) object as follows to specify weekly and annual seasonality.
msts(x, seasonal.periods = c(7, 365.25))

Or omit leap day observations and just use 365.
You can use bats or tbats:
y <- msts(x, seasonal.periods=c(7,365.25))
fit <- tbats(y)
fc <- forecast(fit)
plot(fc)

You should have a look at https://robjhyndman.com/hyndsight/dailydata/
Hope this helps.


Q:

Converting old project to ARC

The following code is a snippet from an older file that I'm trying to use in a newer project. Since ARC is now used, I'm having some trouble making it ARC friendly. I already got rid of all the autoreleases, but this one problem still remains. What do I replace NSMakeCollecatble with?
NSString *newString = NSMakeCollectable(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding([self stringEncoding])));

A:

This answer has already been answered here:
https://stackoverflow.com/a/15198145/1835155
NSString *newString = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding([self stringEncoding])));


Q:

Matlab manually finding histograms and pdfs of images

Image processing using Otsu's method and getting histogram and PDF for white/black pictures. Here's the code which I wrote but I couldn't get the PDF via the histogram.
I = imread('sample.jpg');
level = graythresh(I);
X = rgb2gray(I);
A = im2bw(X,level);
A2 = im2bw(X,58/255);
B = medfilt2(A2);
figure, imshow(I)
figure, imhist(X)
figure, imshow(A)
figure, imshow(A2)
figure, imshow(B)

A:

imhist only shows the histogram, not the PDF. If you're looking for the PDF of X, you can use:
histogram( X(:), 'Normalization', 'probability' );
axis tight

EDIT: Full code
I = imread('sample.jpg');
level = graythresh(I);
X = rgb2gray(I);
A = im2bw(X,level);
A2 = im2bw(X,58/255);
B = medfilt2(A2);
figure, imshow(I)
figure; histogram( X(:), 'Normalization', 'probability' );
axis tight;
figure, imshow(A)
figure, imshow(A2)
figure, imshow(B)


Q:

DevPartner Profiler Community Edition

I used to have DevPartner Profiler Community Edition installed on my machine, which was free to use indefinitely and was compatible with Visual Studio 2003.
After I have rebuild my machine and downloaded a newer version (version 8.1) of the software, it turns out it is actually a 45 day trial eventhough it is still called a Community Edition.
I have tried looking for an older version, but haven't been able to find it.
Could someone help me out please?

A:

Billy, Compuware retired the Community Edition profiler years ago and pulled it from any web sites. That profiler was used as a marketing tool. Folks were supposed to use the profiler then request an upgrade to the full DevPartner Studio suite. Because that didn't really pan out they yanked down the profiler. Under Micro Focus, you can now obtain the full suite but license just the profiler at a much lower price point than the full suite. I suggest you look at http://www.microfocus.com under MF Developer at the different offerings. Shameless plug: I work on the DevPartner team. We are releasing our 64-bit profiler editions in version 10.5 on February 4, 2011. Check out the download eval once its posted.


Q:

Make an image clickable to expand

I have a background image that I would like to expand when clicked. I have setup animations that will dim the background and prop the image to the center, but for some reason the image is not clickable.
I have tried to implement a simple print(tapped) and when I tap I dont see anything as well. I am wondering if I have to declare my image view as something else?
import Foundation
import UIKit

class JobViewController: UIViewController {

let imageView: UIImageView = {
    let iv = UIImageView(image: #imageLiteral(resourceName: "yo"))
    iv.contentMode = .scaleAspectFill
    iv.isUserInteractionEnabled = true
    iv.translatesAutoresizingMaskIntoConstraints = false
    iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleZoomTap)))
    return iv
}()

@objc func handleZoomTap(_ tapGesture: UITapGestureRecognizer) {
  print("tap tap")

}

override func viewDidLoad() {
    super.viewDidLoad()

     view.addSubview(imageView)
    imageView.fillSuperview()

}
}

When I tap the image, I expect that it should at least print "tap tap"
Is there something else that i am missing?

A:

Delete this line:
iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleZoomTap)))

And add this to your viewDidLoad:
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleZoomTap)))


Q:

AnyLogic 7: Excel access library (Apache POI) is not specified

AnyLogic 7: Excel access library (Apache POI) is not specified
I'm trying to use the AnyLogic ExcelFile class, but it appears that AnyLogic can't find the required Apache POI library:
Error during model startup:
Excel access library (Apache POI) is not specified (or is specified incorrectly) in the classpath
Caused by: org/apache/poi/openxml4j/exceptions/InvalidFormatException
Caused by: org.apache.poi.openxml4j.exceptions.InvalidFormatException
java.lang.RuntimeException: Excel access library (Apache POI) is not specified (or is specified incorrectly) in the classpath
    at com.xj.anylogic.engine.Engine.a(Unknown Source)
    at com.xj.anylogic.engine.Engine.start(Unknown Source)
    at com.xj.anylogic.engine.ExperimentSimulation.b(Unknown Source)
    at com.xj.anylogic.engine.ExperimentSimulation.run(Unknown Source)
    at generic_agent_based_model_with_births_and_deaths.Simulation.executeShapeControlAction(Simulation.java:107)
Caused by: java.lang.NoClassDefFoundError: org/apache/poi/openxml4j/exceptions/InvalidFormatException
    at generic_agent_based_model_with_births_and_deaths.ExcelDataSource.onStartup(ExcelDataSource.java:668)
    at generic_agent_based_model_with_births_and_deaths.ExcelDataSource.start(ExcelDataSource.java:652)
    at generic_agent_based_model_with_births_and_deaths.Main.start(Main.java:1046)
    ... 4 more
Caused by: java.lang.ClassNotFoundException: org.apache.poi.openxml4j.exceptions.InvalidFormatException
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    ... 7 more

How do I fix this?
Some notes:

I am working with a model initially developed by someone else. I am assuming the model was initially built for AnyLogic 6.9, but I am using AnyLogic 7.0.3.
I assume that AnyLogic is supposed to import the POI library automatically: any idea what it did wrong / what I did wrong to cause AnyLogic to fail?
To head off any confusion, ExcelDataSource is a wrapper class I've created to simplify ExcelFile for our use case.

Thanks in advance!

A:

AnyLogic uses Apache POI library for working with Excel spreadsheets. But it is disabled by default as unnecessary. You should drop Excel File element from Connectivity palette to be able to use Apache POI methods. Another way - add the library to model dependencies list (see Dependencies section of the model properties view).


Q:

How can I 'git clone' from another machine?

On one machine (IP address 192.168.1.2), I create a Git repository by
$ cd /home/hap/working
$ git init
$ (add some files)
$ git add .
$ git commit -m 'Initial commit'

And I have another machine on the same Wi-Fi network. How can I get clone from the other machine?

A:

You need to use a git+ssh URL to perform the Git cloning:
git clone git+ssh://hap@192.168.1.2/~/working

To break it down:

git+ssh tells Git that you want to use ssh to connect to the Git repository.
hap is your username (I assume based on the home directory in your question).
192.168.1.2 is the machine that you want to connect to
~/working is the path to your Git repository on the remote machine (so ~ is your home directory)

Some other things to note:

You need to have a ssh server enabled on the machine with the Git repository
You'll need to know the password for the user hap


Q:

Transform list to dataframe efficiently

I have a list of images and I want to get all the pixels of each image in one DataFrame column and the number of the image into another column. I am trying to do it with
plotDF = DataFrame()
plotData = [np.array([[1,2,1],[1,1,2],[4,2,1]]), np.array([[1,2,2,1],[1,3,1,3]]), np.array([[1,1,2,3],[4,1,1,1],[1,1,1,4]])]
plotData = [image.flatten() for image in plotData]
for n, pD in zip(range(len(plotData)), plotData):
    for pixel in pD:
        plotDF = plotDF.append(DataFrame.from_records([{'n': n, 'pixel': pixel}]))
plotDF = plotDF.reset_index(drop=True)

but this seems really inefficient.
How can I do this more efficient, possibly with https://github.com/kieferk/dfply?

A:

I think you can use numpy.repeat for repeat values by legths by str.len and flat values of nested lists by chain.
from  itertools import chain

s = pd.Series(plotData)
df2 = pd.DataFrame({
        "n": np.repeat(s.index + 1, s.str.len()),
        "pixel": list(chain.from_iterable(s))})

print (df2)
    n  pixel
0   1      1
1   1      2
2   1      1
3   1      1
4   1      1
5   1      2
6   1      4
7   1      2
8   1      1
9   2      1
10  2      2
11  2      2
12  2      1
13  2      1
14  2      3
15  2      1
16  2      3
17  3      1
18  3      1
19  3      2
20  3      3
21  3      4
22  3      1
23  3      1
24  3      1
25  3      1
26  3      1
27  3      1
28  3      4


Q:

HTML multiple Tables

Please help me !
I have two divs, in each div is a table. How can I change the content of first table by clicking in the second table.
The first table is on the left side, and the second table is on the right side. "Image 1"

I want to change the content on the left table by clicking on the right table on the "Table 1" , "Table 2"
One more thing, how can I keep the both tables in line when the content of the first table is to long. when I add more data in the first table the tables are changing their position like this

A:

You can use javascript for changing the content of the left table when you click on the right table.
It is the mistake of all newbies in HTML. If you put the example content in the cell that is endless string without spaces there is no way to make the row shorter. If you put there real data with words separated by spaces the browser splits rows automatically. For being sure you can limit the width of the left table by using css.


Q:

Modus vivendi, modus praevalentis

As you may know, when two states fail to come to permanent treaty terms, they may agree for the time being to a modus vivendi, an interim memoradum of indefinite term specifying usually mutually unsatisfactory but nevertheless tolerable conditions of peaceful continuance, pending a final agreement.  The phrase modus vivendi is of course Latin, literally translated (if I understand correctly), as "way (or manner) of living."
What I need today is a slight variation on the phrase, a variation that implies that one state has outwitted the other in negotiating the modus vivendi, such that the real effect of the modus is to deliver a sly, unearned advantage to  the one  at the other's expense, with the added insult that the modus is not even a permanent treaty—that once the advantage has been pocketed, a permanent treaty will still remain to be negotiated.
Of course, this is a lot to load into a two-word Latin phrase!  I hardly expect two words to convey the whole meaning, but I want a fresh phrase that nonetheless captures the spirit of modus vivendi, with the indicated twist.
The best with which I have yet been able to come up is modus praevalentis, in which valere is (I believe) "to be strong" and, by extension, praevalere is "to take the upper hand."
Two questions, please:

Can you think of a better Latin phrase to serve the indicated purpose?
Did I decline my Latin right, or should it have been modus praevalendi or such?

A:

While I agree with Kris above (you need a very sound understanding of the noun declensions and verb conjugations to create your own Latin phrases), I think it is fine to do so, though it is uncommon and somewhat misleading, connoting the wisdom of antiquity where there is none.
Many, many Latin phrases were 'coined' well after Latin was no longer spoken anywhere but in the Vatican. Those come to us mostly through Law, eg. "in loco parentis", and a few through Medicine.
The English translation of "PRAEVALERE" is "to prevail with greater skill and knowledge". I'm not sure that's exactly what you want, and I sure cant conjugate it well enough to help you there, but good luck.


Q:

What is the difference between delete a pointer and set the pointer as NULL?

Suppose I have a pointer to MyClass:
MyClass *myPointer = new MyClass();

What is the difference between delete myPointer; and myPointer = NULL;?
Thanks

A:

delete myPointer de-allocates memory, but leaves value of myPointer variable, that it is pointing to some garbage address.
myPointer = NULL only sets value of myPointer to null-pointer, possibly leaking memory, if you don't delete other pointer, which points to same address as myPointer
In ideal world you should use both those strings, like this:
delete myPointer; // free memory
myPointer = nullptr; // setting value to zero, signalizing, that this is empty pointer

But overall, use std::unique_ptr, which is modern approach to memory management.


Q:

How to use gwtbootstrap3 calendar with UiBinder

Can we use gwtbootstrap3 fullcalendar mentioned at http://gwtbootstrap3.github.io/gwtbootstrap3-demo/#fullcalendar with UiBinder.
I am trying to use it with UiBinder and nothing is appearing on that page.
code to my UiBinder class
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
    xmlns:g="urn:import:com.google.gwt.user.client.ui"
    xmlns:b="urn:import:org.gwtbootstrap3.client.ui.gwt">
    <g:HTMLPanel ui:field="calendarContainer">
    </g:HTMLPanel>
</ui:UiBinder>

code to the corresponding view class
public class EventView extends ReverseCompositeView<IEventView.IEventPresenter> implements IEventView {

    private static EventViewUiBinder uiBinder = GWT.create( EventViewUiBinder.class );

    interface EventViewUiBinder extends UiBinder<Widget, EventView> {
    }

    @UiField
    HTMLPanel calendarContainer;

    @Override
    public void createView() {
        //don't create the view before to take advantage of the lazy loading mechanism
        initializeCalendar();
        initWidget( uiBinder.createAndBindUi( this ) );
    }

    private void initializeCalendar() {
        final FullCalendar fc = new FullCalendar("event-calendar", ViewOption.month, true);
        fc.addLoadHandler(new LoadHandler() {
            @Override
            public void onLoad(LoadEvent loadEvent) {
                addEvents();
            }

            private void addEvents() {
                for (int i = 0; i < 15; i++) {
                    Event calEvent = new Event("id "+ i, "this is event "+i);
                    int day = Random.nextInt(10);
                    Date start = new Date();
                    CalendarUtil.addDaysToDate(start, -1 * day);
                    calEvent.setStart(start);
                    if(i%3 ==0){
                        calEvent.setAllDay(true);
                    }else{
                        Date d = new Date(start.getTime());
                        d.setHours(d.getHours()+1);
                        calEvent.setEnd(d);
                    }
                    fc.addEvent(calEvent);
                }
            }

        });

        calendarContainer.add(fc);
    }

}

and I am using mvp4g framework.

A:

initializeCalendar();
initWidget( uiBinder.createAndBindUi( this ) );

You should first init the widget and then initialize the calendar. This is because you are adding your FullCalendar to the calendarContainer HTMLPanel in initializeCalendar. And before the call to initWidget, calendarContainer is null.
I think you can go a step further and do it like this:
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
    xmlns:g="urn:import:com.google.gwt.user.client.ui"
    xmlns:b="urn:import:org.gwtbootstrap3.client.ui.gwt"
    xmlns:f="urn:import:org.gwtbootstrap3.extras.fullcalendar">
    <g:HTMLPanel>
        <f:FullCalendar ui:field="fullCalendar" />
    </g:HTMLPanel>
</ui:UiBinder>

And then in your EventView:
@UiField(provided = true) FullCalendar fullCalendar;

@UiField(provided = true) means it's up to you to initialize this widget before calling initWidget. So, in this case, the order:
initializeCalendar();
initWidget( uiBinder.createAndBindUi( this ) );

is OK. Additionally, you don't have to add the FullCalendar to any panel anymore - it's already added, you just have to initialize it.


Q:

How does the aspect ratio of a wing impact its lift?

The wing lift formula shows that lift of a wing is proportional to its area.
$
L = {\dfrac 1 2 \times \rho V^2 \color{magenta}S C_L}
{\small
\begin{align}
&{} &&\text{where:} &&L = \text{lift,} &&\rho = \text{density of air,} \\
&{} &&{} &&V = \text{velocity,} &&\color{magenta}S = \text{wing area,}\\
&{} &&{} &&{}&&C_L = \text{coefficient of lift.}
\end{align}}
$
So why are most conventional wings shaped the same (swept back rectangles)?
Imagine a conventional airplane but with the wings shaped as 2 thin long rectangles attached to a fuselage from the cockpit until the tail with the same area as the original wing.
With all other things (like angle of attack, etc) being equal will the same lift be generated as the original wing?

A:

"The wing lift formula shows that lift of a wing is proportional to its area".
That's absolutely true. However a wing generates both lift and drag. Drag is of two natures: Parasitic drag and lift-induced drag. The sum of all drag is the total drag:

Source: Wikipedia
Induced drag decreases with speed, and has its origin in wing tip vortices. Vortices actually increase the velocity of the downwash, and changes the effective angle of attack. Which in turn changes the direction of the aerodynamic force, creating a force opposing to the direction of flight:

Induced drag, source: Wikipedia
Induced drag being due to tip vortices, if we can make vortices less efficient, then we also reduce induced drag. The way to do that is to have long wings, so the the downwash from the vortices affects only a part of the wing:

Tip vortices, source: Wikipedia
Research demonstrated that the induced drag is dependent on the wing aspect ratio, not only on the wing span. This can be understood easily: The quantity of air in a tip vortex is larger when the chord is large.
So the answer to your question is: Yes lift is proportional to the wing area, but the lift/drag ratio is proportional to the wing aspect ratio. That's why longer wings are preferred, they minimize energy lost in fighting drag.

"Why are most conventional wings shaped the same (swept back rectangles)?"
Longer wings are better for fuel efficiency, but we have other problems in the designer queue, and some can be solved by selecting the wing planform, e.g.:

We want to prevent the stall to be abrupt (at the expense of creating less lift though):

We want to delay the creation of a local supersonic flow in supercritical wings used in commercial airliners. When flying at M 0.8, airflow is accelerated to produce lift, some areas of the wing reach supersonic speed (Mach > 1). The associated shock wave creates an additional drag. By sweeping the wing we add a spanwise component to the airflow which decreases the chordwise velocity, so the shock wave appears only to a higher aircraft airspeed:

On the other hand, the sweptback wing tends to stall at the tip first, which is not good at all, as when a stall appears we need ailerons to prevent it from worsening, and ailerons are located at the tips to increase their effectiveness. So swept wings are also twisted so that the tip angle of attack is smaller than the root one, forcing the stall to start at wing root.

Wings planforms are multiple, each type of wing, or sometimes subcomponent, can improve a particular issue (possibly creating another that will be less important for the designer). See this very interesting article on Wikipedia: Wing configuration

A:

A higher aspect ratio (given the same wing area) means more wing span and less lift-dependent drag. At the same angle of attack, higher aspect ratio also means more lift (within limits).
Lift is produced by deflecting the oncoming stream of air downwards. The more air can be affected, the more efficient lift production becomes. Maybe you want to read a few answers around here if you want to learn more.
What you describe is a slender body wing. Most of the deflecting is done by the first few percent of this wing's chord, and the remainder will not be able to increase lift more, working on the already deflected air. Consequently, the same area of wing will create less lift force, at least in subsonic flow. Take the XB-70, for example: Its maximum wing loading (mass divided by area) was 420 kg/m². The swing-wing B-1, which could stretch its wings out for slow speed flight, has a maximum wing loading of 1190 kg/m², however, the calculation method of its wing area does not include the large delta section ahead of the main wing. Still, a sizeable difference remains and shows that the same wing area can create more lift when stretched out.

A:

The "wing lift formula" that you quoted is a simple approximation and is not
used for the detailed design of wings.
Practical reasons why conventional wings have the shape they do depend on
many design considerations, including the mission of the aircraft. The
answers you have received address some of those issues.
Be aware though, that there are many misconceptions in wing design.
One common misconception is that:
"Induced drag being due to tip vortices, if we can make vortices less efficient, then we also reduce induced drag."
That is a great over-simplification. Induced drag depends on the shape of the entire wing, not just the aspect ratio and the tip vortices.
Former Boeing Technical Fellow Doug Maclean discusses this misconception in
particular, and many others in his book:
Understanding Aerodynamics - Arguing from the Real Physics.
You might get a lot out Maclean's talk:
Common Misconceptions in Aerodynamics


Q:

Passing Structures between Managed and Unmanaged Code

I call c++/cli method from c# in this method:
        bool SetProperty(Element element, Node referencePoint, List<Materializer> materializers, List<ulong> properties)
    {

        // Loop over STLs
        for (int i = 0; i < materializers.Count; i++)
        {
            Materializer materializer = materializers[i];
            PentalTreeNode pentalTreeRoot = pentalTreeDatasets[i].top;

            if (materializer.IsPointInside(referencePoint.X, referencePoint.Y, referencePoint.Z, pentalTreeRoot))
            {
                element.PropertyId = properties[i];
                return true;
            };

        }

        return false;
    }

C++/cli method is this:
bool IsPointInside(double x, double y, double z, PentalTreeNode ^root)
    {
        int intersectionCount = 0;

        Math3d::M3d rayPoints[2], intersectionPoint;

        rayPoints[0].set(x,y,z);
        rayPoints[1].set(x,y,1.0e6);

        if(_box->IsContainingPoint(x,y,z))
        {
            intersectionCount=CountIntersects(x,y,z,root);
            return (intersectionCount%2!=0);

        }

    }

What is wrong, because c++/cli method doesn't return always the same result?
How to pin or marshal?
Method in c++/cli(Maybe this not ok?):
int CountIntersects(double x, double y, double z, PentalTreeNode ^root)
    {

        Math3d::M3d rayPoints[2], intersectionPoint;

        rayPoints[0].set(x,y,z);
        rayPoints[1].set(x,y,1.0e6);

        if(!root)
            return 0;
        else
        {
            int special = CountIntersects(x,y,z,root->special);
            if (x <= root->xMax && x >= root->xMin && y <= root->yMax && y >= root->yMin)
            {

                if( _stlMesh->IsRayIntersectsPoly(root->index, rayPoints, intersectionPoint))
                {
                    return (1 + special);
                }
                else
                    return special;
            }
            else
            {
             if (y>root->yMax)
              {
                    return (CountIntersects(x,y,z,root->top)+special);
              }
              else if(y<root->yMin)
                    {
                        return (CountIntersects(x,y,z,root->bottom)+special);
                    }
                    else if(x<root->xMin)
                            {
                                return (CountIntersects(x,y,z,root->left)+special);
                            }
                            else if(x>root->xMax)
                            {
                                return (CountIntersects(x,y,z,root->right)+special);
                            }
                            else
                                return special;
            }

        }

    }

A:

if( _stlMesh->IsRayIntersectsPoly(root->index, rayPoints, intersectionPoint))

There's one possible flaw in this particular statement, you've never initialized intersectionPoint.  C++ lets you get away with this, it doesn't have anything similar to C#'s definite assignment rules.  It isn't 100% clear whether that's the real problem, the variable might be passed by reference.
In the Debug build, such an uninitialized variable will have a predictable value.  Something you can easily see in the debugger when you switch it to hexadecimal display mode.  Fields in this struct or class will contain the value 0xcccccccc, a value that's apt to generate nonsensical results or crash your code with an access violation.  In the Release build, the /RTC option isn't turned on and you'll get entirely random values in the variable.
Which corresponds very well with the description of your problem, so high odds that this is indeed the problem.  Be sure to use the debugger to find problems like this, you can easily see the value of local variables with the Autos debugger window as you single-step through the code.


Q:

I like to order my .tex documents visually by inserting blank lines. How to tell Latex to not put a new line there, but only with \\?

When editing my documents in Texstudio I like to visually have some parts separated. Usually I would leave some blank lines in the .tex file. But Latex translates this into a linebreak/new line.
Is there a possibility to stop it from doing that and only have linebreaks when putting a \\ ?

A:

You can't: blank lines are used by TeX-the-program to indicate a new paragraph (the basic unit for text formatting), and you should use \\ exceptionally (it is used for multiline equations environments, tabulars, &c.).
To order visually your source-code, why don't you insert lines containing only the comment sign %?


Q:

SQL SERVER , error in my query

I need to know where is the problem in query, and how can I solve this?
SQL Query :
SELECT
    P.NameAr, P.NameEn,
    Sum(p.OrderQty) AS SumQty ,
    Sum(p.OrderQty * P.NewPrice) AS SumQtyPrice ,
    ROW_NUMBER() OVER(ORDER BY D.ProductID ASC) AS Number,
    'Soon' AS ColSoon
FROM OrderMasters M
INNER JOIN OrderDetails D ON D.OrderMasterID = M.OrderMasterID
INNER JOIN Products P ON P.ProductID = D.ProductID
INNER JOIN Categories C ON C.CategoryID = P.CategoryID

GROUP BY P.NameAr, P.NameEn
Order By D.OrderDetailsID

Error Msg :
Msg 8120, Level 16, State 1, Line 7

Column 'OrderDetails.ProductID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

When I remove line consisting @RowNumber code execute with no problem, but I need that in query.

A:

You can't apply order by field which doesn't belongs to group by;
So, you should change it your order by clauses
SELECT
    P.NameAr, P.NameEn,
    Sum(p.OrderQty) AS SumQty ,
    Sum(p.OrderQty * P.NewPrice) AS SumQtyPrice ,
    ROW_NUMBER() OVER(ORDER BY P.NameAr ASC) AS Number,
    'Soon' AS ColSoon
FROM OrderMasters M
INNER JOIN OrderDetails D ON D.OrderMasterID = M.OrderMasterID
INNER JOIN Products P ON P.ProductID = D.ProductID
INNER JOIN Categories C ON C.CategoryID = P.CategoryID

GROUP BY P.NameAr, P.NameEn
Order By P.NameAr

I put the P.NameAr as order field to provide example.


Q:

How to move the cursor between textboxes using arrow keys?

I have several TextBoxes and I want the cursor to move from one TextBox to another using arrow keys.
How can I do that?
It looks like this, also the tap moves vertically which is weird.
Thanks.

A:

You can override the form's ProcessCmdKey method, and handle the key press and focusing on text boxes in it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TextBoxes
{
    public partial class Form1 : Form
    {
        List<TextBox[]> _textBoxes;
        public Form1()
        {
            InitializeComponent();

            //Getting a 2 dimentional structure to hold textboxes
            this._textBoxes= new List<TextBox[]>();

            TextBox[] row1 = new TextBox[4];
            row1[0] = textBox1;
            row1[1] = textBox2;
            row1[2] = textBox3;
            row1[3] = textBox4;

            TextBox[] row2 = new TextBox[4];
            row2[0] = textBox5;
            row2[1] = textBox6;
            row2[2] = textBox7;
            row2[3] = textBox8;

            TextBox[] row3 = new TextBox[4];
            row3[0] = textBox9;
            row3[1] = textBox10;
            row3[2] = textBox11;
            row3[3] = textBox12;

            TextBox[] row4 = new TextBox[4];
            row4[0] = textBox13;
            row4[1] = textBox14;
            row4[2] = textBox15;
            row4[3] = textBox16;

            this._textBoxes.Add(row1);
            this._textBoxes.Add(row2);
            this._textBoxes.Add(row3);
            this._textBoxes.Add(row4);
        }

         /// <summary>
         /// Processes a command key.
         /// </summary>
         /// <param name="msg">A <see cref="T:System.Windows.Forms.Message"/>, passed by reference, that represents the Win32 message to process.</param>
         /// <param name="keyData">One of the <see cref="T:System.Windows.Forms.Keys"/> values that represents the key to process.</param>
         /// <returns>
         /// true if the keystroke was processed and consumed by the control; otherwise, false to allow further processing.
         /// </returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            //A key was pressed!
            Control activeCtrl = this.ActiveControl;
            TextBox txb = activeCtrl as TextBox;
            //Handle it only if it was sent when a textbox was focused
            if (txb != null)
            {
                int row;
                int column;
                //find out which text box is currently active
                this.GetTextBoxIndexes(txb, out row, out column);

                //change indexes according to key stroke
                if (keyData == Keys.Up)
                {
                    row--;
                }
                else if (keyData == Keys.Down)
                {
                    row++;
                }
                else if (keyData == Keys.Left)
                {
                    column--;
                }
                else if (keyData == Keys.Right)
                {
                    column++;
                }
                //Make sure we are not in negative / out of ranfe index
                row = Math.Abs(row + 4) % 4;
                column = Math.Abs(column + 4) % 4;

                //focus requested text box
                TextBox slected = this._textBoxes[row][column];
                slected.Focus();

            }
            //don't forget not to break the chain...
            return base.ProcessCmdKey(ref msg, keyData);
        }

        /// <summary>
        /// Gets the text box indexes.
        /// </summary>
        /// <param name="txb">The texbox.</param>
        /// <param name="row">The out row index.</param>
        /// <param name="column">The out column index.</param>
        private void GetTextBoxIndexes(TextBox txb, out int row, out int column)
        {
            row = -1;
            column = -1;
            for (int rowIdx = 0; rowIdx < this._textBoxes.Count; rowIdx++)
            {
                TextBox[] currRow = this._textBoxes[rowIdx];
                for (int colIdx = 0; colIdx < currRow.Length; colIdx++)
                {
                    TextBox currTextBox = this._textBoxes[rowIdx][colIdx];
                    if (currTextBox.Equals(txb))
                    {
                        row = rowIdx;
                        column = colIdx;
                        return;
                    }
                }
            }
        }
    }
}

A:

The following solution works if there is some text in the text boxes.
First create a KeyDown event handler:
private void textBoxLeft_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode.Equals(Keys.Right))
    {
        e.Handled = true;
        //SendKeys.Send("{TAB}");
        textBoxRight.Focus();
    }
}

private void textBoxRight_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode.Equals(Keys.Left))
    {
        e.Handled = true;
        //SendKeys.Send("+{TAB}");
        textBoxLeft.Focus();
    }
}


Q:

How many records does SNSEvent Object's getRecords() return?

How many records will be returned and how does it actually work?
public String handleRequest(SNSEvent snsEvent, Context context) {
        List<SNSRecord> records = snsEvent.getRecords();
        System.out.println("Size "+ records.size());
        return "success";
}

A:

Read the docs:

Q: Will a notification contain more than one message?
No, all notification messages will contain a single published message.


Q:

Auto fill not working

I am working on my code and I have this to filter rows and insert a formula in the first filter row. with that formula I want it to fill down, but it only insert the formula in the first filtered row and doesn't fill down.
Sub Cal()
dim LastRow as long
With Worksheets("Data")
.Range("$A$1:$AI$80000").AutoFilter Field:=1, Criteria1:= _
    "Actual"
.Range("$A$1:$AI$80000").AutoFilter Field:=2, Criteria1:="2018"
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

.AutoFilter.Range.Offset(2).SpecialCells(xlCellTypeVisible).Cells(1, 35).Select 'SELECTS THE FIRST cell in A after deleting
ActiveCell.FormulaR1C1 = "=SUM(RC[-12]:RC[-1])"
.AutoFilter.Range.Offset(2).SpecialCells(xlCellTypeVisible).Cells(1, 35).Select
Selection.FillDown
End With
End Sub

A:

How about something like below, instead of .FillDown, specify the range for the last column of visible data, and offset to the next column to enter the formula in there:
Sub Cal()
Dim LastRow As Long
    With Worksheets("Data")
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        .Range("$A$1:$AI$" & LastRow).AutoFilter Field:=1, Criteria1:="Actual"
        .Range("$A$1:$AI$" & LastRow).AutoFilter Field:=2, Criteria1:="2018"
        'filter according to values specified
        Set fltrdrng = .Range("$AI$2:$AI$" & LastRow).SpecialCells(xlCellTypeVisible)
        'set the range of visible data on last column with data on your data-set
        fltrdrng.Offset(0, 1).FormulaR1C1 = "=SUM(RC[-12]:RC[-1])"
        'add the formula to the adjacent column by offsetting
    End With
End Sub


Q:

Selecting static ROI

I was following this tutorial
https://www.pyimagesearch.com/2018/07/30/opencv-object-tracking/
and you choose the ROI by pausing the video with S and then making a window on the object you want to track
What I need help in is::

I want to choose the object without pausing the video nor selecting a window I mean the selection window is static and I just click left click to track
every time I click right click on another object it deletes the previous one and track the new object
control the selection window size by the mouse wheel|
here is the code I'm using now

# import the necessary packages
from imutils.video import VideoStream
from imutils.video import FPS
import argparse
import imutils
import time
import cv2
import serial

arduino=serial.Serial('com51', 115200)
# Serial write section

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", type=str,
 help="path to input video file")
ap.add_argument("-t", "--tracker", type=str, default="kcf",
 help="OpenCV object tracker type")
args = vars(ap.parse_args())
# extract the OpenCV version info
(major, minor) = cv2.__version__.split(".")[:2]

# if we are using OpenCV 3.2 OR BEFORE, we can use a special factory
# function to create our object tracker
if int(major) == 3 and int(minor) < 3:
 tracker = cv2.Tracker_create(args["tracker"].upper())

# otherwise, for OpenCV 3.3 OR NEWER, we need to explicity call the
# approrpiate object tracker constructor:
else:
 # initialize a dictionary that maps strings to their corresponding
 # OpenCV object tracker implementations
 OPENCV_OBJECT_TRACKERS = {
  "csrt": cv2.TrackerCSRT_create,
  "kcf": cv2.TrackerKCF_create,
  "boosting": cv2.TrackerBoosting_create,
  "mil": cv2.TrackerMIL_create,
  "tld": cv2.TrackerTLD_create,
  "medianflow": cv2.TrackerMedianFlow_create,
  "mosse": cv2.TrackerMOSSE_create
 }

 # grab the appropriate object tracker using our dictionary of
 # OpenCV object tracker objects
 tracker = OPENCV_OBJECT_TRACKERS[args["tracker"]]()

# initialize the bounding box coordinates of the object we are going
# to track
initBB = None
# if a video path was not supplied, grab the reference to the web cam
if not args.get("video", False):
 print("[INFO] starting video stream...")
 vs = VideoStream(src=0).start()
 time.sleep(1.0)

# otherwise, grab a reference to the video file
else:
 vs = cv2.VideoCapture(args["video"])

 #if vs.isOpened():
    # get vs property
#width2 = vs.get(3)
#height2 = vs.get(4)

# initialize the FPS throughput estimator
fps = None
# loop over frames from the video stream
while True:
 # grab the current frame, then handle if we are using a
 # VideoStream or VideoCapture object
 frame = vs.read()
 frame = frame[1] if args.get("video", False) else frame

 # check to see if we have reached the end of the stream
 if frame is None:
  break

 # resize the frame (so we can process it faster) and grab the
 # frame dimensions
 #frame = imutils.resize(frame, width=1280)
 (H, W) = frame.shape[:2]
 # check to see if we are currently tracking an object
 if initBB is not None:
  # grab the new bounding box coordinates of the object
  (success, box) = tracker.update(frame)

  # check to see if the tracking was a success
  if success:
   (x, y, w, h) = [int(v) for v in box]
   cv2.rectangle(frame, (x, y), (x + w, y + h),
    (0, 255, 0), 2)
  # update the FPS counter
  fps.update()
  fps.stop()
  #fixing the x,y tracker box center
  x2=int(x+w/2)
  y2=int(y+h/2)
  #the offsets for the x,y tracking from the center
  sox = str(x2 - (W/2))
  soy = str((H/2) - y2)
  #sending the offsets to arduino
  arduino.write('x'.encode())
  arduino.write(sox.encode())
  #print ("offset X value sent: ")
  #print (sox)
  #time.sleep(0.01)
  arduino.write('y'.encode())
  arduino.write(soy.encode())
  #print ("offset Y value sent : ")
  #print (soy)
  #time.sleep(0.01)
  cv2.line(frame, (int(W/2), int(H/2)), (x2, y2), (0, 255, 0), 1)
  cv2.line(frame, (int(W), int(H/2)), (0, int(H/2)), (0, 0, 0), 2)
  cv2.line(frame, (int(W/2), int(H)), (int(W/2), 0), (0, 0, 0), 2)
  #cv2.line(frame, (320, 240), (x2, y2), (0, 255, 0), 1)

  # initialize the set of information we'll be displaying on
  # the frame
  info = [

   #("Tracker", args["tracker"]),
   #("X = ",str(x)),
   #("Y = ",str(y)),
   ("offset X = ",sox),
   ("offset y = ",soy),
   #("width = ",W),
   #("height = ",H),
   ("FPS", "{:.2f}".format(fps.fps())),

  ]

  # loop over the info tuples and draw them on our frame
  for (i, (k, v)) in enumerate(info):
   text = "{}: {}".format(k, v)
   cv2.putText(frame, text, (10, H - ((i * 20) + 20)),
    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)

# show the output frame
 cv2.imshow("Frame", frame)
 key = cv2.waitKey(1) & 0xFF

 # if the 's' key is selected, we are going to "select" a bounding
 # box to track

 if key == ord("s"):
  # select the bounding box of the object we want to track (make
  # sure you press ENTER or SPACE after selecting the ROI)
  initBB = cv2.selectROI("Frame", frame, fromCenter=False,
   showCrosshair=True)

  # start OpenCV object tracker using the supplied bounding box
  # coordinates, then start the FPS throughput estimator as well
  tracker.init(frame, initBB)
  fps = FPS().start()

 # if the `q` key was pressed, break from the loop
 elif key == ord("q"):
  break
# if we are using a webcam, release the pointer
if not args.get("video", False):
 vs.stop()

# otherwise, release the file pointer
else:
 vs.release()

# close all windows
cv2.destroyAllWindows()

A:

You will need to make a few changes to your code. First add this call-back function at the top of your code to inform openCV what to do when you click.
mouse_click = False
tracker_location = (0,0)
def click_track(event, x, y, flags, param):
    global mouse_click, tracker_location
    # if the left mouse button was clicked, change flag
    # Click is sensed as a button up
    if event == cv2.EVENT_LBUTTONUP:
        mouse_click = True
        tracker_location = (x,y)

Then before you start the while loop add this to start your display window with the ability to sense mouse click.
# Create a window for click detection
cv2.namedWindow("Frame")
cv2.setMouseCallback("Frame", click_track)

Finally at the spot where select ROI was once was, replace it with a static ROI that only operates when the mouse click flag is true.
if mouse_click == True:
    # select the bounding box of the object we want to track (make
    # sure you press ENTER or SPACE after selecting the ROI)
    h , w, ch = frame.shape

    # initial ROI size
    ROI_size_x = 0.1 * w
    ROI_size_y = 0.1 * h

    # Adjust the size when object is near image border
    if( tracker_location[0] + ROI_size_x >= w):
        ROI_size_x = w - tracker_location[0]
    if( tracker_location[1] + ROI_size_y >= h):
        ROI_size_y = h - tracker_location[1]
    if( tracker_location[0] - ROI_size_x < 0):
        tracker_location[0] = 0
    if( tracker_location[1] - ROI_size_y < 0):
        tracker_location[1] = 0

    initBB = ( tracker_location[0] - ROI_size_x, tracker_location[1] - ROI_size_y, ROI_size_x * 2,ROI_size_y * 2)

You can change the size of the static ROI with any value you like. Currently its set as 20% of the image size at the center.
Here is the entire code
# import the necessary packages
from imutils.video import VideoStream
from imutils.video import FPS
import argparse
import imutils
import time
import cv2
import serial

mouse_click = False
tracker_location = (0,0)
def click_track(event, x, y, flags, param):
    global mouse_click, tracker_location

    tracker_location = (x,y)
    # if the left mouse button was clicked, change flag
    # Click is sensed as a button up
    if event == cv2.EVENT_LBUTTONUP:
        mouse_click = True

arduino=serial.Serial('com51', 115200)
# Serial write section

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", type=str,
    help="path to input video file")
ap.add_argument("-t", "--tracker", type=str, default="kcf",
    help="OpenCV object tracker type")
args = vars(ap.parse_args())
# extract the OpenCV version info
(major, minor) = cv2.__version__.split(".")[:2]

# if we are using OpenCV 3.2 OR BEFORE, we can use a special factory
# function to create our object tracker
if int(major) == 3 and int(minor) < 3:
    tracker = cv2.Tracker_create(args["tracker"].upper())

# otherwise, for OpenCV 3.3 OR NEWER, we need to explicity call the
# approrpiate object tracker constructor:
else:
    # initialize a dictionary that maps strings to their corresponding
    # OpenCV object tracker implementations
    OPENCV_OBJECT_TRACKERS = {
        "csrt": cv2.TrackerCSRT_create,
        "kcf": cv2.TrackerKCF_create,
        "boosting": cv2.TrackerBoosting_create,
        "mil": cv2.TrackerMIL_create,
        "tld": cv2.TrackerTLD_create,
        "medianflow": cv2.TrackerMedianFlow_create,
        "mosse": cv2.TrackerMOSSE_create
    }

    # grab the appropriate object tracker using our dictionary of
    # OpenCV object tracker objects
    tracker = OPENCV_OBJECT_TRACKERS[args["tracker"]]()

# Create a window for click detection
cv2.namedWindow("Frame")
cv2.setMouseCallback("Frame", click_track)

# initialize the bounding box coordinates of the object we are going
# to track
initBB = None
# if a video path was not supplied, grab the reference to the web cam
if not args.get("video", False):
    print("[INFO] starting video stream...")
    vs = VideoStream(src=0).start()
    time.sleep(1.0)

# otherwise, grab a reference to the video file
else:
    vs = cv2.VideoCapture(args["video"])

 #if vs.isOpened():
    # get vs property
#width2 = vs.get(3)
#height2 = vs.get(4)

# initialize the FPS throughput estimator
fps = None
# loop over frames from the video stream
while True:
    # grab the current frame, then handle if we are using a
    # VideoStream or VideoCapture object
    frame = vs.read()
    frame = frame[1] if args.get("video", False) else frame

    # check to see if we have reached the end of the stream
    if frame is None:
        break

    # resize the frame (so we can process it faster) and grab the
    # frame dimensions
    #frame = imutils.resize(frame, width=1280)
    (H, W) = frame.shape[:2]
    # check to see if we are currently tracking an object
    if initBB is not None:
        # grab the new bounding box coordinates of the object
        (success, box) = tracker.update(frame)

        # check to see if the tracking was a success
        if success:
            (x, y, w, h) = [int(v) for v in box]
            cv2.rectangle(frame, (x, y), (x + w, y + h),
                (0, 255, 0), 2)
        # update the FPS counter
        fps.update()
        fps.stop()
        #fixing the x,y tracker box center
        x2=int(x+w/2)
        y2=int(y+h/2)
        #the offsets for the x,y tracking from the center
        sox = str(x2 - (W/2))
        soy = str((H/2) - y2)
        #sending the offsets to arduino
        arduino.write('x'.encode())
        arduino.write(sox.encode())
        #print ("offset X value sent: ")
        #print (sox)
        #time.sleep(0.01)
        arduino.write('y'.encode())
        arduino.write(soy.encode())
        #print ("offset Y value sent : ")
        #print (soy)
        #time.sleep(0.01)
        cv2.line(frame, (int(W/2), int(H/2)), (x2, y2), (0, 255, 0), 1)
        cv2.line(frame, (int(W), int(H/2)), (0, int(H/2)), (0, 0, 0), 2)
        cv2.line(frame, (int(W/2), int(H)), (int(W/2), 0), (0, 0, 0), 2)
        #cv2.line(frame, (320, 240), (x2, y2), (0, 255, 0), 1)

        # initialize the set of information we'll be displaying on
        # the frame
        info = [

            #("Tracker", args["tracker"]),
            #("X = ",str(x)),
            #("Y = ",str(y)),
            ("offset X = ",sox),
            ("offset y = ",soy),
            #("width = ",W),
            #("height = ",H),
            ("FPS", "{:.2f}".format(fps.fps())),

        ]

        # loop over the info tuples and draw them on our frame
        for (i, (k, v)) in enumerate(info):
            text = "{}: {}".format(k, v)
            cv2.putText(frame, text, (10, H - ((i * 20) + 20)),
                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)

    # select the bounding box of the object we want to track (make
    # sure you press ENTER or SPACE after selecting the ROI)
    h , w, ch = frame.shape

    # initial ROI size
    ROI_size_x = 0.1 * w
    ROI_size_y = 0.1 * h

    # Adjust the size when object is near image border
    if( tracker_location[0] + ROI_size_x >= w):
        ROI_size_x = w - tracker_location[0]
    if( tracker_location[1] + ROI_size_y >= h):
        ROI_size_y = h - tracker_location[1]
    if( tracker_location[0] - ROI_size_x < 0):
        tracker_location[0] = 0
    if( tracker_location[1] - ROI_size_y < 0):
        tracker_location[1] = 0

    initBB = ( tracker_location[0] - ROI_size_x, tracker_location[1] - ROI_size_y, ROI_size_x * 2,ROI_size_y * 2)
    #initBB = cv2.selectROI("Frame", frame, fromCenter=False,
    #   showCrosshair=True)

    if mouse_click == True:
        # start OpenCV object tracker using the supplied bounding box
        # coordinates, then start the FPS throughput estimator as well
        tracker = OPENCV_OBJECT_TRACKERS[args["tracker"]]()
        tracker.init(frame, initBB)
        fps = FPS().start()
        mouse_click = False

    #drawing the initial box
    cv2.rectangle(frame,int(initBB[0],initBB[1]),int(initBB[2],initBB[3]),(0,255,255),2)

    # show the output frame
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF

    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break
# if we are using a webcam, release the pointer
if not args.get("video", False):
    vs.stop()

# otherwise, release the file pointer
else:
    vs.release()

# close all windows
cv2.destroyAllWindows()