text:
Q: call array items with a delay using in swift - get UIResponder error Searching around didn't seem to provide anything that I understood straight away.
I'm trying to make a stupid 'old skool' loading screen for an app which will print out 'DOS like' statements.
My current code looks like this, but I get a UIResponder, UIApplicationDelegate error - EXE_BAD_ACCESS
I've tried copying this to a new project etc. still get the same error.
Code below:
class ViewController: UIViewController {

    @IBOutlet weak var loadingLBL: UILabel!

    @IBOutlet weak var logoIMG: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //fades logo image in
        logoIMG.alpha = 0
        UIView.animateWithDuration(5, animations: {
            self.logoIMG.alpha = 1;
        })

        //array for loading text

        var loading = ["Loading please wait.......\n", "Registry , OK!\n", `"Available ram, 256k\n", "BIOS Load... OK\n", "Welcome" ]`

        var i = 0
        var str: String = ""
        var timer = NSTimer()

        //delay function for loading array text

        func delayFunc() {
            str += "\(loading[i])\n"
            loadingLBL.text = str
            if i == loading.count - 1 {
                timer.invalidate()
            }
            i += 1
        }

        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector(delayFunc()), userInfo: nil, repeats: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

As I mentioned, I get a crash and I've no idea what I've done wrong.
Any help would be much appreciated.

A: I think your problem is that delayFunc() is in viewDidLoad, the selector is looking in the viewController but can't find the function (because it is in viewDidLoad)
Edit: I wasn't 100% clear about why the selector can't find delayFunc when it's in viewDidLoad. If you declare a function within another function's body it's lifetime is at most the lifetime of its 'parent' function. So when your timer tries to call delayFunc, delayFunc doesn't exist anymore because viewDidLoad has finished running.
Try:
var i = 0
var str: String = ""
var timer = NSTimer()

var loading = ["Loading please wait.......\n", "Registry , OK!\n", "Available ram, 256k\n", "BIOS Load... OK\n", "Welcome" ]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    //fades logo image in
    logoIMG.alpha = 0
    UIView.animateWithDuration(5, animations: {
        self.logoIMG.alpha = 1;
    })

    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "delayFunc", userInfo: nil, repeats: true)
}

func delayFunc() {
    str += "\(loading[i])\n"
    loadingLBL.text = str
    if i == loading.count - 1 {
        timer.invalidate()
    }
    i += 1
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


text:
Q: how to make php submit button follow URL with Parameters vs Echo (current setup)? My Code:
<?php if(isset($_POST['submit'])){
$drop = $_POST['drop_1'];
$drop_2 = $_POST['drop_2'];
$drop_3 = $_POST['drop_3'];
    echo "

You selected $drop $drop_2 $drop_3
See XXX For Your XXX

";
//echo $drop_3." ".$drop." ".$drop_2;

} ?>

What I aim to do instead of displaying a table with the variables, is to have it follow the link
www.xxxxxx.com/index.php/catalogsearch/advanced/result/?name=&description=&short_description=&sku=&price%5Bfrom%5D=&price%5Bto%5D=&make=$drop&v_model=$drop_2&&engine=$drop_3&&category=3

upon clicking the submit button.
I tried
if($_POST['submit'] == 1 )
header("Location: http://www.xxxxxxxxxx.com");

However, it doesn't not work, the page just reloads.
please advise, thanks!

A: You could do this two ways, either change your code so that you have:
<?php
if(isset($_POST['submit']))
{
$drop = $_POST['drop_1'];
$drop_2 = $_POST['drop_2'];
$drop_3 = $_POST['drop_3'];

header('Location: http://www.xxxxxx.com/index.php/catalogsearch/advanced/result/?make=$drop&v_model=$drop_2&engine=$drop_3');

}
?>

However the best bet would be to change your form so that the action is the URL you're wanting to post to e.g. http://www.xxxxxx.com/index.php/catalogsearch/advanced/result/ and change the method to "GET" and then name your form fields appropriately (make, v_model, and engine).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to compute AIC for linear regression model in Python? I want to compute AIC for linear models to compare their complexity. I did it as follows:
regr = linear_model.LinearRegression()
regr.fit(X, y)

aic_intercept_slope = aic(y, regr.coef_[0] * X.as_matrix() + regr.intercept_, k=1)

def aic(y, y_pred, k):
   resid = y - y_pred.ravel()
   sse = sum(resid ** 2)

   AIC = 2*k - 2*np.log(sse)

return AIC

But I receive a divide by zero encountered in log error.

A: sklearn's LinearRegression is good for prediction but pretty barebones as you've discovered.  (It's often said that sklearn stays away from all things statistical inference.)
statsmodels.regression.linear_model.OLS has a property attribute AIC and a number of other pre-canned attributes.
However, note that you'll need to manually add a unit vector to your X matrix to include an intercept in your model.
from statsmodels.regression.linear_model import OLS
from statsmodels.tools import add_constant

regr = OLS(y, add_constant(X)).fit()
print(regr.aic)

Source is here if you are looking for an alternative way to write manually while still using sklearn.


text:
Q: Modal footer cannot align with the body in Safari I have a modal which has a fixed footer. But it doesn't display correctly in Safari. The modal-footer does not align with the modal-body.
This is the bad display:

Whenever I resize the browser, open inspect, or under inspection window to disable any css style, the footer will become correct. And it only happened in Safari, Chrome can display correctly.


text: Q: Получение arp таблицы Как получить arp-таблицу текущего хоста или как найти mac-адрес по ip-адресу с помощью boost.asio? Нужно что-то типа SendARP функции, только кроссплатформенной. Если это невозможно сделать с помощью boost.asio, то посоветуйте подходящую либу.


text:
Q: How to avoid writing an import for every single file in dart/flutter? I am making a flutter application and I created a file/class for each custom widget I am using. Then, I imported all of these files into the main screen but I don't like how it looks. Especially because if I want to add another widget or delete the one I would need to fiddle with the imports.
Is there something like C# namespaces where I can just make one import for all files in folder/namespace?
I already tried using library/part with success but then in https://www.dartlang.org/guides/libraries/create-library-packages says that I should avoid using part/part of. So, are we expected to import each and every file?
Instead of having:
import 'package:custom_widgets/custom_multiplechoice.dart';
import 'package:custom_widgets/custom_singlechoice.dart';
import 'package:custom_widgets/custom_time.dart';
import 'package:custom_widgets/custom_yesnochoice.dart';
import 'package:custom_widgets/custom_date.dart';

I would like to have:
import 'package:custom_widgets';

A: There is this extension for VSCode which can help to create this.
Dart Barrel File Generator

A: Yes there is, you can use export to achieve what you want.
You can place all your widgets in a folder, for example libs/src/ and then create file custom_widgets.dart in libs/ and use export like this inside custom_widgets.dart:
export 'src/custom_multiplechoice.dart';
export 'src/custom_singlechoice.dart';
export 'src/custom_time.dart';
export 'src/custom_widgets/src/custom_yesnochoice.dart';
export 'src/custom_date.dart';

Once you import custom_widgets.dart, all those widgets will be available to you.
Check this out, its all explained here: Dart: Organizing a library package
Update:
In Dart there are no namespaces like in most other languages.
Dart uses libraries for encapsulation, data hiding.
Only way to import a class into your code is to use import in the beginning of your file, which should also be a library.
I have an issue with this too. Imagine a situation where you want to import library dynamically. Let's say you would like to implement MVC pattern in your application, if you are doing this on the server, you would have a Router class that would analyze URL and decide what Controller class to instantiate and what Method from that Controller to invoke. Now every URL would trigger different Controller, and you don't know it in advance, its up to your Router to detect a Class to instantiate. What you need to do in this situation is import every Controller that could get instantiated at the beginning of your file. And I have issues with that. What if your application gets big and you have to import lets say 20 Controller classes, just so Router / Dispatcher can invoke one of them, and in reality you will invoke only one Controller, as there is only Controller per URL.
Don't have issues with manual loading of Libraries, if they are going to be used, but for situation like described above, Dart fails as there is no "auto loading" of classes like in for example PHP, where you can use auto loaders that use namespaces to find out about location of your class and instantiate a class in the middle of the code dynamically.


text:
Q: Change the xml structure by grouping xml elements based on attribute I have to regroup the xml elements in the same xml structure based on the attributes
I have an xml like this

        <c>
            <d1 att2="t1">test 1</d1>
            <d1>test 2</d1>
            <d1>test 3</d1>
            <d1 att2="t1">test 4</d1>
        </c>

I need to conver this xml to,

        <c>
            <d1 att2="t1">test 1</d1>
            <d1 att2="t1">test 4</d1>
        </c>

        <c>
            <d1>test 2</d1>
        </c>

        <c>
            <d1>test 3</d1>
        </c>

A: This is a really uninspired / manual effort, but seems to get the job done. The template applies separate branches to elements with and without @att2 attributes.
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="/">
        <root>
            <xsl:for-each-group select="//d1[@att2]" group-by="@att2">

                        <c>
                            <xsl:for-each select="current-group()">
                                <xsl:apply-templates select="." mode="nowrapper"></xsl:apply-templates>
                            </xsl:for-each>
                        </c>

            </xsl:for-each-group>
            <xsl:apply-templates select="//d1[not(@att2)]" mode="wrapper" />
        </root>
    </xsl:template>

    <xsl:template match="d1" mode="wrapper">

                <c>
                    <xsl:apply-templates select="." mode="nowrapper" />
                </c>

    </xsl:template>

    <xsl:template match="d1" mode="nowrapper">
        <xsl:copy-of select="." />
    </xsl:template>

</xsl:stylesheet>


text:
Q: Persisting java objects except cache or static First of all sorry if the question is weird coz it seemed weird to me too. But still to confirm.
Are there any possible ways to persist a java object except using static specifier and cache?
Cache is not recommended since its an external source and static storage will take up a lot of memory.
Need something if so, with higher performance

A: Java object lifetime is not related to the keyword static (which means a different thing) or using a cache.
Since Java has a managed memory model, everything is managed by the garbage collector, as long as an object is reachable (so it is referenced with a strong reference by another object which itself is reachable) then you don't have to worry about the risk of the deallocation of the object.


text:
Q: Design principle behind a non-stack blowing parser I'm designing a JSON parser for my embedded system. It should come with the protection against stack overflows, meaning that there should be no nested function calls (recursion) or growing storage information. Also no dynamic allocation! How would I in general design such a parser?
In general I can't really figure out how to save contextual information to return to after processing the lower layers. I could of course just parse the upper layers and then start from the beginning to dive down to the second layer, but that would be really inefficient.


text:
Q: python requests not sending my POST data as content-type:multipart/form-data auto I have coded a script that will search a folder for all images and take all information from a excel file and post that data to an API
I have done everything that last what I got stuck that python requests suppose to send my POST DATA auto content-type:multipart/form-data but it didn't as my post data to a dict object the script send the requests as Content-Type: application/x-www-form-urlencoded
import requests
import logging
import os
import json
import csv

try:
    import http.client as http_client
except ImportError:
    # Python 2
    import httplib as http_client
http_client.HTTPConnection.debuglevel = 1

# You must initialize logging, otherwise you'll not see debug output.
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

url_and = "https://api.test.com/api/3.0/listings/"

android_token = '8fas8d7f9a8s7d9f87as9d8f7sa9df7s9f'
headers = {
    'Authorization': "Token " + android_token,
    'platform': 'android',
}

data_android = {}

with open("listingData1.csv", "r") as f_input:
    csv_input = csv.DictReader(f_input)

    for row in csv_input:
        data_android = {
        'mailing_details':row['shipping'],
        'abcoupay':'false',
        'price':row['price'],
        'description':row['desc'],
        'title':row['title'],
        'meetup':'false',
        'condition':'2',
        'mailing':'true',
        'collection_id':row['cat']
        }

        search_path = row['image']
        urls = []
        for file in os.listdir(os.getcwd()+search_path):
            if file.endswith((".jpg",".jpeg",".png",".JPG",".JPEG",".PNG")):
                x = os.getcwd()+"\\"+search_path+"\\"+file
                urls.append(x)

        files = {'photo_%s' % x: ('photo_%s.jpg' % x, open(file, 'rb'), 'image/jpeg') for x, file in enumerate(urls)}

        response = requests.request("POST", url_and,data=data_android,headers=headers)
        print(response.text.encode("utf-8"))

python requests sending http request like
POST /api/3.0/listings/ HTTP/1.1
Host: api.test.com
Connection: keep-alive
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.21.0
platform: android
Authorization: Token as8fa7d87af7s9d8f79as8df0
Content-Length: 986
Content-Type: application/x-www-form-urlencoded

meetup=false&testupay=false&description=%95+Product+Details%0A%95+Suitable+for+very+small+dogs+and+cats%2C+rabbits+and+other+rodent+carriers+such+as+guinea+pigs%2C+ferrets%2C+rats+and+chinchillas.+Made+of+sturdy+plastic%2C+it+is+sturdy+and+convenient.+A+suitable+grill+allows+air+to+circulate+on+both+sides.+The+door+is+made+Of+plastic+coated+steel.+Thanks+to+the+ergonomic+handle%2C+the+mobile+utility.+It+has+a+mix+of+colors+to+choose+from.+--------%0A%95+80cm+length+X+56cm+width+X+65cm+height%0A%95+Approx.+4.1kg+after+assembly%0A%95+Suitable+for+pets+below+16kg%0A%95+Ideal+for+pet+transportation%0A%95+PP+plastic+material%3B+durable+and+sturdy%0A%95+Great+ventilation+and+air+flow%0A%95+Smart+lock+system%0A%95+Can+be+dismantled+for+easy+storage%0A%95+%2A+Please+check+that+this+item+meets+your+airline%27s+specific+requirements+prior+to+air+travel+usage+%2A%0A&mailing_details=FREE&collection_id=45&price=190&title=Pet+Cat+Dog+Carrier+Portable+Breathable&mailing=true&condition=2'

A: The issue is that you are using data instead of file when making the POST request
if you change the request to use the file field as I did below requests should set the Content-Type to multipart/form-data
response = requests.request("POST", url_and, files=data_android, headers=headers)


text:
Q: Replacing input method for Android OS I want to replace the touch-based input method of an android device with an alternative one. For example, if the device operates using finger touch, then I want to operate it using a mouse.
I've searched about how to do this for android systems, but all the methods I found controls the input method only in the context of some application. For example, controlling the text input method in some texting application. After reading some tutorials I found that InputMethodService can be used to control the input, but I observed that the tutorials use it only in applications, not for the entire OS.
Here are some tutorials I found:
http://developer.samsung.com/technical-doc/view.do;jsessionid=T3BZWJLQJGRQYMgdgJyXZpK8GPYrcPRLyFw22xQnWxphmXwkz2LJ!-2094516650?v=T000000030
http://developer.android.com/reference/android/view/inputmethod/InputMethodManager.html
But none of them indicates how I can control the input for the entire system. To elaborate more, I want to be able to enable and disable the touch functionality of the entire OS, when it's disabled I want to use my own input method. This input method will be used to control all the applications and settings of the system, just as the touch method is used.
Can anyone please tell me how to do that, or provide me with a useful resource that explains such a process?
Thank you.


text:
Q: Installing ubuntu server on laptop - can't recognize wifi card I am trying to install ubuntu server on my laptop and it doesn't recognize the wifi card on start of the installation. And i think it's because it is turned off. How can i turn it on without hardware switch?
update
I have managed to install it without wifi (that is my only nic) and turned it on after, but i don't have internet now. How to connect to my wifi network from command line?
I found that i need this wpasupplicant but i can't install it without internet. Maybe this can be found on iso image?

A: For starters, if your notebook does not have a hardware switch to enable/disable WiFi, there probably is an option in the BIOS or UEFI to do it.
Now that you managed to install the system and have a working WiFi card, , you should use wpa_supplicant to setup the network. To do this, you edit the file /etc/wpa_supplicant/wpa_supplicant.conf so that it holds the information necessary to connect to your network. Examples can be found in the wpa_supplicant man pages, a minimal one would look similar to this:
network={
    ssid=YourSSID
    key_mgmt=WPA-PSK
    psk=your_very_secret_passphrase
}

Additionally, you need to set your /etc/network/interfaces to use the configuration for wpa_supplicant:
auto wlan0
iface wlan0 inet dhcp
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

Assuming your WiFi card is the network interface wlan0. Now, issue ifup wlan0 on the command line, and you should be fine.
Edit: If you do not have wpa_supplicant installed, you can download the .deb package on another machine and install from a USB device or whatever possibility you have to move files onto that machine. The package and its dependencies can be found in the Ubuntu package archive.


text:
Q: Проблема с display: table Есть такой пример на jsfiddle.net

.table {
    display: table;
}
.table > div {
    display: table-cell;
}

— Я наблюдал за этой драмой с вертолета. На пакистанское побережье словно напал чудовищный водяной монстр. Темно-зеленая стена, покрытая серебристой пеной, неистовым потоком обрушилась на Карачи, деловую столицу Пакистана, сметая с лица земли большие здания и маленькие дома, словно они были из папье-маше. Люсьена, это было поистине жуткое зрелище. Жители города выбежали на улицы и бросил

как сделать, что бы 2 колонки были на одном уровне?

A: .table { display: table; }
.table > div { display: table-cell; vertical-align: middle; }


text:
Q: Use CppUnitTestFramework with VS2015 to test exe file I have been working all day to try to get the CppUnitTestFramework to work in Visual Studio 2015 with my existing C++ MFC project, which is an exe file with graphical user interface.
I have been trying different things from this MS Guide, including "To link the tests to the object or library files" and "To add unit tests in the same project": https://msdn.microsoft.com/en-us/library/hh419385.aspx
In the case with "To add unit tests in the same project", I just added a new unit test class in the same solution. When I compile the project the unit test just compiles fine, but it never shows up under "Test Explorer".
And in the case with "To link the tests to the object or library files", I just added a new unit test project in the same solutions. From the beginning the unit test project works fine and the sample unit test method shows up in "Test Explorer". But when I add all OBJ files from the other project (added under Linker > Input > Additional Dependencies) - and also a couple of LIB files that used by the other project are added in the same place (in total around 360 obj and lib files). And the paths are added under Linker > General > Additional Library Directories. Everything then compiles fine, but the sample unit test method disappears from the "Test Explorer". If I remove all from Linker > Input > Additional Dependencies, the sample unit test method appears in "Test Explorer" again.
My project settings can be seen here.
Anyone who has an idea as to what is going wrong, since I can not get my test methods to show up in the "Test Explorer" to test my existing project?


text:
Q: Present Perfect: been or gone? Which one to choose:

(A) My father has never gone on holiday in summer.
  (B) My father has never been on holiday in summer.

A: (A) My father has never gone on holiday in summer.
(B) My father has never been on holiday in summer.
Both are correct. You can often use been and gone interchangeably when we are talking about something in the past. For example:
Where had you gone?

*

*I had been to the supermarket.

*I had gone to the supermarket.

HOWEVER, in other tenses this is not applicable. The meaning of the sentence then changes. For example:
Where have you gone?

*

*I have gone to the supermarket. (This means that you are at the supermarket right now)

*I have been to the supermarket. (This means that you were at the supermarket, and now you are back home).

A: The differences are subtle, and not everyone will use them the same way. Here is how I would describe the differences:

*

*"Gone on holiday" implies a change in location, usually away from home, while "been on holiday" could possibly mean taking time away from work without traveling.

*When using the phrases to answer questions, only one might be appropriate for the given context:
Where have you been for the past week?
"I have been on holiday." (I was on holiday, but now I am back)
Why aren't you answering your phone today?
"I have gone on holiday." (I have not yet returned from holiday)


text:
Q: Relation tables n:n on laravel I'm new to Laravel and I have a doubt, I have two tables n: n and I want to create an additional table that stores the two ids of each table. Such as shop and product.
How do I create a store by creating an product automatically in the table shop_product?

A:  save shop data
                 $shop->save();
                 $shopid= $shop->id;
 after save fetch data from shop and simillarly from product

               $product->save();
               $productid= $product->id;
finally use both variables in shop_product like this
             $shop_product->shop_id= $shopid;
               $shop_product->product_id= $productid;


text:
Q: Sphere parameterization with 6 patches I am looking for a parameterization of the sphere with 6 patches, like in http://www.image.ucar.edu/staff/rnair/research09.html
and the inverse of this parameterization.
As well, I would need a method to determine, for a point $x$ (which coordinates are known of course) on the sphere, which patch (patches for boundaries) $x$ lies in (with patches defined by the above parametrization).
Thanks.

A: Hint: you get the parametrization by composing "parametrisation" of the surface of the cube and normalizing points of that surface viewed as vectors in a euclidean space.
How to determine which patch point belongs to? We know that points on the sphere are normalized points from the surface of the cube. So it is enough to find such a way of determining a face of the cube that behaves well with respect to change of length (normalization). Can you find such a method?
EDIT. I'll show two methods of determining the patch. Let's assume we are talking about the unit sphere in $\mathbb R^3$ ($x^2+y^2+z^2=1$). The inscribed cube is $\left[-\frac{1}{\sqrt3}, \frac{1}{\sqrt3}\right]^3$.
Method 1. The top patch is that patch where $z>0$ and $|z|=\max(|x|,|y|,|z|)$. (It's obviously a correct method for the cube surface and it relies on inequalities between coordinates, so behaves well with respect to normalizing.) The same with the other patches.
Method 2. Note that the cube is a ball in the maximum ($\ell_\infty$) metric. So our surface may be described by the formula $\max(|x|, |y|, |z|)=\frac{1}{\sqrt3}$.
Now: we have "parametrization" $g:\partial C\to S^2$ (from the cube surface to the sphere) given by normalization with respect to the euclidean metric. By the previous observation we can easily find its inverse - it's given by the formula (it's just normalizing with respect to the maximum metric + homothety):
$$g^{-1}(x,y,z) = \frac{(x,y,z)}{\sqrt3 \max(|x|,|y|,|z|)}.$$
So the second method is first use $g^{-1}$ and then just test which coordinate(s) are equal to $\pm\frac{1}{\sqrt3}$.
EDIT2 I realized that $\pi/4$ from your link may not be a random mistake. Maybe they want a different parametrization, not coming from the natural parametrization of the cube surface (but maybe more natural for the sphere). Consider the following (for the top patch):
$$\varphi'(\alpha, \beta) = (
\sin\alpha \cdot \cos\beta,
\cos\alpha \cdot \sin\beta,
\cos\alpha \cdot \cos\beta)$$
$$\varphi(\alpha, \beta)=\varphi'(\alpha, \beta)\cdot S\left(\varphi'(\alpha, \beta)\right)$$
Why this formula? $\pi/4$ is an angle - so I wanted the parametrization to be ingular in some sense. But I can't just take one vector and rotate it around one axis by $\alpha$ and then around another by $\beta$ - rotations are not be commutative and we want our solution to be symmetric.
It also translates nicely to the cube - if you normalize it with respect to the maximum metric (you can divide it by $\sqrt3$ if you prefer) you end up with a nonstandard parametrization of the top face of the cube:
$$(\tan\alpha, \tan\beta, 1).$$
EDIT3 (the OP asked in comments for a version for an ellipsoid)
Let's consider an ellipsoid given by the formula $\frac{x^2}{a^2}+\frac{y^2}{b^2}+\frac{z^2}{c^2}=1$. It is the image of the unit sphere under linear automorphism given in the standard basis by a diagonal matrix $D=\mathrm{diag}(a,b,c)$.
It seems that the requested projection is a projection from $[-a,a] \times [-b,b] \times [-c,c]$ (the case of projecting a cube was already discussed in the comments). But this case is actually trivial - if we apply $D^{-1}$ to our picture, we will get the known case of projecting the unit cube $[-1,1]^3$ onto the unit sphere.
All together
Actually we can handle all the cases (cube or cuboid, sphere or ellipsoid, the same parameters for cuboid and ellipsoid or different ones) in one go. We need to firstly: parametrize, secondly: determine the patch. The parametrization of the surface of a cube/cuboid is easy, the tricky thing is how to project it onto a sphere/ellipsoid. One of the ways of determining a patch is by projecting back onto the cube/cuboid. So all we need is projections.
Projections there and back are done by normalizing with respect to appropriate norm. So, projection to the surface of the cube $[-a,a] \times [-b,b] \times [-c,c]$ may be done with the formula $(x,y,z)\mapsto\frac{(x,y,z)}{\|(x,y,z)\|_\infty^{a,b,c}}$, where $\|(x,y,z)\|_\infty^{a,b,c}$ is given by the formula:
$$\|(x,y,z)\|_\infty^{a,b,c} = \left\|\left(\frac{x}{a},\frac{y}{b},\frac{z}{c}\right)\right\|_\infty.$$
Similarly, projection on the ellipse given by $\frac{x^2}{d^2} + \frac{y^2}{e^2} + \frac{z^2}{f^2}=1$ may be done with the formula $(x,y,z)\mapsto\frac{(x,y,z)}{\|(x,y,z)\|_2^{d,e,f}}$, where $\|(x,y,z)\|_\infty^{d,e,f}$ is given by:
$\|(x,y,z)\|_\infty^{d,e,f} = \left\|\left(\frac{x}{d},\frac{y}{e},\frac{z}{f}\right)\right\|_2.$


text:
Q: Is there an online way to compute additive, kernel or spline regressions? I have an online learning problem where every second (say) I receive a new observation $(x_1,x_2,y)$. I'd like to fit the following models: $$ y = f(x_1) + f(x_2)$$ and maybe $$ y = f(x_1,x_2) $$
In an offline setting I would simply run the data through R npreg package or the gam function. Those methods however are offline methods that compute the model once. Whenever a new datum shows up I need to recompute the whole regression all over again.
This is very wasteful and I was hoping I could compute a simple non-parametric regression the same way I use recursive least squares filters for the parametric case (which predicts very poorly in this case).

A: Turns out there is a way to do this with Kernel regressions.
Assuming your fixed test point is $x$, rather than computing every time the prediction at that point through the usual Kernel regression formula we can do the following:
$m_0(x) = g_0(x)=0$
$g_n(x) = g_{n-1}(x) + K_h(x-X_n)$
$m_n(x) = m_{n-1} + \frac{ \left(Y_n - m_{n-1}(x) \right) K_{h}(x-X_n)}{g_n(x)}$
Where  $m_n(\cdot)$ is the prediction after $n$ observations, $(Y_n,X_n)$  is the new observation and $g_n(\cdot)$ is just the running denominator.
This comes from:
Krzyzak, Adam. "Global convergence of the recursive kernel regression estimates with applications in classification and nonlinear system estimation." IEEE Transactions on Information Theory 38.4 (1992): 1323-1338.


text:
Q: Opticon F31 can't enter VCP/Serial mode I've just purchased an Opticon F31 2D barcode scanner for use in a cocoa mac application as a USB Serial device.
We've used the NLV 2101 and scanned the C01 barcode from the universal manual which works, but the F31 always gives back a bad scan error and stays in HID mode (acts as a keyboard). Have I bought the correct scanner or is this one faulty?

A: It turns out that the command code to switch the scanner to VCP mode doesn't work on the F31. You need to use the barcodes on the following URL to switch between VCP and HID mode.
http://wiki.opticon.com/index.php/2D_Scanner_USB_Default


text:
Q: how to get resolution (PPI) of an image
Possible Duplicate:
How to define DPi for a new JPG image?

Is there a way to get a resolution (pixels per inch) of an image in Java? Either with Native APIs or third party libraries. I don't just want the height and width of an image but actually the resolution that determines the output quality of an image.

A: An image has only pixels. it has not ppi.
a monitor, an image sensor and an printer have ppi because they all have dots/pixels related to a measurable distance in inch.
ppi is short for pixels per inch, and therefore a measure for pixel density.
for calculation of ppi / dpi see http://en.wikipedia.org/wiki/Dots_per_inch
You simply divide the number of pixels or points by the number of inch that the output device or photo paper has.
But be carefull if points or pixels is wanted.


text:
Q: SFTP Connection Failing To Linode's Ubuntu Server I installed vsftpd on our Ubuntu machine on (Linode VPS) and followed the steps from this documentation. http://www.noob2geek.com/linux/setup-vsftpd-debian-ubuntu/
So, everything works correcly if I try to login via @root, but I cannot connect via stfp outside from server using this command.
ssh myuser@176.58.112.67
This is the terminal output: http://codepad.org/o9HaVstA
What's the problem?

A: Solved.

*

*Connected as @root

*run "nano /etc/passwd"

*Changing user's "/bin/false"to "/bin/bash"
then fixed.


text:
Q: Film identification: Two men using equipment to play metal CD-like discs I remember seeing a film (or part of) a long time ago (probably about 1988) and I'm trying to identify it. As I recall it was black and white. The only bit of it I remember had two men working with some equipment, trying to get it to work. The equipment was for playing discs (something like CDs, but I think they were metal). When they got it working it projected the image and sound of a third man. I can't recall if the image was purely a recording, or if it could interact with the other men and respond to them. There might have been an element of time travel in the film as well, or I could be mixing it up with something else. The film was in English (not dubbed / subtitled).
Thinking a little more about it I think that the person on the recordings was the boss of the other two and was issuing them their orders.
UPDATE
I seem to recall that there were lots of discs (in a heap on the floor?) and that the one they needed had a scratch on it. I think the machine might have been outside - they might have been on another planet perhaps?

A: I'm thinking This Island Earth (1955).  they assemble a machine they know nothing about and use a metal disc to contact the alien Exeter who entices them to work for him.


text:
Q: How to generate a complex non-binary tree? I want to create a complex tree, where every subtree can have several branches that go deep. Where can I find info about this?
EDIT:
OK, binary tree also suits my needs. But I can't find random binary tree generator for C#

A: For an implementation and source:
http://daisley-harrison.com/blog/post/NET-Generic-BTree-Library-and-Source-Code.aspx
For concepts and explanation, Wikipedia is your friend: http://en.wikipedia.org/wiki/B-tree

A: Word complex in your question might mean that you don't exactly understand, what particular tree you need ) You should read general material about trees first and you'll find the closest type of tree...
Here is wide range of data-structures including dozens of tree-types: enter link description here

A: also good explanation, i'm currently study this  and have found this useful
http://xlinux.nist.gov/dads//HTML/tree.html
but in general,yandex.com will help you


text:
Q: How to rearrange mail merge documents in ms-word? Requirement:
I have an excel file, which connects to Mail merge in word, which I already did.
Suppose there seems to be total 500 records in that excel, and have a field serial number, which seems to be unique from 1 to 500.  I need to list the details of the 1st record in top of the 1st A4 page and 251st record in bottom of the 1st A4 page, and 2nd record in top of the 2nd A4 page and 252nd record in bottom of the 2nd A4 page and so on.. and in 250th page,  250th record in top and 500th record in bottom of that page..
My Requirement is, when I cut this A4 size to 2 parts, the page needs to be sort in the serial number order.  Hope you understand my requirement.
Thank you in advance..


text:
Q: How to reset config files to default, especially boot sequence Is there a way to reset all ubuntu config files, a batch procedure?. No the local config files, I mean all /etc config files.
I know how to do that one by one but that is a job for weeks or work.

A: No - there is no standard command.
But with the following command you may inspect which configurations may be different from the "default" configuration provided by the ubuntu packages.
 find /etc/ -name "*.dpkg-*"


text:
Q: finding middle of linked list using fast/slow ptrs, running into nullptr error when I should not be (fast.next.next check) Here's my code to find the middle of the linked list:
public ListNode findMiddleNode(ListNode head) {
    if(head == null){return null;}
    if(head.next == null){return head;}
    ListNode slow = head;
    ListNode fast = head;
    while(fast != null && fast.next.next != null){
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;

}

In the case of 1->2->3->4->5, the final iteration of this should be:
1->2->3->4->5
      s
            f

My loop should end right here. fast.next.next is null and does not exist. However, I get a console nullptr error instead of the answer '3'. My guess is somehow I'm going outside the list.
Can anyone reason a guess why this is happening?
Edit: Looks like if I add the condition "fast.next" in my while loop, it works. No clue why.
Edit 2: Is "fast.next.next", when fast is at the end of my list at 5, giving me some kind of junk value that isn't null? Just a guess.
Edit 3: Here is my full results output: https://ibb.co/XpNbFWh , on firecode.io

A:     while(fast != null && fast.next.next != null){

The above line of code checks fast.next.next without checking fast.next.
Since fast.next can be null, fast.next.next can throw NullPointerException in such cases.

A: Your code inside the while and the condition have logic mistakes.
Try this, I tried it on paper and it seems to work fine:
    while(fast != null && fast.next != null){
        slow = slow.next;
        if (fast.next != null)
        {
          fast = fast.next;
          if (fast.next!=null)
             fast = fast.next;
        }
    }

I guess the code can be simplified, but well, as the another user said, your mistake is on the line fast.next.next.
For that reason inside the while I added the condition fast.next != null
to avoid the NullPointerException.
You should verify on a paper the way is working the code inside the while loop and its conditions


text:
Q: How to fire INotifyPropertyChanged handler when I change ComboBox's selected item? I'm trying to bind a ComboBox to an ObservableCollection<MyType> but it's not working as I expect. When I create an instance of ComboData, e.g.
ComboData = new ObservableCollection<MyType>();

and add data to it, e.g.
ComboData.Add(new MyType(string.Format("{0}", i.ToString()), i));

I can see that the Value property of MyType is being set and the PropertyChangedEventHandler event handler executes. This is correct functionality.
The problem is when I select a different item in the ComboBox later. I expect to see Value being set again and firing the event handler, but nothing happens. However, I can see that the property's getter is being fired and returning _value.
Is there something I'm doing wrong?
MyType is defined as:
public class MyType : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public MyType(string key, int value)
    {
        Key = key;
        Value = value;
    }

    public string Key { get; set; }
    private int _value;
    public int Value
    {
        get { return _value; }
        set
        {
            if (_value != value)
            {
                _value = value;

                OnPropertyChanged("Value");
            }
        }
    }

    internal void OnPropertyChanged(string prop)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }
    }

    private void IntegerItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        // this never executes *after* the ComboBox has been populated!!!
    }

}

The User Control's XAML is:
<Grid>
    <ComboBox x:Name="cboItems"
      DisplayMemberPath="Key"
      SelectedValuePath="Value"
      ItemsSource="{Binding Path=ComboData}">
    </ComboBox>
</Grid>

And the code behind for the User Control is
public partial class ComboBoxControl : UserControl
{
    public ObservableCollection<MyType> ComboData { get; set; }

    public ComboBoxControl()
    {
        InitializeComponent();

        ComboData = new ObservableCollection<MyType>();
        int min = 0;
        int max = 10;
        for (int i = min; i <= max; i++)
        {
            ComboData.Add(new MyType(string.Format("{0}", i.ToString()), i));
        }

        cboItems.DataContext = this;
    }
}

What do I need to do to fire the event handler when I change the selected item in the ComboBox?

A: Better to use CollectionView class, which has a CurrentChanged event.. You can bind CollectionView to your ComboBox. So when selecteditem change.. you can get value from CollectionViewMember.CurrentItem in CurrentChangedEvent

A: Selecting a different option in your combobox isn't changing any of the items in ComboData, it's just changing the selected item, so it won't use the setter in MyType.  It uses the getter to retrieve the value to display.
The ComboBox has a SelectedItemChanged event which will trigger when a new item is selected.


text:
Q: Does The Daus's counterattack work with Trifurcated Strike? When The Daus card is played, it summons Chimes in the spaces next to it. If an enemy attacks a Chime, the Daus will counter attack that enemy.
If I give The Daus a multi-attack ability like Bifurcated or Trifurcated Strike, will The Daus's counterattack hit multiple spaces?

A: No, a Daus with Trifurcated Strike will only counterattack the enemy that attacked the Chime.
https://clips.twitch.tv/SneakyElatedSwanTakeNRG-IIR_znZ9OOy5262b


text:
Q: How to use user-defined Java function in velocity files in archetype-resource path?
I am creaing a arhetype project for convenient creation of similar projects by maven-archetype-archetype archetype. The following is the command I use:
mvn archetype:generate \
  -DgroupId=cn.edu.idea.bios \
  -DartifactId=archetype-spring-console \
  -DarchetypeGroupId=org.apache.maven.archetypes \
  -DarchetypeArtifactId=maven-archetype-archetype \
  -DarchetypeVersion=1.4

As shown in the picture above, I want to use a  Java function in a velocity file in the archetype-resources path. There is a ClassNotFoundExcept thrown when I executed the command mvn clean install.
The class is located in target/classes path.
This is my pom.xml. the compiler plugin is added by myself because of no classes found in target/classes before adding the compiler plugin.
How to resolve this problem, please?
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>cn.edu.idea.bios</groupId>
  <artifactId>archetype-spring-console</artifactId>
  <version>1.0.0</version>
  <packaging>maven-archetype</packaging>

  <name>Archetype - archetype-spring-console</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-collections4</artifactId>
      <version>4.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.11</version>
    </dependency>
  </dependencies>

  <build>
    <extensions>
      <extension>
        <groupId>org.apache.maven.archetype</groupId>
        <artifactId>archetype-packaging</artifactId>
        <version>3.0.1</version>
      </extension>
    </extensions>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <executions>
          <execution>
            <id>default-compile</id>
            <phase>compile</phase>
            <goals>
              <goal>compile</goal>
            </goals>
          </execution>
          <execution>
            <id>default-testCompile</id>
            <phase>test-compile</phase>
            <goals>
              <goal>testCompile</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
    </plugins>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-archetype-plugin</artifactId>
          <version>3.2.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>


text:
Q: PhantomJS server running in Docker container I need to run PhantomJS server to generate images on demand. When I set this up on a standard Amazon Linux EC2 instance, it works fine.
However, I want to distribute it in a Docker container. Using the Amazon Linux base (http://docs.aws.amazon.com/AmazonECR/latest/userguide/amazon_linux_container_image.html) I include the following RPMS:
RUN \
  yum update && \
  yum install -y tar \
  yum install -y bzip2 \
  yum install -y freetype6 \
  yum install -y fontconfig \
  yum install -y freetype-devel \
  yum install -y fontconfig-devel \
  yum install -y libicu-devel \
  yum install -y libpng-devel \
  yum install -y libjpeg-devel \
  yum install -y gperf \
  yum install -y bison \
  yum install -y flex \
  yum install -y gcc \
  yum install -y gcc-c++

And then set up the phantomjs server as I did on the standard EC2 instance.
When launched, this generates images, but the images are missing their text labels. I can't find any debug output, and I didn't write the original code to generate the image.
Could anyone suggest what might be missing from the Docker container? I didn't have to install any extra libraries in the EC2 instance to get it to work. I've also tried increasing the spec of the host instance image in case there were issues with RAM.
Sample broken image:
https://gm1.ggpht.com/RxVy2Q6KpRVRxSPCoVEupfnl2ieHY9dr9Vu8o9P4JOjw4FqVsEfPgW1leA59R8n2hNF9u6cmL3LLO3idArCWBiE1EFpIz5CI9n29z1_95sC0lesTy6oxkcIoBoHMFNdMNSqURW9Sc1Is8Sd1t-YWsQKgJvtUsotBmRaEOWSKr7JpyjY6stSl1xJiJ5enc7ccvKTkPcuFNMl_NQCrv9b44brzpFjO2y6ZDrfBZolFXc-hqXvbRFazsRd-IVFh4mENLxVmQpeqbRug-egBHV_LCmj0ohBToxT4_b6_pqZpim9MZR6KFCX7QDu-rGtlhpMeweeDZ8uRkPwYyZ48hiEAQpVPAfsHNQGHR_kcRSN7-3bKDZJKjvPtcQjn-5bR-AMwX5B8iqFGyLLaG4QeA7AykmPJ4LGrX8aboPRRSdkH9EdYwEa4wH4IogHa6m4-OobG1FLdEgnveHzVL4XkB3zesrKa3-t5TgdL8nP9xTLaId2uLdqVO39QPTxKGrutyFJst1WhsdoUiBYhLD4JQZW0COBaQB9Kdu-anLpgaZ4oObrtqfzVRxrjdL5s7Qf_FagPtyZiSra2RfF3uDEpjRi0w3BSd8P-PvC2jmTqvuMz4rK-Go9pLLU1Dsqz3mR7p70yE7SVTzVy61YJLYT_NW3vAgHIir_HuJ4fpA3vg8qc2WGgUbOB83QtBsxQoIvu0oyIqq7k7pYzJ6SKCA=s0-l75-ft-l75-ft

A: I eventually resolved this by using an Ubuntu base rather than an Amazon Linux base. Never determined what was missing from Amazon Linux.


text:
Q: How to attach click event on iframe I want to make an iframe clickable so that I can associate an ng-click or a javascript event listener to it.
Actually, I want to call some function once it's clicked
Update1:
As per the comment I tried this SO link & created the Plunker but it's not working


text:
Q: Associatif array doesnt have a length I'm trying to JSON.stringify an associatif array in javascript, when i console.log it the output is :
Array[0]
adresse:
"zfzf"
adresse2:
"zfz"
adresse3:
"fzfz"
code_postal
"fzfz"
[...]
length:
0
[...]
__proto__:
Array[0]

as you can see the lenght is equal to 0, so when i JSON.Strigify it, the answer is [ ]
i use to build my array like this :
var info = [];
    $("[data-change]").each(function(key,obj){
        if ($(obj).val() == "") {
            i = 1;
        }
        else {
            info[$(obj).attr("name")] = $(obj).val();
            j++;
        }
    });

all those "data-change" are inputs, i've tryied to use the variable j instead of $(obj).attr("name")] and it works but i neeed the key to be the name of the input

A: Because Objects doesn't have length property.
Use Object.keys(obj).length to view length


text:
Q: Is it allowed to write "put someone into words"? "put into words" is commonly used in English,
as in

I cannot put into words how much I love him.
I can't put my feelings into words.

But is it allowed to place a "person" as an object in this phrase?
as in

"Amy was so unique that I couldn't put her into words."

A: In a case like yours, I would use a different verb other than put.

Amy was so unique that I couldn't describe her in words.

One might say that the phrase "in words" is redundant in that sentence, and that it could be improved were it more concise:

Amy was so unique, she was indescribable.

Nevertheless, the use of "in words" in such contexts is grammatical and not all that uncommon. The following are all quotes found in recent news articles:

I can't describe in words the feeling of winning. I'm very proud of my team.
I can't describe in words the meaning of this win and the way it happened.
I can't describe in words the kind of energy and dynamism our talented cast is bringing to this show.
All I know is that it filled me with a rage I simply can't describe in words.


text:
Q: jsp out.write scriptlet tag within scriptlet how do i out.write scriptlet tag when the out.write is already in scriptlet tag?
    <% if (answerList.size() > 2){
                            int toPrint = answerList.size() - 2;
                            int init = 2;

                            for (int x = 0; x < toPrint; x++){
                                out.write("	");
                                out.write("<input type='checkbox' name='to_delete" + (init+1) + "' id='to_delete" + (init+1) + "' value='to_delete'> &nbsp &nbsp &nbsp ");
                                out.write("<input type='text' name='answer' id='answer' class='mlselect'  maxlength='200' size='90' value='<%=((SurveyAnswerBean)answerList.get(answerList.size()-"+(init+1) +")).getAnswerText()%>'> &nbsp ");
                             }
                            System.out.println("Answer List more than 2");
                            System.out.println("To print: " + toPrint);
                        }%>

i have tried but it has tag error, any help will be appreciated!

A: The answer is that you cannot nest scriplets tags, and it also doesn't make sense to do it (becuase you can't evaluate server-side variables on the client-side).
You should replace:
"...value='<%=((SurveyAnswerBean)answerList.get(answerList.size()-"+(init+1) +")).getAnswerText()%>'...

with:
"...value='" + ((SurveyAnswerBean)answerList.get(answerList.size()-(init+1))).getAnswerText() +"'...


text:
Q: implicit classes in Scala : performance and good practice As far as I know, implicit classes are used to provide extension methods to existing types , or let's say enrich types coming from other libraries or APIs.
However, I was playing around and tried this :
case class Person(firstname : String , lastName:String ) {
  def x() = {
      println("x")
  }
}

implicit class Foo(x : Person) {
  def y() = {
    println("y")
  }
}

Person("","").y()

I wanted y() to be accessible from this file only and undefined elsewhere.
I could just have added a private class that inherit from class Person and
thus add method y() in it. [1]
So my question is : other than the fact that this goes against the principle which implicit classes are essentially created for; what does really happen behind the scenes, and does this have any performance issues one should be aware of ( comparing to solution 1 ) ?


text:
Q: Python global logging How do I make a Logger global so that I can use it in every module I make?
Something like this in moduleA:
import logging
import moduleB

log = logging.getLogger('')

result = moduleB.goFigure(5)
log.info('Answer was', result)

With this in moduleB:
def goFigure(integer):
    if not isinstance(integer, int):
        log.critical('not an integer')
    else:
        return integer + 1

Currently, I will get an error because moduleB does not know what log is.  How do I get around that?

A: Creating a global logger which can be used to

*

*create a new log file or

*returns logger for a global log file.

Create a module called called myLogger.py : This will have the log creation code
myLogger.py:
import logging

def myLog(name, fname = 'myGlobalLog.log'):
'''Debug Log'''
    logger = logging.getLogger(name);
    logger.setLevel(logging.DEBUG)
    fhan = logging.FileHandler(fname)
    fhan.setLevel(logging.DEBUG)
    logger.addHandler(fhan)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fhan.setFormatter(formatter)
    '''comment this to enable requests logger'''
    #logger.disabled = True
    return logger

Now to create a new log in your module say A.py
from myLogger import myLog
log = myLog(__name__, 'newLog.log')
log.debug("In new log file")

Thus you have to pass the file name along while getting the logger.
To use the global logger in A.py:
from myLogger import myLog
log = myLog(__name__)
log.debug("In myGlobalLog file")

Need not pass the file name in this case as we gonna use the global log.

A: You could make your own logging "module" which instantiates the logger, than have all of your code import that instead. Think:
logger.py:
import logging
log = logging.getLogger('')

codeA.py:
from logger import log
log.info('whatever')

codeB.py:
from logger import log
log.warn('some other thing')

A: A module has by default only access to builtin functions and builtin constants. For all other variables, functions... you have to use the keyword import.
Now for your concrete example, you can import the log-variable of moduleA in modulesB like this:
from moduleA import log

The following would be equivalent because the logging-module returns the same instance of the logger that was returned to moduleA:
import logging
log = logging.getLogger('')

Another solution for you could be to use the default-logger of the logging module like this:
logging.info("Hello")


text:
Q: Will ES6 RegExps support the Iterator protocol? I'm unable to find an answer in the spec or list of proposals as to whether RegExps in ES6 will provide the necessary methods to support the Iterator protocol for matched groups. There are a number of symbol methods, but I'm not familiar enough with the semantics of the various symbols to tell if they will provide this.
I would imagine something like:
var rex = /((\w+)\s?)*/;
var res = rex.exec("test string");

console.log(res);

for (let match of res) {
    console.log(match);
}

This seems to work in 6to5's REPL, logging the expected "test string", "string", "string".
Is this specifically defined in the ES6 spec, and if not, what properties of the regex result allow it to work? Or is it just an artifact of 6to5 not being exactly ES6?

A: res is just an Array of matches. You can check it using one of the next variants:

Object.prototype.toString.call(res) === '[object Array]'
res instanceof Array;
Array.isArray(res);
res.constructor === Array;

And arrays in ES6 supports iterator interface. See here, or in MDN: Array.prototype[@@iterator]
What about input and index properties - they just added to the res array by exec method. For example you can check v8 source code:

*

*RexExpExec method JS

*RegExpImpl::Exec C++

*SetLastMatchedInfo (last matched info is our res object)


text:
Q: Error while calling Web service in Android 4 and above I used the following code for calling the web service in android.
if( requestType.equals( "GET" ) )
{
    try
    {
         // GET
        HttpGet request = new HttpGet( );
        request.setURI( new URI( requestURL ) );
        HttpResponse response = client.execute( request );
        if( response == null )
        {
            Log.d( APP_NAME, "Get Response returned null" );
        }
        else
        {
            HttpEntity entity = response.getEntity( );
            String encoding = EntityUtils.getContentCharSet( entity );
            responseString = EntityUtils.toString( entity, encoding == null ? "UTF-8" : encoding );
        }
    }
    catch( Exception e )
    {
            Log.e( APP_NAME, "Error Get : " + e.getMessage( ) );
    }
}

This code is supporting upto 3.0. But not supporting in android version 4.0 and above.
Please do the needful.

A: I guess the problem is NetworkonMainThreadException.
This is because either you are performing network operation on main thread which in not allowed android version >= 3.0.
Use AsyncTask Read from http://developer.android.com/reference/android/os/AsyncTask.html


text:
Q: How do I enable auto prefix in visual studio code? I've been trying to make my website more responsive but I'm having trouble enabling auto prefixer in visual studio code. I installed the extension but it doesn't seem to work. Any help would be appreciated.

A: You shoud go to visual studio extensions.
1 - Install Autoprefixer.

2 - Ctrl + Shift + P > Type "Preferences: Open Settings(JSON)".

3 - Add this code snippet :
"autoprefixer.options": {
"browsers": [
"last 4 versions",
"ie >= 9",
"> 5%"
]
}

4- Restart Visual Studio Code.

5 - Select the css code you want to prefix.

6 - Ctrl + Shift + P > Type "Autoprefixer: Run".

That's it.

A: You can go to setting and search for auto prefixer in search bar at the top you will be able to enable and customize any extension. Moreover, you can check the detail of the extension to know how to use it, Or You check out this answer also Enable vendor prefix autocomplete in CSS files in Visual Studio Code.


text:
Q: Django: Recommended Model definitions for Customers and Payments when handling recurring payments Assuming I have two models, one for Customer and another for Payment.  Each month my customer should have made a payment no later that the 15th of each month. What is the best way to structure the models in order to easily get a report of customers who haven't pay for the current month?
Customer model:
class CustomerModel(models.Model):
    first_name = models.TextField()
    last_name = models.TextField()
    email = models.EmailField()

Payment model:
class Payment(models.Model):
    customer = models.ForeignKey(
               Customer,
               on_delete=models.SET_NULL,
               null=True)
    amount = models.FloatField()
    date_received = models.DateField(auto_now=False)

A: We can make use of .exclude(..) here to exclude the people that have paid, like:
from datetime import date
month_day = date.today()            # specify a day in the month to check
from_date=month_day.replace(day=1)  # the first of the current month
to_date=month_day.replace(day=15)   # the 15th of the current month

Customer.objects.exclude(
    payment__date_received__gte=from_date
    payment__date_received__lte=to_date
)
or more elegant with a __range lookup:
Customer.objects.exclude(
    payment__date_received__range=(from_date, to_date)
)
If we thus run this today (with month_day equal to the 15th of October, 2018), we will get all Customers that have not made a payment with date_received between the first of October, and the 15th of October. The same will happen any day of this month. By setting month_day to for example date(2017, 12), you obtain all the customers that did not make a payment between December 1st, 2017 and December 15th, 2017.
Note hwever that perhaps not all customers started using your service at that moment (or already unsubscribed). In that case these Customers will thus get listed, so it might require some refactoring to make this more usable.


text:
Q: Apache Flink, more threads than Kafka partitions The data flow is simple like
kafka -> some logic -> kafka
and 'some logic' is a bottleneck here so I want to use more threads/tasks to increase throughput instead of increasing kafka partitions (currently 3). Order between input and output topics doesn't matter here.
It can be easily done with Apache Storm. I can just increase parallelism of a bolt for the some logic. How can I do it with Flink? More general question is if there is any simple way to use different parallelism for different stages with Flink?

A: This is quite simple in Flink. You can specify the parallelism of each operator using the setParallelism() method:
DataStream<String> rawEvents = env
  .addSource(new FlinkKafkaConsumer010("topic", new SimpleStringSchema(), props));

DataSteam<String> mappedEvents = rawEvents
  .flatMap(new Tokenizer())
  .setParallelism(64); // set parallelism to 64


text:
Q: How to have accessible swipe action for iCarousel I am trying to make an accessible app. The problem arises when I wanted to have standard (Three-finger swipe right or left) behavior with iCarousel.
Since iCarousel is not fully accessible by nature and it just lets user to have items be User intractable.
I done some research, there are some workarounds but
I also don't want to implement UIAccessibilityCustomAction cause this will not give the user easy to swipe ability.

A: You can override and implement accessibilityScroll(_:)
 method as:
extension iCarousel {
    override open func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool {
        super.accessibilityScroll(direction)

        if direction == UIAccessibilityScrollDirection.left {
            self.scroll(byOffset: 1, duration: 1.0)
        }
        if direction == UIAccessibilityScrollDirection.right {
            self.scroll(byOffset: -1, duration: 1.0)
        }
        return true
    }
}

and post a desire (e.g. page number) in iCarousel delegate method carouselDidEndScrollingAnimation, you may also change the accessibilityLabel and other accessibility related values here.
func carouselDidEndScrollingAnimation(_ carousel: iCarousel) {
    self.carousel.accessibilityLabel = accLabels[currentItemIndex]
    self.carousel.accessibilityValue = accValues[currentItemIndex]
    UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification,
                                    "item \(currentItemIndex + 1) of \(self.items.count)")
}

Also in viewDidLoad set the initial accessibilityLabel as well as:
self.carousel.accessibilityTraits = UIAccessibilityTraitUpdatesFrequently

I hope this helps someone.


text:
Q: Is Traits in Scala an Interface or an Abstract Class? I have read over the internet that Traits in Scala are

interfaces that can provide concrete members

this means, traits are interface and we may provide body to methods in interface. I have a simple query here, if that is possible than why my below code shows error:

Error:(6, 8) object Car inherits conflicting members:   method
  startEngine in trait Vehical of type => Unit  and   method startEngine
  in trait Motor of type => Unit (Note: this can be resolved by
  declaring an override in object Car.) object Car extends Vehical with
  Motor {

trait Vehical {
  def startEngine : Unit = {
    println("Vehical Start")
  }
  def stopEngine
}

trait Motor {
  def startEngine : Unit = {
    println("Motor Start")
  }
  def stopEngine
}

object Car extends Vehical with Motor {

  override def stopEngine : Unit = {
    println("Stop Engine")
  }

  def main(args: Array[String]): Unit = {
    Car.startEngine
    Car.stopEngine
  }
}

Being a java developer I would have not provided body inside interface but scala traits allowed this. If traits are not interface then I'll consider them as an abstract class, that means no interface allowed in scala.
Also please let me know how to resolve this ambiguity problem. How can I use my startEngine method in child class if the same method is available in multiple traits.

A:
Being a java developer I would have not provided body inside interface
  but scala traits allowed this

A trait in Scala provides means of defining a default implementation, and so does Java starting version 8. In Scala, they are primarily used as mixins.
In regards to the compilation error, this arises from the fact that you have declared both Vehicle and Motor with a startEngine method, and that creates an ambiguity from the compilers point of view, since you're mixing in both implementations. To overcome this, you need to explicitly override the method in the implementing class/trait:
override def startEngine: Unit = super.startEngine

One important thing to note is that super here is referring to the last trait in the mixin chain which supplies a startEngine method, in this case Motor. This means that you'll see:
Motor Start
Stop Engine

Which I'd argue is not what you want.
What can be done is to require Vehicle to have a mixed in Motor implementation using self types:
trait Vehicle {
  self: Motor =>

  def startEngine: Unit = {
    println("Vehicle Start")
    startMotor
  }

  def stopEngine: Unit = {
    println("Stopping Engine")
    stopMotor
  }
}

And define your Motor methods in terms of motor only:
trait Motor {
  def startMotor: Unit = {
    println("Motor Start")
  }

  def stopMotor: Unit = {
    println("Stop Motor")
  }
}

And then you mixin everything:
object Car extends Vehicle with Motor

And call:
def main(args: Array[String]): Unit = {
  Car.startEngine
  Car.stopEngine
}

And you get:
Vehicle Start
Motor Start
Stopping Engine
Stop Motor


text:
Q: Javascript: Grab link from external webpage source and then place it in the specified location I need to create a JScript that does the following actions:
1- Grab a link from an external webpage's source code
2- Remove unecessary string from the link, if needed
3- Place that link in the specified entry
Now explained:
I have a video hosted in another website and i want to make it play in my own, the problem is that the link to that video changes after 12/24h and i have to update it all the time.
The webpage that provides the file has a permanent url so the link to the page that has the file never changes but the link to the video does.
I need a JScript that could recover the updated link from the specified webpage and place it inside the src field, something like a source code crawler until it find the match to the video name, like so:
The video is called video.mp4 and it allways has the same string after it (ex. &download=yes)
Upon the match of the string 'video.mp4&download=yes', it would retrieve the full path to the file, from "..." to "...video.mp4", ignoring the &download=yes because the player cant play with that last string included.
After that is done, it would place the link in the specific "src=" field making it possible to be played in the video player.
Also, thanks in advance for the time spent, if possible try to make it easy for me to understand since im new in Jcript.

A: As all the comments say'ed this cant  be done by simple JavaScript BUT you could use YQL to query the page and get back the result as JSNOP.
YQL is an service by Yahoo that scans a side for you. Also you can pass in a javascript file to query the result html with xpath. All this will be done by Yahoo on their servers. At the end you can import the result on your page as JSONP.
So this is an example in the YQL console to query a specific link type from yahoo finance side:
http://developer.yahoo.com/yql/console/#h=select%20*%20from%20html%20where%20url%3D%22http%3A//finance.yahoo.com/q%3Fs%3Dyhoo%22%20and%20xpath%3D%27//div%5B@id%3D%22yfi_headlines%22%5D/div%5B2%5D/ul/li/a%27
the query will give you a jsonp string:
http://developer.yahoo.com/yql/console/#h=select%20*%20from%20html%20where%20url%3D%22http%3A//finance.yahoo.com/q%3Fs%3Dyhoo%22%20and%20xpath%3D%27//div%5B@id%3D%22yfi_headlines%22%5D/div%5B2%5D/ul/li/a%27
On your side you have to create an new script and insert it in your DOM. As you can see in the result jsonp it will call a function "cbfunc" with json as parameter. All you need is function "cbfunc" on your side to process the json

A: This will only be possible with JavaScript if the video page and yours are on the same domain (though you may be able to employ some tricks to make it happen). The best way, as I see it, would be to do some server-side scripting to download the page (which would be text only, so you wont be using much bandwidth)  and to do some DOM manipulation with whatever HTML lib is available for your server language.


text:
Q: How to print values of all elements of java.util.Date type Array in R language I am new in R language and i have a problem :
In java i have a method like this
public Date[] getAllDates(String fromDate, String toDate){
        ArrayList<Date> dates= new ArrayList<Date>();
            -------
      Generating dates from fromDate to toDate here and setting into above
      arraylist.
            ------

           return dates.toArray(dates.size());

}

Now in R when i am calling this method then it is returning this array
dates= c(classInstance$getAllDates(fromDate,toDate));

Now i am not able to show the dates values present in dates array it is showing as object only.
Case : 1
and if i use print(str(dates[1])) then it displays
List of 1
 $ :Formal class 'jrectRef' [package "rJava"] with 4 slots
  .. ..@ dimension: int 10
  .. ..@ jsig     : chr "[Ljava/util/Date;"
  .. ..@ jobj     :<externalptr>
  .. ..@ jclass   : chr "[Ljava/util/Date;"
NULL

when i use : print(typeof(dates[1]))
it is showing
"S4"

Case : 2
when i use : print(typeof(dates[1]))
it is showing
"list"

i tried everything but i am not able to show the values from this array.
please help me.Thank you

A: Finally after a lot of search on google(approx 3 days continuously) about R programming and concept and techniques to resolve my above issue, now i am able to give my answer itself.
dates= c(classInstance$getAllDates(fromDate,toDate));

from here
Case : 1 Solution
for(i in 1 : dates$length) {
 #Fetching one by one date object using for each loop in R
 index = .jevalArray(dates)[[i]]
 # Holding an individual array into variable
 print(index$toString())
 # Now printing using Java toString() method only.
 }

Note** : but for "list" type this solution also got stuck. It worked for me when typeof was "S4"
Case : 2 Solution
I found a working solution for this as well
arraysObject = .jnew("java/util/Arrays")

#Just taken a reference of an object of java Arrays classes
for (i in 1:length(indexes[[1]])){
        print(arraysObject$toString(indexes[[1]][i]))
#calling Arrays.toString() method of java into R programming
    }

OR
arraysObject = .jnew("java/util/Arrays")
print(arraysObject$toString(indexes[[1]]))


text:
Q: Is it possible to set up PHP-FPM with different pool-options (xdebug enabled / xdebug disabled) I've a LEMP environment and need the option to separate all development subdomains from staging (development with xdebug staging without).

*

*dev.projectX.mydomain.tld

*staging.projectX.mydomain.tld

Therefore I set up two pools php-dev and php-stage, but it seems that i can enable extensions only in the php.ini!?
Here is my pool.conf (dev)
[php-dev]
listen = 127.0.0.1:9101
listen = /var/run/php-fpm/a1-php-dev.socket
listen.backlog = -1
listen.allowed_clients = 127.0.0.1

user = nginx
group = nginx

request_slowlog_timeout = 3s
slowlog = /var/log/php-fpm/slowlog-php-dev.log

pm = dynamic
pm.max_children = 20
pm.start_servers = 10
pm.min_spare_servers = 4
pm.max_spare_servers = 16
pm.max_requests = 500
pm.status_path = /status

request_terminate_timeout = 120s
rlimit_files = 131072
rlimit_core = unlimited
catch_workers_output = yes

env[HOSTNAME] = $HOSTNAME
env[TMP] = /tmp
env[TMPDIR] = /tmp
env[TEMP] = /tmp

php_admin_value[zend_extension]         = "/usr/lib64/php/modules/xdebug.so"
php_admin_value[xdebug.default_enable]      = 0
php_admin_value[xdebug.remote_enable]       = 0
php_admin_value[xdebug.remote_autostart]        = 0
php_admin_value[xdebug.remote_host]         = localhost
php_admin_value[xdebug.profiler_enable_trigger]     = 0
php_admin_value[xdebug.remote_port]         = 9001
php_admin_value[xdebug.collect_params]      = 2
php_admin_value[xdebug.collect_vars]        = 1
php_admin_value[xdebug.trace_format]        = 2

Unfortunately, xdebug won't be loaded.
Is there any other option to load xdebug only on dev.* domains?

A: Unfortunately you can't load different modules or version of modules for each FPM pool. So far I've created multiple completely separate instances of PHP-FPM in similar situations.

A: Yes, but the extra pool also needs to run under a separate service. That service can use the same binaries, but needs its own conf files and (some) dirs. How to achieve this depends on your system and its service manager. I used this answer as a basis because I have systemd.

A: simplest is to create service in /etc/init/php-xdebug
start on runlevel [2345]
stop on runlevel [016]

# you can uncomment this with recent upstart
# reload signal USR2

pre-start script
mkdir -p /run/php
chmod 0755 /run/php
chown www-data:www-data /run/php
end script

respawn
exec /usr/sbin/php-fpm7.0 --nodaemonize --fpm-config /etc/php/7.0/fpm/php-xdebug.conf

A: XDebug in combination with PHP-FPM has one pitfall - option xdebug.mode can be set only in php.ini. But if you have one production and one staging site using the same php.ini and you want xdebug enabled for staging but disabled for production (cos of performance) you got a problem.
You can solve that by creating another php-fpm service (https://www.digitalocean.com/community/tutorials/understanding-systemd-units-and-unit-files) and in unit configuration you can set php.ini file which will be new ini file with xdebug enabled.
Then you just need to make sure that your debug requests point to this new php-fpm (which you can do by setting fpm pool's listening host and port).
Hope I left some clues for others struggling with xdebug, php-fpm and php.ini stuff...


text:
Q: Scala: Why lower bounds in existential type declaration not enforced? Assume the following declarations made into the Scala repl:
class Animal
class Bird extends Animal
class Chicken extends Bird
type SubType = t forSome { type t <: Bird }
type SuperType = t forSome { type t >: Bird }

As I expect, SubType is of a type that conforms to Bird.  Since Animal is a superclass of Bird, a variable of type SubType cannot hold value of type Animal:
scala> val foo: SubType = new Animal
<console>:10: error: type mismatch;
 found   : Animal
 required: SubType
       val foo: SubType = new Animal

and yet this corollary is not as I expect:
scala> val foo: SuperType = new Chicken
foo: SuperType = Chicken@1fea8dbd

The assignment succeeds, and so do these:
scala> val foo: SuperType = 2
foo: SuperType = 2

scala> val foo: SuperType = "wtf?"
foo: SuperType = wtf?

scala>

Again, here's SuperType:
type SuperType = t forSome { type t >: Bird }

According to SLS 4.3,

A type declaration type t [tps ] >: L <: U declares t to be an abstract type with lower bound type L and upper bound type U.

So I'm declaring t to be an abstract type with lower bound Bird.  Chicken is not a superclass of Bird, neither are String nor Int.
I thought that maybe it's because a Chicken is an Any and a SuperType can store an Any.  But if I change the declaration of SuperType to this:
type SuperType = t forSome { type t >: Bird <: Animal}

to set an upper bound of Animal nothing seems to change.
Questions
First
How are my assignments of values of types Chicken Int and String to a SuperType variable allowed by existential clauses { type t >: Bird } and { type t >: Bird <: Animal}?
Second
What is the significance of the word "abstract" in the quoted specification that "A type declaration type t [tps ] >: L <: U declares t to be an abstract type..."  What would the difference in meaning be if the word "abstract' were not there?

A: I think the confusion is between the use of the term "bound" and "constraint". The "<:" and ">:" syntax constructs are for specifying type constraints, not bounds. When you say
{ type t >: Bird }

you are merely constraining the type "t" such that inhabitants of that type must share a superclass with Bird. Since Chicken and Bird both extend Animal, the constraint is met, and Scala allows the assignment. This is also why your "bogus" assignments work (String and Int both share the superclass Any with Bird. The later constraint you proposed
{ type t >: Bird <: Animal }

properly restricts your examples of String and Int, as there exists no type in the type hierarchy of String or Int that meets the constraint of being a supertype of Bird while also being a subtype of Animal. However, that will still allow your initial assignment.
Edit: Other answers on SO say that both are called bounds. Shows how much I know. :)


text:
Q: ShareKit - sharing on Facebook still show the demo app I've got a problem in using the share kit function.
I've got a button and its IBAction like below.
But the problem is when I tab on button, it shows an ActionSheet with Facebook, Twitter and Pocket, I select Facebook, got authenticated, and then it redirects me to the ShareKit demo app!
- (IBAction)moreSharing:(id)sender {
{
// Create the item to share (in this example, a url)
NSURL *url = [NSURL URLWithString:@"http://www.mywebsite.com"];
SHKItem *item = [SHKItem URL:url title:@"Welcome to mywebsite"];

// Get the ShareKit action sheet
SHKActionSheet *actionSheet = [SHKActionSheet actionSheetForItem:item];

// Display the action sheet
[actionSheet showFromToolbar:navigationController.toolbar];
}

I have checked my Xcode project solution file and already removed and deleted the Examples folder. I have no idea where the demo app comes from.
Any idea?

A: Have you subclassed DefaultSHKConfigurator and edited the settings? You can find out how it's done in their documentation.

A: It seems that you use the ShareKit's demo app Facebook URL scheme for your app. You can see it in ShareKit-info.plist (and your app-info.plist). You should use your own app id from Facebook.


text:
Q: C#/XNA Why can't I add to the Array List? I'm having some trouble adding objects to an ArrayList. When attempting to add KeyboardController() and GamepadController() to the ArrayList, i'm told that ControllerList is a field, but it is being used as a type. Both of these classes implement the interface IController. Furthermore, I'm being told that both KC() and GC() must have a return type. Would anyone be able to let me know what is causing the problem. Is there a more proper way of doing this?
// Initialization

ArrayList ControllerList;
ControllerList.Add(new KeyboardController());  //error
ControllerList.Add(new GamepadController());   //error

IAnimatedSprite MarioSprite = new SmallMarioRunningRightSprite();

protected override void Update(GameTime gameTime)
{
    foreach(IController Controller in ControllerList)
    {
        Controller.Update();
    }

    MarioSprite.Update();

    base.Update(gameTime);
}

This specific section of code was provided to me by an instructor and I am unclear to why it isn't functioning properly.

A: You are trying to execute non-initializer code (the calls to ArrayList.Add) outside of a method body. This won't work.
You have to either use the collection initializer syntax
ArrayList ControllerList = new ArrayList
                               {
                                   new KeyboardController(),
                                   new GamepadController()
                               };

or do the initialization in the constructor of your class.
Also, don't use ArrayList if you don't have to. Use List<IController> instead.

A: You need to put the item adding code lines in a class constructor or a method.
ControllerList = new ArrayList();
ControllerList.Add(new KeyboardController());

and also you can't add items to not initialized (null) ArrayList , you only declare ControllerList as ArrayList but not initialized


text:
Q: Application Menu in different place after elevating privileges I am on Ubuntu 16.04. I have set my application menus (file, edit, view, help etc.) to be in window's title bar and always visible. (see here)
When I run applications like bleachbit or gedit or virtualbox in user mode, application menus show up correctly in window's title bar (as expected).

But when I open bleachbit or gedit or virtualbox with root privileges, application menus behaviour is not consistent.
1 : bleachbit as root shows application menus but it does not show them in title bar. It also shows window title Bleachbit in title bar which I don't want.

2 : sudo gedit completely removes the title bar. So no application menus.

3 : sudo virtualbox also displays application menus in wrong place. It also changes the scrollbar and font (looks more like windows 95 than ubuntu).

So I want to know if it is possible to get the application menus back to the title bar when using in root mode. If yes, how?
Note : I know the risk of running as gui programs root. Also the problem is not limited to these 3 programs specifically. Other programs such as synaptic package manager, wireshark have the same problem.


text:
Q: Class statements in python This code keeps on returning an error...object.init() does not have any perimeters.
class Car(object):
  def __init__(self,make,colour):
       object.__init__(self,make,colour)
       self.make = Ford
       self.colour = Black
  def display(self):
       print("Make:", self.make)
       print("Colour:", self.colour)
#main program
cObj1 = Car("Ford", "Black")
cObj1.display()

A: You are calling object.__init__(), but that method doesn't take any parameters:
object.__init__(self,make,colour)

Just remove that line, it is not needed at all. object.__init__ doesn't do anything, not calling it doesn't do any harm.
Next, you are ignoring the arguments, and are instead using the names Ford and and Black; those names are not defined in your code so that'll give you a NameError exception. Use make and colour instead:
def __init__(self, make, colour):
    self.make = make
    self.colour = colour


text:
Q: fnStandingRedraw shows no records in datatable plugin I am using jQuery datatable plugin to display a list of records on my page. I am getting all my data from the server side and handling paganation from the server side as well. I wanted that whenever I referesh the table the page state should be maintained. I use the following plugin to achieve this
oTable.fnStandingRedraw();

This works fine except if i am on the final page of the table and i delete all records from that page and call the fnStandingRedraw() function it shows that the table is empty and when clicking on the previous page it shows all records again.
here is the code for the fnStandingRedraw plugin that i am using
$.fn.dataTableExt.oApi.fnStandingRedraw = function (oSettings) {
if (oSettings.oFeatures.bServerSide === false) {
    var before = oSettings._iDisplayStart;

    oSettings.oApi._fnReDraw(oSettings);

    // iDisplayStart has been reset to zero - so lets change it back
    oSettings._iDisplayStart = before;
    oSettings.oApi._fnCalculateEnd(oSettings);
}

// draw the 'current' page
oSettings.oApi._fnDraw(oSettings);
};

Datatable Plugin Link

A: This is the correct behaviour. This script provide way to draw the table again with keeping filtering/sorting/pagination. So when you be on last page, delete all rows and call standing redraw, datatables stay on that last page and show nothing.
Of course you can try catch this situation by checking the current table lenght:
oTable.fnGetData().length

and if this piece of code return 0 you can call common redraw function:
oTable.fnDraw()


text:
Q: What is the proper way to fire an ASP.NET control event programatically? What is the proper way to fire an ASP.NET control event programatically?
I am looking to refactor a little code and I see items sprinkled in the code behind coded like this; the developer is calling the event handler and saturating it with params.
for a DropDownList
ddlAddress.SelectedIndex = 1;
ddlAddress_SelectedIndexChanged(null, new EventArgs());

&
for a RadioButtonList
rblAction.SelectedIndex = 0;
rblActionType_SelectedIndexChanged(null, new EventArgs());

Is this normal coding practice? What should I do as to not disrupt/break the page?
Any thoughts or suggestions would be appreciated.
Thanks,
~ck in San Diego

A: I would start by removing all of the code from the actual event's method and refactor it into a new method called AddressChanged or whatever else fits your naming standards.  You can then call that new function from anywhere else in your code.
protected void ddlAddress_SelectedIndexChanged(object sender, EventArgs e){
    AddressChanged();
}
private void AddressChanged(){
    //do the changed event
}

private void doingSomething(){
    ddlAddress.SelectedIndex = 1;
    AddressChanged();
}

A: Note that you're calling the event handler programatically, not the event.
This can be indicative of a design problem, because usually event handlers should not be relying on each other to execute in a specific order.   However, I have seen this pattern and even used it occasionally when code that existed in one event handler needed to be executed in another event handler and could not be refactored at that time. You can set the "sender" to indicate that it's coming from elsewhere in the code and not from the expected control itself, but this is a little bit too opaque to be called a good design.
It would be better practice to refactor out the code that needed to be shared, and put it in a private method, and have both event handlers use it, passing in whatever data from the sender or the eventargs that it needed.


text:
Q: Bootstrap 3 how to have buttons at same horizontal positions in different columns I am trying to put Three Columns- About, Services & Why_Us in One Row and having one "Button" for "Read More" Option in each column. I am trying to make these three buttons to have at same horizontal level. If i am defining height & position in CSS for columns & button, layout for these is getting distorted at different screen sizes. (like buttons overlapping the content). Please help to resolve.
Here is my Code:
CSS:

HTML

About Us

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source.

          <button type="button" class="btn pull-right btn-info">Read More</button>

Services

SERVICE-1

SERVICE-2

SERVICE-3

SERVICE-4

SERVICE-5

SERVICE-6

SERVICE-7

SERVICE-8

          <button type="button" class="btn pull-right btn-info">Read More</button>

Why Choose Us

Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

          <button type="button" class="btn pull-right btn-info">Read More</button>

Thanks

A: I think this would be suitable for you, assuming you want equal height columns also:

.intro_col {
  height: auto;
  background-color: #EEEEEE;
  margin: 30px 1.35%;
  padding-bottom: 60px;
  box-shadow: -8px 8px 0px 2px #E0E0E0;
}

#intro .btn-info {
  position: absolute;
  bottom: 4%;
  right: 4%;
}

.row-eq-height {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

About Us

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked
        up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source.

      <button type="button" class="btn pull-right btn-info">Read More</button>

Services

SERVICE-1

SERVICE-2

SERVICE-3

SERVICE-4

SERVICE-5

SERVICE-6

SERVICE-7

SERVICE-8

      <button type="button" class="btn pull-right btn-info">Read More</button>

Why Choose Us

Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line
        of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

      <button type="button" class="btn pull-right btn-info">Read More</button>


text:
Q: Count number of instances in Excel based on another cell I want to count the number of times a name appears with "Yes" in the next column.
Table sample:

A: The formula to use for that will be COUNTIFS, which lets you do a count based on multiple ranges and multiple criteria.
For your example the exact formula would be:
=COUNTIFS(B1:B1000,E1,C1:C1000,"Yes")

Where E1 is a cell with one of the names, and then E2 for the next name, and so on.
See sample here:

And here you could see the formulas:

A: You can use a PivotTable:

*

*Put headers on your 2 existing columns (e.g. "Name" and "Y/N")

*Add a 3rd Column "Count" and fill it with "1" all the way down

*"Insert" tab -> PivotTable. It should automatically select your data. Hit OK.

*In the "PivotTable Fields" sidebar: Drag "Name" to the Rows area, "Y/N" in Columns, and "Count" in Values


text:
Q: Changing the bounds of integration in the proof that normal distribution is a P.D.F Considering the following snippet:

I am unsure why the bounds of integration change to
$(0,\infty)$ and $(0, 2\pi)$.
Are we mapping $(- \infty, \infty) \rightarrow (0, \infty)$ since $r>0$ for any radius
and $(- \infty, \infty) \rightarrow  (0, 2\pi)$ since this assumes all values for the unit circle. Any simple clarifications much appreciated.

A: Yes it is right $r>0\in(0,+\infty)$ and $\theta$ is the angle and it takes all the values around a circle so $\theta\in [0,2\pi)$.

A: The transformation being used here is from Cartesian coordinates to polar coordinates.
That is, $r$ is the displacement length of the line segment from the origin $(0,0)$ to the point $(x,y)$, and $\theta$ is the angle between the $x$-axis and that line segment.
So integrating over all points in the interval of $]-\infty;\infty[^2$ is transformed to an integral over all points of any radius, ranging over $[0;\infty[$, and any angle in the range from $[0;2\pi[$.
$$\int_{-\infty}^\infty\int_{-\infty}^\infty g(x,y)\operatorname d y\operatorname d x = \int_{0}^\infty\int_0^{2\pi} g(r\cos(\theta), r\sin(\theta))\cdot r\operatorname d \theta\operatorname d r$$


text:
Q: Using javascript regexp to find the first AND longest match I have a RegExp like the following simplified example:
var exp = /he|hell/;

When I run it on a string it will give me the first match, fx:
var str = "hello world";
var match = exp.exec(str);
// match contains ["he"];

I want the first and longest possible match,
and by that i mean sorted by index, then length.
Since the expression is combined from an array of RegExp's, I am looking for a way to find the longest match without having to rewrite the regular expression.
Is that even possible?
If it isn't, I am looking for a way to easily analyze the expression, and arrange it in the proper order. But I can't figure out how since the expressions could be a lot more complex, fx:
var exp = /h..|hel*/

A: How about /hell|he/ ?

A: All regex implementations I know of will (try to) match characters/patterns from left to right and terminate whenever they find an over-all match.
In other words: if you want to make sure you get the longest possible match, you'll need to try all your patterns (separately), store all matches and then get the longest match from all possible matches.

A: You can do it. It's explained here:
http://www.regular-expressions.info/alternation.html
(In summary, change the operand order or group with question mark the second part of the search.)

A: You cannot do "longest match" (or anything involving counting, minus look-aheads) with regular expressions.
Your best bet is to find all matches, and simply compare the lengths in the program.

A: I don't know if this is what you're looking for (Considering this question is almost 8 years old...), but here's my grain of salt:
(Switching the he for hell will perform the search based on the biggest first)
var exp = /hell|he/;
var str = "hello world";
var match = exp.exec(str);

if(match)
{
  match.sort(function(a, b){return b.length - a.length;});
  console.log(match[0]);
 }

Where match[0] is going to be the longest of all the strings matched.


text:
Q: Is there any way to enable extensions or features after an instance/device is created? I'm doing some wrapper job with Vulkan, to make the API more safe, and I wondered if I can create an instance or device first, and enable extensions or features later.
First, according to the spec:

VUID-VkDeviceCreateInfo-pProperties-04451
If the VK_KHR_portability_subset extension is included in pProperties of
vkEnumerateDeviceExtensionProperties, ppEnabledExtensionNames must
include "VK_KHR_portability_subset"

This looks fine, but notice that to enable VK_KHR_portability_subset extension on a device, you must enable its dependency VK_KHR_get_physical_device_properties2, which is an instance extension. This makes the fact that an instance must enable VK_KHR_get_physical_device_properties2 anyway in case the 04451 will check when a device is creating.
Secondly, it will be convenient to enable features later, for example if a user passed some parameter in, which requires some features, I can implicitly enable them for this user.

A: Features and extensions are specified at creation time. They're an innate part of the instance or device from that point forward. They cannot be modified later.
You can create new instances or devices. But you can't change existing ones.