Wolfram Alpha unexpected answer.

Question: http://www.wolframalpha.com/input/?i=5+%2B+%286.7a%29%2B+%28a+%5E+0.8%29
What does "imaginary part" mean?
Comment: http://en.wikipedia.org/wiki/Complex_number
Answer: Some equations, like $x^2+1=0$ for instance, have no solutions in the real numbers. You may have heard things that allude to this in your education so far—perhaps you've heard it said that the polynomial $x^2+1$ has no real roots, perhaps implying that it may have solutions that are "not real". The same types of equations may have solutions in a different number system called the complex numbers. The complex numbers are a number system in which negative numbers have square roots, and often they are defined in terms of a number $i=\sqrt{-1}$ known as the imaginary constant. We may then write any complex number in the form $a+bi$ where $a$ and $b$ are real numbers, and we say that the number $z=a+bi$ has real part $a$ and imaginary part $b$. So, for example, $i$ has real part $0$ and imaginary part $1$, and is a solution of the equation I mentioned at the start:$$i^2+1=-1+1=0$$
So when you give Wolfram Alpha certain types of polynomials or equations, it checks for solutions in the complex numbers as well as in the real numbers since often there will be complex solutions but not real solutions to a given equation.
Answer: Imaginary numbers are those which are defined as the following:
$$\sqrt{-1} = i$$
In yours it says $0i$ which just evaluates to $0$, essentially there is no imaginary part.
Wolfram Alpha is putting it in a form called Complex Numbers. These have an imaginary and real part, and are defined as: $a+bi$. If the imaginary part is equal to $0$ then you are essentially left with a real number.
Comment: Thanks Link. I will accept it as soon as possible. (8 mins left)
Comment: @user117031 No problem! Glad to be of help.

Wolfram Alpha unexpected answer.


Rules: Send mail to author when value in date field has passed

Question: So, I have a content type "contest" which has an "end date" field. I want to setup rules so the author of a "contest" gets an e-mail as a reminder that the contest ended.
As event I used "Cron maintenance tasks are performed" and as condition I try to use "Data Comparison" to check the value of the end date to be smaller than current site time. The problem is I can't use the token of the "end date" field as my event is not node-related. I tried to add a "Content is of type" condition, but also here, I can't select anything node-related.
I feel like overlooking something small but I've been searching now several hours and could use some help..
Answer: Assuming you are using Drupal 7.
You need to enable the Rules Scheduler module, it comes with Rules.
Then for Rule event use After saving new content.
Add condition, content is of type: Contest
Exit out of your Rule, and now create a Rule Component of Data Type: Node
Add condition, content is of type: Contest
Action Send E-mail.
Now exit the component and go back to your rule, for action, schedule rule component, and use your end-date field for schedule evaluation date.
I highly suggest you watch Introducing Rules Scheduler and I am sure my answer will make more sense to you.
Comment: Thanks a lot for the help. It's an interesting tutorial. I have to do some testing but it seems that Rules scheduler can achieve what I am looking for.
Answer: To further complete the previous answer, you may also want to look at the answer to "Rule to store user's last post date and scheduled rule based 30 day reminder" (which is a variation of your question here).
It includes a Rules Component (in Rules export format) which, with some minor tweaking, should work for you also. And it includes a Rule (also in Rules export format) that schedules the Rules Component. Just replace the field_next_article by your node's field date and you should be close. And replace the Rules Event and/or Condition(s) with what fits for your case.
Also note that this Rule takes care of "rescheduling" such eMail in case the data field gets updated somehow ...


JsonEditor integration with Django Admin

Question: I am working on integrating JSONEditor into the Django admin.  There is one field in my model that uses the Postgres JSON and the Tree editor in this library is perfect.
models.py
class Executable(models.Model):
    """ Simplified model for sake of the question."""

    recipe = JSONField(null=True, blank=True)

I've made decent progress (I think) integrating the JSONEditor library within the appropriate create/edit screen in the Django Admin. The data is displayed correctly upon loading but for some reason when I make edits within the JSONEditorWidget the changes are not saved.  I'm sure there is some save override that I need to work on, or that I'm missing something obvious, but I'm really not sure where to go from here.
admin.py
import json
from django import forms, utils
from django.contrib import admin

from .models import Executable

class JSONEditorWidget(forms.Widget):
    html_template = """

        <textarea readonly class="vLargeTextField" cols="40" id="id_%(name)s" name="%(name)s" rows="2" height="20px">%(value)s</textarea>
    """
    def __init__(self, attrs=None, formats=None, defaults=None):
        self.formats = formats
        self.defaults = defaults
        super(JSONEditorWidget, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        if isinstance(value, basestring):  # Edit existing instance
            value = json.loads(value)
        result = self.html_template % {
            'name': name,
            'value': json.dumps(value)
        }
        return utils.safestring.mark_safe(result)

class ExecutableForm(forms.ModelForm):
    recipe = forms.CharField(widget=JSONEditorWidget())    # Kwargs here?

    class Meta:
        model = Executable
        fields = '__all__'

    class Media:
        css = {
            'all': ('http://www.jsoneditoronline.org/app.min.css',)  # TEMP
        }
        js = (
            'http://www.jsoneditoronline.org/app.min.js',   # TEMP
            )

class ExecutableAdmin(admin.ModelAdmin):
    model = Executable
    form = ExecutableForm
    fields = (('request', 'status'), 'recipe')

admin.site.register(Executable, ExecutableAdmin)

Comment: @e4c5 The library is well-documented and available on Github. What makes you think it is not? Btw, I'm still a novice programmer so maybe I've missed something :)
Comment: I am sorry I misunderstood, i had not used this library before but upon visit to the site there were no visible developer or github links
Comment: @e4c5 no worries, the link is buried in the footer and I could see how you could come to that conclusion. I've updated the link in my post to point to the GitHub repo and not the demo site ( https://github.com/josdejong/jsoneditor/ )
Answer: My solution for Django 1.10.2, jsoneditor#^5.5.9, Postgres 9.5:
models.py
from django.contrib.postgres.fields import JSONField

class Consumer(models.Model):
    data = JSONField(default=dict, db_index=True)

admin.py:
from django import forms
from django.contrib import admin
from django.utils.safestring import mark_safe
from django.template.loader import render_to_string

from .models import Consumer

class JSONEditorWidget(forms.Widget):

    template_name = 'jsoneditor.html'

    def render(self, name, value, attrs=None):
        context = {
            'data': value,
            'name': name
        }

        return mark_safe(render_to_string(self.template_name, context))

class ConsumerForm(forms.ModelForm):

    class Meta:
        model = Consumer
        fields = '__all__'
        widgets = {
            'data': JSONEditorWidget()
        }

    class Media:
        css = { 'all': ('jsoneditor/dist/jsoneditor.min.css',) }
        js = ('jsoneditor/dist/jsoneditor.min.js', )

class ConsumerAdmin(admin.ModelAdmin):
    list_display = ['pk']
    model = Consumer
    form = ConsumerForm

admin.site.register(Consumer, ConsumerAdmin)

jsoneditor.html:

<textarea cols="40" id="id_{{ name }}" name="{{ name }}" rows="10" required="" style="display: none">{{ data }}</textarea>

Blockquote
  Written with StackEdit.
Comment: Sorry but this didn't work perfectly for me. I had to add minor tweaks esp. converting json text to json `var json = JSON.parse({{ data|safe }});` and renaming `onChange` to `change`.  Following is the updated gist https://gist.github.com/rgupta2/761fd987254703673d83426912dc015d
Comment: I have been looking for something like this for a while now... thanks


How can I detect when a node is changed from 'Published' to 'Unpublished'?

Question: In hook_node_update(), I can easily tell the 'status' of a node (whether it's published or not) after it's been updated.
However, is there an easy way to check to see if the updated node was published, but now is not? (Or vice-versa)?
I think Rules might have some condition for 'node value has changed' or something along those lines, but I'd like to do this programmatically.
I found this issue by fago (developer of Rules) on drupal.org that seems to deal with this in Drupal 7, but a nice explanation would be appreciated.
Answer: Nevermind. After reading through the issue linked above (especially comment #38), I found that the $node object (any entity, actually) stores the 'original' cached copy in $entity->original.
So, I wanted to detect whether a node changed from 'status = 1' to 'status = 0' (this happens when the node is unpublished), and the following code does this:
<?php
function custom_node_update($node) {
  if ($node->type == 'article') {
    // Act on the unpublishing of an article.
    if ($node->original->status == 1 && $node->status == 0) {
      // Do something here.
    }
    // Act on the publishing of an article.
    if ($node->original->status == 0 && $node->status == 1) {
      // Do something here.
    }
  }
}
?>

Comment: why? It was still helpful to me, worth a +1 ;-)
Comment: I've gotta stop answering my own questions ;-)
Comment: Heh, this is about the 10th time I've landed on my own answer in Google results. Future me thanks past me for answering :)
Comment: Above code is not going to work if you are using revisioning module
Comment: For the record, this could not be not working for status + workflow + translation, I had to use `$entity->original->getTranslation($lng)->status->value == 0 && $entity->getTranslation($lng)->status->value == 1`
Answer: node_save() contains the following code.
  try {
    // Load the stored entity, if any.
    if (!empty($node->nid) && !isset($node->original)) {
      $node->original = entity_load_unchanged('node', $node->nid);
    }
  }

entity_load_unchanged() loads the entity (in this case the node) from the database; it returns the entity object before any changes made from the running modules.
The code is executed before any pre-save, and update hooks.
module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');

//...

node_invoke($node, $op);

// Save fields.
$function = "field_attach_$op";
$function('node', $node);

module_invoke_all('node_' . $op, $node);
module_invoke_all('entity_' . $op, $node, 'node');

In those hooks, it is possible to see the node properties before any change in $node->original, for example with $node->original->status.


How to pass enum in Mutation using graphql in Flutter?

Question: mutation{addOrder (create:{ offerId:2,paymentType:PaymentType!})
{
id
}
}
Here is my code .here PaymentType is a enum.
Comment: pass it as normal string
Answer: since you have the PaymentType you can use it normally , example:
PaymentType =enum {"visa" ,"masterCard"}

you have to passe the variable in you flutter end which corresponds to one of these two anyother value will generate an error
the variables should be something like this :
variables :{offerId:2,paymentType:"visa"}


Exchange regenerating calendar cancelation email over and over

Question: Today, at about 9:30am, one of our users deleted a repeating calendar entry from a public calendar on our Exchange 2003 server (using Outlook 2007 on Windows XP).  He chose to have the cancellation sent via email to the meetings 2 attendees.  The calendar event had been repeating weekly since 2007 and was scheduled to continue repeating weekly.  I do not know the end date of the recurring event.
The event has been successfully removed from the calendar, but Exchange is sending groups of 28 meeting cancellation notices every 5-10 minutes to the two attendees.  This has been happening for 2 and a half hours.
I have restarted the Exchange server as well as the user's computer.  There are no outstanding messages in any queue on the Exchange server.  When using the Message Tracking Center tool, you can see that the messages are delivered immediately.  This explains why there is nothing in the queue.  Something is regenerating the cancellation notices every 5 minutes or so and sending them out in batches of 28 emails at a time.
I'm new to this site, but if anyone has any suggestions, I'd really appreciate them!
Comment: Update.  It appears the Exchange server is resending the 28 meeting cancellation notices whenever the user deletes the first 28.  If he doesn't delete the notices, all is good (which is the solution for now).  Still seems weird.
Answer: Try poofing the calendar
Comment: Thank you!!!  I did this, which caused me to see some additional occurrences of the deleted entry on the calendar.  Deleted those, and voila!  I can delete the 28 emails and they don't come back.  Thank you!


Reproducing kernel Hilbert space of set functions

Question: Let $\Omega$ be a finite set. Can we construct a reproducing kernel Hilbert space (RKHS) of real-valued functions $2^\Omega \to \mathbb{R}$? If so, how can we construct one and how is the kernel defined?
Thank you!
Comment: The set $2^\Omega$ is finite, so the RKHS is just the finite dimensional space $\mathbb{R}^{2^\Omega}$ with the usual inner product?
Answer: If you let $X = 2^\Omega$, then the space of real valued functions on $X$ is basically $\mathbb{R}^n$ for $n = |2^\Omega|$. Indeed, you equip it with the standard dot product to get a Hilbert space. From there, you quickly see that the evaluation functionals $T_x(f) := f(x)$ are all continuous (linear maps from finite dimensional vector spaces are always continuous). Hence $\mathbb{R}^n$ is a RKHS. Note also that $T_x(f)$ is basically a projection. So, for example, if $\Omega = \{1\}$ and we allow ourselves to forgo function notation to instead work directly with $\mathbb{R}^2$, we get $T_\emptyset((x,y)) = x$ and $T_{\{1\}}((x,y)) = y$. It's probably time to note the notational convenience of using natural numbers as the base set $X$. Indeed, $T_1$ looks better than $T_\emptyset$.
So, how does the kernel of standard Euclidean $n$-space look like?
Simple, $K(x,y) = \langle K_x, K_y \rangle$, where $K_x$ is the vector/function in our space that represents $T_x$ in the sense that $T_x(f) = \langle f, K_x \rangle$. In our case, $K$ is a function from $\{1,2\}^2$ to $\mathbb{R}$ so that we must define $K(1,1), K(1,2), K(2,1),$ and $K(2,2)$. For that, note $\langle (1,0), (x,y) \rangle = x$ and $\langle (0,1), (x,y) \rangle = y$ so that the canonical vectors $e_1$ and $e_2$ are, respectively, $K_1$ and $K_2$. From here, you only need to compute four (three if you are smart) inner products, and you're done.
Comment: So a RKHS $H$ of functions $X \to \mathbb R$ is finite-dimensional if and only if $X$ is a finite set and in this case, $H = \mathbb R^{| X |}$?


Detect file type in a directory/folder

Question: I would like to ask how to know the file/files types in a directory/folder using Java.
The reason for asking is that currently, I have one situation in which there will be 2 different types of files exists in the folder,  which one is java based and another one is python.
I would like to use Java as a language to check whether the type file in the unzipped folder is python(.py) or java(.java) programmatically.  Do you know how to make this work? any suggestion?
There is no possibility to have both types of files in the same folder.  That being said, the file either will be all in java or all in python.
Comment: Have you tried to do this in Java? It is not that hard to look through all the files and find their extensions.
Comment: This can be a start: [Listing files in a directory matching a pattern in Java](//stackoverflow.com/q/2102952)
Answer: This can achieved by using the listFiles method .
One way
File [] files = folder.listFiles(f-> f.toString().endsWith(".java"));

With python extension
File [] files = folder.listFiles(f-> f.toString().endsWith(".py"));

Or a better solution creating a method with a parameter so you can after use it every time you need it by just calling it
public File [] returnFiles(File folder,String extension){

        return folder.listFiles(f-> f.toString().endsWith(extension));
    }

EDIT
You guaranteed me that the folder will have only the file of Java or Python so when we are listing all the files in our File [] files array this array will contain java files or python files so there is no need to check them all we check only one file in this array
Example
File[] files = file.listFiles(f -> f.isFile());

        File  fileToCheck;

        if (file.length() >= 0) {
            fileToCheck = files[0];
            int index = fileToCheck.toString().lastIndexOf(".");
            String extension = fileToCheck.toString().substring(index + 1);
            if(extension.equals("java")) {
                System.out.println("Java FrameWork");
            }else if(extension.equals("py")){
                System.out.println("Python FrameWork");
        }

    }

    }

}

Comment: Thanks a lot, Typhon, for the really useful information.   In my code,  the folder instead of using File,  we are using a String(folder name basically).  In this case, how to use them if/else or try/catch by using the approach you suggested? Kind regards
Comment: What do you want to check with if conditions?
Comment: something like if there are .java files in the folder, return "java framework",  else if there are .python then return "python framework"
Comment: @Ken check it out.

Detect file type in a directory/folder


TypeError: FUNCTION NAME () missing 1 required positional argument: 'v_air

Question: I have two problems:

When I call the functiuon Python says that I miss one positional argument of the function simplified_friction_method but all the arguments are written above.

If your str() or list() objects might end up being empty as so: astr = '' or alist = [], then you might want to use alist[-1:] instead of alist[-1] for object "sameness".
some_list = [1, 2, 3]
some_list[-1] = 5 # Set the last element
some_list[-2] = 3 # Set the second to last element
some_list
a_list = ['zero', 'one', 'two', 'three']
a_list[-1]
'three'

Comment: Please show the full traceback. You seem to be calling the function with the correct number of arguments in the last line you showed, so the error may be coming from somewhere else.
Comment: Please show a [mre], which includes the context of the definition of `simplified_friction_method`.
Comment: `TypeError: simplified_friction_method() missing 1 required positional argument: 'v_air` I would guess this is because you defined the function outside the `Duct` class. Once you pass an additional argument, the first argument you pass `duct_circ.V_dot`, which is a `np.ndarray` is passed as self, and thus you get `AttributeError: 'numpy.ndarray' object has no attribute 'rho_air'`
Comment: Is `simplified_friction_method` inside the class that `EN` is an instance of?
Comment: EN is the Engine another file and I call the file that has all the function in this way:
 import ENGINE as EN
Comment: Maybe they made `simplified_friction_method` static by accident?
Comment: @mapf I do not know what do you mean with static, so the only way is to define the attributes in class, also all the other input?
Comment: Don't worry, I was wrong. But now that you have changed the definition of your `simplified_friction_method` I think you shouldn't run into any more problems.
Answer: Look, you basically already had it right but just for the record, here is the working code:
import numpy as np
from scipy.optimize import root

def viscosity(Tair_inlet):
    mu=(1.458*(10**-6)*(Tair_inlet+ 273.15)**1.5)/((Tair_inlet+ 273.15)+110.4)
    return mu

def per_circ(D_1):
    p_c = np.pi*(D_1)
    return p_c

def Tair_outlet(Ts_int,Tair_inlet, hint, p_c, v_air, rho_air, cp_air, L ):
    k = hint/(p_c*v_air*rho_air*cp_air)
    Tair_outlet = Ts_int + (Tair_inlet-Ts_int)*np.exp(-k*L)
    return Tair_outlet

def simplified_friction_method(V_dot, rho_air , L, mu, delta_P, v_air, epsilon ):
    m_dot = V_dot * rho_air
    print('m_dot',m_dot, '[kgs^-1]')
    D_0 = (4*m_dot/(np.pi*rho_air*v_air))**(1/2)
    D_1 = D_0
    print('D_0',D_0, '[m]')
    Re  = (v_air * D_0 * rho_air) / mu
    print('Re', Re )
    f_0= 0*D_0
    f_0 = (-2*np.log((epsilon/D_0)/3.7065))**-2
    print('f_0', f_0,)
    delta_P_tot = delta_P*L
    f_1 = f_0
    f_2 = 0
    e =np.ones(D_0.size)
    print("e",e)
    while e.any() > 0.0001:
        D_1 = ((f_1 * L)/delta_P_tot )* rho_air *(v_air)**2
        print('D_1', D_1, '[m]')
        Re  = (v_air * D_1 * rho_air) / mu
        f_2=(-2*abs(np.log((epsilon/D_1)/3.7065 + 2.5226/(Re*np.sqrt(f_1)))))**-2
        e = abs(f_1-f_2)
        print('e', e, )
        f_1 = f_2
    return('D_1', D_1,'Re', Re,'f', f_2,'e', e )

class Duct:
    def __init__(
        self, Tair_inlet, Ts_int, hint, cp_air, rho_air, Rstar, epsilon
    ):
        self.Tair_inlet = Tair_inlet
        self.Ts_int = Ts_int
        self.hint = hint
        self.cp_air = cp_air
        self.rho_air = rho_air
        self.Rstar = Rstar
        self.epsilon = epsilon

duct_ret = Duct(18, 19.5, 3, 1010, 1.2, 8324.68/29, 0.2/1000)
duct_circ = Duct(18, 19.5, 3, 1010, 1.2, 8324.68/29, 0.2/1000)

duct_ret.L = 8
duct_circ.L = np.array([[10, 8, 10, 8]])
duct_circ.V_dot = np.array([[3, 1, 2, 1]])
duct_circ.v_air = np.array([[5, 3, 5, 3]])
duct_circ.deltaP = 1

duct_circ.mu = viscosity(duct_circ.Tair_inlet)
print(duct_circ.mu)

duct_circ.D_1 = simplified_friction_method(
    duct_circ.rho_air, duct_circ.V_dot, duct_circ.L, duct_circ.mu,
    duct_circ.deltaP, duct_circ.v_air, duct_circ.epsilon
)

print(duct_circ.D_1)

Note that since I don't have two files, I don't import EN and thus removed the EN. in front of the function call. I also added the epsilon parameter to the Duct class which was missing in your version and passed it to the simplified_friction_method function. There are many ways how you could improve the code, but for now I think it's more important that it works and you understand it. You obviously don't really know how Classes work, so I would suggest you look into that.


How Interrogate Variables Higher in Calling Stack (without Passing Arguments)?

Question: In Python 3.6.x, and above, is there a way to reference (interrogate) a local variable contained in a function that is higher in the calling stack than the function that needs to perform an interrogation—without passing the variables as arguments?
For example:
def lowest_leaf():
    #Is there a way to access a_value and/or b_value
        #from lowest_leaf() WITHOUT passing them as arguments into
        #this function?
    #HERE: print(a_value)
    #HERE: print(b_value)
    return(0)

def middle_leaf(a_value):
    print(a_value)
    b_value = a_value * 2
    lowest_leaf()
    return(0)

def root_leaf():
    a_value = 10
    middle_leaf(a_value)
    return(0)

if '__name__' == '__main__':
    root_leaf()

Many, many thanks for your assistance!
Comment: Functions should not be dependent on being called from specific functions. You shouldn't require the calling function having variables with specific names. I agree, everything that the function needs should be passed as parameters.
Comment: Making all functions uselessly return 0 and refusing to pass arguments demonstrates a misunderstanding of the fundamentals of functions.
Comment: You can use call-stack inspection, but **you really shouldn't be doing that here**. Essentially, you would be (hackily) creating dynamic scoping, but why? Just pass the values as arguments to your function. That is *the way to do this*.
Comment: Likely not without doing something super sketchy. Why note just pass the data? That seems entirely possible here, and will make your code much cleaner.
Comment: You could also define `lowest_leaf()` as a nested function inside `middle_leaf()`. Then it can access the outer variables.
Comment: Yes, why are your functions returning `0`? Yu never do anything with the return value.
Answer: I would emphasise that this is generally a dodgy thing to do because it breaks encapsulation, as noted in the comments. Unless you have a very good reason for doing this (and if you need to think whether you do, you don't), I would suggest redesigning your application.
Nevertheless, Python is built around the idea that we are all consenting adults, and consequently you can do what you want with inspect:
import inspect

def lowest_leaf():
    middle_leaf_frame = inspect.currentframe().f_back
    print(middle_leaf_frame.f_locals)
    root_leaf_frame = middle_leaf_frame.f_back
    print(root_leaf_frame.f_locals)

def middle_leaf(a_value):
    b_value = a_value * 2
    lowest_leaf()

def root_leaf():
    a_value = 10
    middle_leaf(a_value)

root_leaf()

Output:
{'a_value': 10, 'b_value': 20}
{'a_value': 10}

Comment: @Carcigenicate I agree fully, but I am not sure that the experience/inexperience of the question's asker should affect whether the question should be answered. If someone who honestly really needed this performed a search and came to this question, I'd think they'd want a solution. (I bolded "don't" for more emphasis)
Answer: Not sure if this is super helpful but this is the only way I see the objective being achieved.
Basically we define a class.
class tree:

    def __init__(self):
        pass

    def lowest_leaf(self):
        #Is there a way to access a_value and/or b_value
            #from lowest_leaf() WITHOUT passing them as arguments into
            #this function?
        #HERE: print(a_value)
        #HERE: print(a_value)
        print(self.a_value)
        print(self.b_value)
        return(0)

    def middle_leaf(self,a_value):
        self.b_value = a_value * 2
        self.lowest_leaf()
        return(0)

    def root_leaf(self):
        self.a_value = 10
        self.middle_leaf(self.a_value)
        return(0)

tree1 = tree() # we define the tree here
tree1.root_leaf() # we can run any method we want.

OUTPUT:
10
20


Show the inequality $P[|S_n-mn| \ge n \epsilon] \le \frac{ σ ^2}{n \epsilon^2}$

Question: Show the inequality $P[|S_n-mn| \ge n \epsilon ] \le \frac{ σ ^2}{n \epsilon ^2}$ for every $ \epsilon>0$ where
$S_n = X_1+...+X_n$ and $X_i$ are independant random variables under the same law. Also $m=E[X]$, $σ=Var[X]$
I think that i need to apply Chebyshev's inequality but i am not sure how...
Comment: Is $E[X_i] = m$ and $\text{Var}[X_i] = \sigma^2$?
Comment: @JimmyK4542 Yes, edited now, sorry.
Answer: Hint: Rewrite the statement you wish to prove as "$P\left[\left|\dfrac{1}{n}S_n - m\right| \ge \epsilon\right] \le \dfrac{\sigma^2/n}{\epsilon^2}$ for every $\epsilon > 0$".
Now, can you compute the mean and variance of $\dfrac{1}{n}S_n$?
Comment: If $\alpha$ is a constant, then $\text{Var}[\alpha X] = \alpha^2\text{Var}[X]$. Also, if $X$ and $Y$ are independent, $\text{Var}[X+Y] = \text{Var}[X]+\text{Var}[Y]$. Those two facts should be enough for you to compute the variance of $\tfrac{1}{n}S_n$.
Comment: The mean will be still $m$ but why will the variance become $\sigma^2/n$?


Intersection of unbounded decreasing open sets is closed?

Question: Suppose $X$ is a Polish space. For any real number $c$, let $(c_n)$ be a convergent sequence that converges to $c$ such that $c < c_n$ for all $n$.
For each $n \in \mathbb{N}$, denote $A_n = (-\infty,c_n)$. Is it true that $f^{-1}(-\infty,c] = \cap_{n \in \mathbb{N}} f^{-1}(-\infty,c_n)$ is closed, where $f:X\rightarrow \mathbb{R}$ has the property that for any real number $d$, its pre-image $f^{-1}(-\infty,d)$ is open in $X$?
Comment: $\varnothing$ is open.
Comment: Second: For an increasing sequence $(c_n)$ converging to $c$ it does not hold $$f^{-1}(-\infty,c] = \cap_{n \in \mathbb{N}} f^{-1}(-\infty,c_n)$$ so your you start with a wrong assumption.
Comment: @Gono: I am assuming the sequence is decreasing to $c$.
Comment: Ah, I haven't seen that, sry.
Answer: A counterexample for both open and closed is
$$\bigcap_{n=1}^{\infty} \left( (-\tfrac{1}{n}, \tfrac{1}{n}) \cup (2,3) \right) = \{ 0 \} \cup (2,3) $$
Comment: What is your $A_n$?
Comment: @Idonknow: I don't have any $A_n$: I'm responding to your question "Is the intersection of decreasing open sets closed?"
Comment: But my question restrict open sets to be unbounded.
Comment: Then use $(2,\infty)$ rather than $(2,3)$.


Interval of convergence of a Laplace-Stieltjes transform

Question: I have a two-sided Laplace-Stieltjes transform,
$$
\int_{-\infty}^{+\infty} e^{-xt}d\mu(t)
$$
that converges absolutely in $(a,b)$.
If the measure $\mu$ is finite,then
$$
\int_{-\infty}^{+\infty}d\mu(t)=\mu(\mathbb{R})<\infty
$$
can I conclude that $(a,b)$ MUST contain the origin?
In general, how changes the interval of convergence of a two-sided Laplace-Stieltjes transform with respect to $\mu$?
Thank you
Answer: In case $\mu$ is finite positive, let us consider its normalization $\mu'(\cdot):=\mu(\cdot)/\mu(\Bbb R)$ which is clearly a probability measure on reals. As a result,
$$
  f_\mu(x):=\int_\Bbb R\mathrm e^{-xt}\mu(\mathrm dt) = \mu(\Bbb R)\int_\Bbb R\mathrm e^{-xt}\mu'(\mathrm dt) = \mu(\Bbb R)f_{\mu'}(x)  = \mu(\Bbb R)m_{\mu'}(-x).
$$
where $m_{\mu'}$ is a moment-generating function (MGF) of the distribution $\mu'$. Clearly, the LHS is finite iff the RHS is, so that your question for positive finite $\mu$ is equivalent to studying the properties of MGF and in particular of heavy-tailed distributions. Note, the clearly $m_{\mu'}(0) = 1$ regardless of $\mu'$, but it does not have to exist anywhere else, e.g. if $\mu'$ is Cauchy distribution.
Comment: Thus, $\mu$ is positive and finite iff $(a,b)$ contain the origin?
Comment: @alexou No, $\mu$ is finite iff the integral converges for the origin (trivial). However, even if $\mu$ is finite and positive, the integral may not converge anywhere else.
Answer: Even if $\mu$ is not a positive measure, its total variation measure $|\mu|$ is, and  "the integral converges
absolutely" means $\int_{\mathbb R} e^{-xt}\ d|\mu|(t) < \infty$.
Now $\int_{A} e^{-xt}\ d|\mu|(t)$ is a convex function of $x$ for every measurable $A \subseteq \mathbb R$, so the set where this is finite is a convex set, i.e. an interval.  If $\mu$ is a finite measure, that says $\int_{\mathbb R} e^{-xt}\ d|\mu|(t) < \infty$ for $x=0$, so $0$ is in the interval.
Note, however, that the interval doesn't have to be open.  For example,
take the measure with density $1/x^2$ for $x > 1$, $0$ elsewhere: this has interval $[0,\infty)$.
Comment: Do you know if is it possible to prove analyticity of the laplace-stieltjes transform for a $\mu$ non-finite? Eventually, do you have some references?
Comment: If $\int_{\mathbb R} e^{-xt}\ d|\mu|(t)$ converges for $x \in (a,b)$, then $\int_{\mathbb R} e^{-zt}\ d\mu(t)$ should be analytic in $a < \text{Re}(z) < b$, as this will be the limit of $\int_{-R}^R e^{-zt}\ d\mu(t)$ as $R \to \infty$, and convergence will be uniform on $c \le \text{Re}(z) \le d$ if $a < c < d < b$.


Injective map from $\mathbb{R}^2$ to $\mathbb{R}$

Question: Can anyone give an example of an injective map from $\mathbb{R}^2$ to $\mathbb{R}$? Clearly, such a map cannot be continuous (for instance by Borsuk-Ulam Theorem).
Thanks in advance.
Answer: How about this construction: Express $(x,y)\in\mathbb{R}^2$ in decimals ($x=\sum a_k 10^k$, $y=\sum b_k 10^k$) and define the image of $(x,y)$ as the real number which you obtain by interlacing the decimals (i.e. take $c_{2k} = a_k$ and $c_{2k+1} = b_k$).
Comment: I think a bit of care needs to be taken in that you'll want to take decimal expansions that don't end in a repeated trail of nines, otherwise $(1,1)$ will go to 1, but $(1,0.\overline{9})$ would go to $1.\overline{90}$.
Comment: I rolled back because: (1) this edit was **far** from being an actual edit. It was a comment at best, I personally found it content altering; (2) the notation in the post was that $(a,b)$ is an ordered pair, adding $(0,1)$ as an interval makes it harder and much less clearer.
Comment: Very good idea, thanks!
Answer: Hopefully this answer complements Dirk's direct answer. I use the fact that $\mathbb R$ has the same cardinality as $2^{\mathbb N}$ (and hence $\mathbb R^{2}$ has the same cardinality as $2^{\mathbb N} \times 2^{\mathbb N}$). Our goal, then, is to establish an injective function from $2^{\mathbb N} \times 2^{\mathbb N}$ to $2^{\mathbb N}$.
Given $S, T \subseteq \mathbb N$, consider the set:
$$
R := \{2x \,:\, x \in S\}\ \cup \ \{ 2y+1 \,:\, y \in T \}.
$$
Given the set $R$, it is easy to "decode" the sets $S$ and $T$. (Hint: Consider the odd and even elements of $R$.) Therefore the mapping $(S,T) \mapsto R$ as above is injective.
Comment: This map is also surjective, and continuous at least under the trivial topology :-)
Answer: One can also consider space-filling curves.  Since there's an onto map from $[0,1]$ to $[0,1]\times [0,1]$, it follows that $\vert[0,1] \vert \geq \vert [0,1] \times [0,1] \vert$.  Of course, the other inequality clearly holds (via the mapping $x \mapsto (x,0)$), hence $\vert [0,1] \vert = \vert [0,1] \times [0,1] \vert$.  Finally, since $\vert [0,1] \vert = \vert \mathbb{R} \vert$, we have $\vert \mathbb{R} \vert = \vert \mathbb{R}^2 \vert$.
Answer: let x_n be the n'th term any unique continued fractional expansion for x.
Then $z(a,b)=\sum (1/(2n)^{1/a_n}+1/(2n+1)^{1/b_n}$)
bonus:
By the Lindemann–Weierstrass theorem
$z=\sum (e^{-pi/a_n}+\pi^{-e/b_n}$)
Comment: I am unable to follow the example. Can you explain why this function is injective?
Comment: @SrivatsanNarayanan because these quantities are linearly independent over the rationals


Xamarin Forms Layout create overlapping views

Question: I am trying to create an Autocomplete control in Xamarin.Forms, so far I have created a ContentView with following Xaml.
<ContentView.Content>
        <AbsoluteLayout BackgroundColor="Red" x:Name="absLayout" HeightRequest="30">
            <Entry BackgroundColor="Green" x:Name="entryView" AbsoluteLayout.LayoutBounds="1,1,1,1" AbsoluteLayout.LayoutFlags="All" Focused="Handle_Focused" Unfocused="Handle_Unfocused"/>
            <ListView BackgroundColor="Blue" Margin="0,30,0,0" IsVisible="false" x:Name="listView" HeightRequest="200">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding .}" />
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </AbsoluteLayout>
    </ContentView.Content>

This will be used on ContentPage, along with other Entry and Label controls.
When someone clicks on Entry then, corresponding ListView must be shown to user just below the Entry, by overlapping other controls, instead of pushing down other controls below it.
I have achieved overlapping of controls, but not correctly. ListView does shows list to user but other controls overlap it. ListView gets a lower Z-Index and other controls get higher Z-Index.
Need help to fix this.
Edit 1-
Screens for what I want to achieve. (This a Spinner control in Android)

I want to do something similar with my control.
PS - follow this SO answer for root cause this behaviour.
Comment: Can you add an image of the result that you want to achieve and explain what other controls have to be overlapped?
Comment: @ganchito55 Updated my question to include some screens
Answer: I had the exact same problem and I fixed it using a custom renderer. This lets the user type to filter the list choices and then puts the selected choice in the entry when the user picks one. In your forms project you'll want a new subclass of entry:
public class AutofillTextView : Entry
{
    public static BindableProperty ChoicesSourceProperty = BindableProperty.Create(
            nameof(ChoicesSource), typeof(ObservableCollection<string>), typeof(CustomPicker),
            default(ObservableCollection<string>), propertyChanged: OnChoicesSourceChanged);

    public ObservableCollection<string> ChoicesSource
    {
        get { return (ObservableCollection<string>)GetValue(ChoicesSourceProperty); }
        set { SetValue(ChoicesSourceProperty, value); }
    }
    public AutofillTextView()
    {
        Items = new List<string>();
    }

    private void ChoicesChanged(object sender, NotifyCollectionChangedEventArgs args)
    {
        switch (args.Action)
        {
            case NotifyCollectionChangedAction.Add:
                Items.Add(args.NewItems[0]);
                break;

            default:
                var itemsList = ChoicesSource.ToList();
                Items = itemsList;
                break;
        }
        OnPropertyChanged(nameof(Items));
    }

    private static void OnChoicesSourceChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var textView = (AutofillTextView) bindable;
        textView.ChoicesSource.CollectionChanged -= textView.ChoicesChanged;
        textView.ChoicesSource.CollectionChanged += textView.ChoicesChanged;
        textView.Items = newValue == null ? new List<string>() : ((ObservableCollection<string>)newValue).ToList();
    }
}

You might need to expand on this, but I never remove items from the list so the switch was good enough for me. I needed to use observable collection as well, so you can simplify by switching to list. Anyway, next you need your custom renderer in droid:
[assembly: ExportRenderer(typeof(AutofillTextView), typeof(AutofillTextViewRenderer))]

namespace Default
{
    public class AutofillTextViewRenderer : ViewRenderer<AutofillTextView, InstantAutoCompleteTextView>
    {
        protected override void OnElementChanged(ElementChangedEventArgs<AutofillTextView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                var control = new InstantAutoCompleteTextView(Forms.Context);

                control.InputType = Android.Text.InputTypes.ClassText | Android.Text.InputTypes.TextFlagNoSuggestions;
                control.Text = Element.Text;
                SetNativeControl(control);
            }

            if (e.OldElement != null)
            {

            }

            if (e.NewElement != null)
            {
                var adapter = new ArrayAdapter<string>(Forms.Context as Android.App.Activity, Resource.Layout.AutofillTextViewItem, e.NewElement.Items.ToArray<string>());
                Control.Adapter = adapter;
                Control.Threshold = 0;
                Control.TextChanged += Control_TextChanged;
                adapter.NotifyDataSetChanged();
            }
        }

        void Control_TextChanged(object sender, Android.Text.TextChangedEventArgs e)
        {
            if (Element.Text != Control.Text)
            {
                Element.Text = Control.Text;
            }
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            if (e.PropertyName == AutofillTextView.ItemsProperty.PropertyName)
            {
                var adapter = new ArrayAdapter<string>(Forms.Context as Android.App.Activity, Resource.Layout.AutofillTextViewItem, Element.Items.ToArray<string>());
                Control.Adapter = adapter;
                adapter.NotifyDataSetChanged();
            }
            else if(e.PropertyName == AutofillTextView.TextProperty.PropertyName)
            {
                if(Control.Text != Element.Text)
                {
                    Control.Text = Element.Text;
                }
            } else if(e.PropertyName == AutofillTextView.IsFocusedProperty.PropertyName) {
                if(Element.IsFocused)
                    Control.PerformFiltering();
            }
        }

    }
}

This will connect your custom class (AutofillTextView) to an android class (InstantAutoCompleteTextView) to replace the default entry renderer. The reason I don't use the built in AutoCompleteTextView is because it won't show the dropdown until you type at least one character. I'd prefer it shown on focus. If you don't care you can skip that. Here's that view:
public class InstantAutoCompleteTextView : AutoCompleteTextView
{

    public InstantAutoCompleteTextView(Context context) : base(context) {}

    public InstantAutoCompleteTextView(Context arg0, IAttributeSet arg1) : base(arg0, arg1){}

    public InstantAutoCompleteTextView(Context arg0, IAttributeSet arg1, int arg2) : base(arg0, arg1, arg2){}

    public override bool EnoughToFilter() {
        return true;
    }

    public void PerformFiltering()
    {
        PerformFiltering(Text, 0);
    }
}


How do I check the user has entered two or more words in a single string?

Question: My function takes a string, and as long as the string has two names in it, such as "John Smith", the program runs OK.
My issue occurs when the user enters 1 or less names in their input.
user_input = input("Enter your name: ")

name = user_input.split()

print(name[0])
print(name[1])

Ideally, it would check that the user has entered a string of just two names, but it doesn't really matter.
I don't know the required checks in Python; if it was Java, it would be a different story.
Comment: `len(name)` should give you the number of words the user entered. Combine that with an `if` condition and you have a word-count check.
Comment: Since you know how to do it in java, what speaks against doing it exactly the same way (and googling how to do those exact same things)?
Answer: You could use len() or try/except as in:
user_input = input("Enter your name: ")
if len(user_input.split()) > 1:
    print("At least two words.")
else:
    print("Only one word")

Or
user_input = input("Enter your name: ")
try:
    user_input.split()[1]
    print("At least two words.")
except IndexError:
    print("Only one word")

Answer: user_input = input("Enter your name: ")

name = user_input.split()

for x in names:
    print(x)


Conjugation in $GL(V)$?

Question: Given $T,P\in GL(V)$, what does it mean to conjugate $T^{-1}PT$? I understand that if we choose a basis for $V$, then conjugation on $GL_n(F)$ just becomes representing the same linear transformation under different choices of basis. However, it seems to me that conjugation in $GL(V)$ is different because if it were the same, we'd be saying $T^{-1}PT=P$ which is definitely false. However, $GL_n(F)$ and $GL(V)$ are isomorphic as groups which further confuses me. Could anyone shed some insight?
Answer: The word conjugate can have several meanings depending on the context, even restricted to the scope of your question.

First, in abstract algebra, an entity such as $$T^{-1}PT$$
is called the conjugate of $P$ by $T$. This terminology holds in any group. One will say that a group (here $GL(V)$) acts on itself by conjugation.
Completely unrelated, some people use the word conjugate to refer to the matrix $M^*$ of the adjoint operator, when the vector space $V$ is endowed with an inner product.
Finally, when the base field is $\Bbb C$, the conjugate of a matrix can refer to the matrix $\bar M$ obtained by applying complex conjugation to every entry.

Now I believe that your question is about the first definition. It is true that $T^{-1}PT$ represents the same operator (call it $L$) as $P$ but in a different basis. That does not make $T^{-1}PT$ equal to $P$ as a matrix.  For the same input vector $\vec v$ would have different coordinates and correspond to a different column-vector depending on whether you want to use the matrix $P$ or the matrix $T^{-1}PT$ to compute the output $L(\vec v)$.
Comment: I understand as matrices these are definitely different. My problem is operators are defined without respect to any basis, so in my mind it should be true that $T^{-1} PT=P$ because they are literally the same operators, if conjugation is GL(V) is literally the same as conjugation in GL_n(F) . But we have a problem because operators don't commute in general. So I'm wondering where my mistake in thinking is.
Comment: @PaulT To view a matrix as an operator, you need to specify a basis. $P$ and $T^{-1}PT$ are the same operator only with different bases, so that the same input looks different to them. That's what I wrote after the boldface sentence; I think that it answers exactly your question.
Comment: I do understand what you're saying, but the point I'm trying to make is I I want to eliminate bases/matrices out of the discussion and view $T,P$ as abstract operators which take in vectors $v$ without specifying a basis. I believe that this viewpoint is legal, because its core, linear operators are ultimately functions which don't require a coordinate system $(v\mapsto Tv)$. So as abstract transformations, to my understanding, they take in the same $v$ and output the same vector $Tv$.

Conjugation in $GL(V)$?


Abstract proof of Fundamental Theorem of Algebra

Question: I have been reading up on the topological proof of the Fundamental Theorem of Algebra.How can one prove it more abstractly?given that the polynomial is a map from topological field S to itself,what is are the additional properties S should satisfy for FTA to be true?
Answer: Here is my intuiutve understanding of the winding number proof of the FTA:
Given a degree-$n$ polynomial $f(z) = a_nz^n + \cdots + a_1z + a_0$, for a "large enough" circle $\gamma_R:[0,1]\to \Bbb C$ (centered at the origin, radius $R$), the curve $f(\gamma_R(t))$ behaves basically like $a_n\gamma_R(t)^n$, going around the origin $n$ times.
For a "small enough" circle $\gamma_r$ (still centered at the origin, radius $r$), on the other hand, $f(\gamma_r(t))$ behaves much like $a_1\gamma_r(t) + a_0$, not necessarily going around the origin at all (and if it does go around the origin no matter how small $r$ is, then $a_0 = 0$, and $z = 0$ is a root of $f$).
As you continually increase the radius from $r$ to $R$, the number of times the corresponding $f(\gamma)$ goes around the origin must increase from $0$ to $n$. As the curve $f(\gamma)$ changes continuously with the radius, at some point it must therefore pass through the origin. Thus $f$ has a root.
The closedness of the curves $\gamma$ ensures that this increase in winding number cannot come from the end points themselves winding around the origin, the way you would wind a rope around a pole. Thus they must come from the curve actually passing through the origin at some stage.
More technically, the function from $[r,R]\to\Bbb N$ given by this winding number is continuous. And since it's not constant, it must be undefined at some points. The only way the winding number is undefined is if the curve passes through the origin.
Comment: Thanks for the answer..i just realised I could phrase my question in a better way,as I wanted to know how deeply all the concepts used in the proof are linked to solutions of a polynomial..


Enviar id via POST no Jquery

Question: Estou trabalhando em uma implementação do Datatables, mas surgiu a necessidade de enviar o id para fazer os filtros:

  $(document).ready(function() {
   var dataTable = $('#employee-grid').DataTable( {
                responsive: false,
    "order": [[ 1, "asc" ]],
    "aoColumns": [
     null,
     null,
     null,
     null
    ],
    //"scrollY": 400,
    "scrollX": true,
    "iDisplayLength": 100,
    "processing": true,
    "serverSide": true,
    "ajax":{
     url :"../php/admin_gerente_cidade.php",
     type: "post",
     error: function(){
      $(".employee-grid-error").html("");
      $("#employee-grid").append('

Nenhum resultado encontrado

');
      $("#employee-grid_processing").css("display","none");
     }
    }
   } );
  } );

Se eu colocar

url :"../php/admin_gerente_cidade.php?id=<?php $id; ?>"

Não funciona.
Seria possível passar um id via POST?
Comment: Nao tenho muito conhecimento de php, mas ali onde tah o $id, como não é interpolação de string (por causa do , da um echo antes do $id e veja se resolve.
Comment: você precisa passar o data: {id: id}
Answer: Basta informar a propriedade data, segue abaixo como ficaria no seu caso, substitua seu_id pelo valor que você precisa.
$(document).ready(function() {
            var dataTable = $('#employee-grid').DataTable( {
                responsive: false,
                "order": [[ 1, "asc" ]],
                "aoColumns": [
                    null,
                    null,
                    null,
                    null
                ],
                //"scrollY": 400,
                "scrollX": true,
                "iDisplayLength": 100,
                "processing": true,
                "serverSide": true,
                "ajax":{
                    url :"../php/admin_gerente_cidade.php",
                    type: "post",
                    data: {id: seu_id},
                    error: function(){
                        $(".employee-grid-error").html("");
                        $("#employee-grid").append('

Nenhum resultado encontrado

');
                        $("#employee-grid_processing").css("display","none");
                    }
                }
            } );
        } );

Comment: Perfeito. Muito obrigado!

Enviar id via POST no Jquery


Groupon coupon code system in PHP

Question: I am trying to create a system just like groupon but where merchants input voucher codes into the system that customers can use to get their products.
So let's say Merchant 1 has the following product

Product Name: Camera
Product ID: 2

He would add coupon codes for Product ID 2 into the system.
Coupons get added to the COUPON table with the following fields:

id
code
product_id (refers back to Product table
num_available
max

max is the maximum of the coupon that can be given out. num_available is the number of that coupon available. So if a Merchant puts in 5 as max, then num_available starts out as 5. but whenever a customer gets assigned that coupon, num_available gets decreased by 1
Then when customers order they get assigned a coupon
User orders get added to the following table Orders:
Orders:

order_id
user_id

OrderPosition:

id
order_id
product_id
amount
coupon_id

Each Order (stored in Orders) has multiple products associated with it (stored in OrderPosition).
So User 1 orders Product 2 and gets assigned Coupon ID 1 that was added for Product 2. The num_available for Coupon ID 1 (in the COUPON table) gets decreased by 1 in the database.
but what if User 1 orders TWO Product 2s - one for her and one for her friend - does she get two different coupon codes?
Basically, I would like to make his process more efficient, and I don't know how Groupon has designed this process, but if anyone has good ideas on how best to do so, please let me know!
I would love to know if I should change the database schema to make this more efficient ...
My end goal is to allow people to buy deals. Once they buy a deal, they get a coupon. I could have automatically generated that coupon, but I'm guessing some merchants want to input their own coupons that work on their own system, right?
The question is - how should I design the system to achieve my goals described above?
I would also like to stress that the products that will be listed on my website will be from different merchants. I won't be listing my own products. Merchants list their own products just like on Groupon.com.
Is it feasible to generate coupon codes instead of having merchants input their codes? Wouldn't that mean that they would have to also support these codes on their own systems? Like If jcpenny.com inputs products on my website, I could generate coupon codes for these products, but what if jcpenny.com does not support these coupon codes? I am guessing that Merchants would want to input their own codes... Or maybe I am wrong?
Comment: @MattBall: That wasn't in the original question, it's been edited  :-)
Comment: @Clive isn't it obvious? Read the last sentence: _"how should I design the system to achieve my goals described above?"_
Answer: i'd suggest generating a coupon code for each request. if someone orders 2, generate 2 codes.
it's easier if someone buys for a friend, or if the same user buys multiple times. i actually had the same case in a system i wrote, and it ended up being the most convenient solution for my case.
of course, it's a matter of opinion...

Groupon coupon code system in PHP


ProFTPd: how to show virtual user name in listings?

Question: I'm using ProFTPd 1.3.5a (btw I get the same behavior on an older 1.3.4d) with a pretty common virtual users setup for a web server.
In plain words, ProFTPd is running with apache's UID/GID and has its local files for authentication. All users have the same real UID/GID (again, apache's one) and are chrooted in their directories, with DirFake* entries.
This is an excerpt from configuration:
AuthPAM off
AuthOrder mod_auth_file.c
AuthUserFile /etc/proftpd/ftpd.passwd
AuthGroupFile /etc/proftpd/ftpd.group
UseFtpUsers off
DefaultRoot ~
DefaultChdir /
DirFakeUser on ~
DirFakeGroup on ~
DirFakeMode 0644
ShowSymLinks off
Umask 026 027

<Directory ~/>
  UserOwner www-data
  GroupOwner www-data
</Directory>

But with every ftp client I try, when listing files I only get numeric UID/GID and not the virtual user name. This is also annoying because clients such as CyberDuck will assume that numeric ID is not the same as the user they are connected with, and will show all files/directories as inaccessible (even if then trying to access them actually works).
edit: on the server there is a "real" user www-data with UID 33 and group www-data with GID 33, ProFTPd runs with that UID/GID, the virtual users in /etc/proftpd/ftpd.[passwd|group] all have uid=gid=33, all the files in the users directories have uid=gid=33. Right now ftp clients list all files as uid 33 and gid 33 and fail to convert numeric IDs to user / group names. I don't want to show files as belonging to www-data in ftp clients, but belonging to the user name they used to authenticate.
This is also what the mod_ls would do with DirFake* options, as I understood it: throwing fake user/group to the connected clients. It isn't doing that or at least it is doing that just for the numeric IDs.
How can I let ProFTPd show the virtual user name in listings to clients?
Comment: Are files owned by "real users"  i.e. those present in /etc/passwd also always shown as UID/GID numbers? Because that might indicate that  [`ListOptions`](http://www.proftpd.org/docs/modules/mod_ls.html#ListOptions) is set to [**`-n`**](http://www.proftpd.org/docs/howto/ListOptions.html)
Comment: Some FTP clients now use the newer `MLSD`/`MLST` commands, rather than `LIST` and `NLST`, for listing files; these newer commands don't have _facts_ for the names, just the IDs.  Thus you might try adding `FactsAdvertise off` to your `proftpd.conf`, which tells ProFTPD to not _advertise_ that it can handle those newer FTP commands.  This, in turn, should cause the FTP clients to fall back to the older FTP commands, which _do_ provide the names.
Comment: @Castaglia that did the trick, thanks! You should post it as an answer!
Comment: @Luke404 Posted as answer. :)
Comment: @HBruijn thanks for asking, I added that information to my original question.
Comment: @HBruijn there is no `ListOptions` in my config, and I even tried adding `ListOptions +n` to the `` block but it did not have any effect.
Answer: Some FTP clients now use the newer MLSD/MLST commands, rather than LIST and NLST, for listing files; these newer commands don't have facts for the names, just the IDs. Thus you might try adding FactsAdvertise off to your proftpd.conf, which tells ProFTPD to not advertise that it can handle those newer FTP commands. This, in turn, should cause the FTP clients to fall back to the older FTP commands, which do provide the names.
Update: I've requested that two new OS-Specific Facts, UNIX.ownername and UNIX.groupname, be registered with the IANA for use in MLSD listings, to be able to provide the user/group names in listings using that command.  I'll be adding support for these to ProFTPD soon.
Hope this helps!


Allow users to >only< upload images to existing nodes?

Question: I want to allow users to upload images for exsits content, for example for article, but i will not allow they to delete already exist images.
How modules i can use? How to create this submit form for they?
I use drupal 7.
Thank you!
EDIT:
Hi Vincent,
thanks for reply.
On example:
I have article about Rome with title "Rome". I create description for that beautiful city and i want to allow users to upload images to this exist article about Rome and create gallery of users pictures under descripton.
User can submit photo, but can't remove own or anyone images.
Admin must accept every image before it's publish.
Greetings.
Comment: You could try with [file entity](https://www.drupal.org/project/file_entity) module which has some useful permissions like: Bypass file access control, Add and upload new files, Edit own files, Edit any files, Delete own files, Delete any files.
Answer: Hints for your updated, clarified question (from NOT an expert)
Considering your updated question, there exists a documentation-page on Drupal.org on attaching images to nodes:

Attaching images to other nodes

But, perhaps easier to start off, is to read some answers posted to identical / very similar questions, here on StackExchange:

How to allow users upload images to existing nodes?
Add new images to existing nodes

Having referred to these, I would like to add that I would intuitively enable pictures in comments, and let people post the pictures in to the comments; but I don't know if that's what you're looking for.
If you would choose them to use the comments: after having enabled comments to include pictures, one can disable unneeded fields, similarly to the method described below, via

Structure >> Content Type >> Content type >> Comment fields.
Structure >> Content Type >> Content type >> Comment display.

For further fine-tuning of the display of the comments, the module Views is advised, which will allow you to first select a lay-out in the "Comment display" referred to above, via:

Structure >> Content Type >> Content type >> Comment display >> Layout for comment node content type

& will then allow fine-tuning of the fields in the comments.
The approving of the content by the admin; considering comments; can be tweaked via the row:

People >> Permissions >> Comment >> Skip comment approval

Alternative modules for admin approval of general content can be found in the following StackExchange-post:

Allow users to submit content that is approved before it is published.

Just a final extra remark (more of an alternative easy work-around really): if the text format (cf. Configuration » Content authoring >> Text formats) to be used for your users allows for the HTML -tag, one can of course tell your users how to "post" (but not upload technically) images as a comment, by explaining that they could use <img src="URL">, like you can find explained e.g. @ the W3C-wiki or @ W3-schools.

P.S.: You are a funny guy to re-use Rome.

I will leave my original answer below, which is more applicable to letting people upload pictures as separate nodes; but (as described below) is not a good method for letting people upload multiple pictures to already existing nodes (as you have now updated your question).
Answer to your original question
What you can do is to create a new content type.
To do this, use the administrative overlay & go to:

Structure >> Content Type >> Add content type.

Perhaps you could name the content type "Add a photo", or something.
Then, I would manage & display the fields such that all fields are hidden, except a field for a photo. This can usually be done after creating the content type, by going to:

Structure >> Content Type >> Add a photo >> Manage fields.
Structure >> Content Type >> Add a photo >> Manage display.

Then, I would restrict access to authenticated users (all of them / or some authenticated users; as you'd like) to create &/or edit certain content types only. This can be done (again, using the administrative overlay) by going to:

People >> Permissions >> Add a photo: Create new content
People >> Permissions >> Add a photo: Edit own content

The two boxes of these row can be checked at the column "AUTHENTICATED USER". (That is, if you'd like only authenticated users to be able to post pictures). Then, Creating & Editing of all the other content types should be disabled; if I understand you well. This can be done on the same page, by disabling the checkmarks for "AUTHENTICATED USER"s in e.g. the default content type "Article", via:

People >> Permissions >> Article: Create new content
People >> Permissions >> Article: Edit own content

This is just only what first comes to my mind. You'll see that Drupal is very flexible, and multiple roads lead to Rome.
Comment: Please read edit note in my first post. Thank you.


Update updated_at attribute in mongo on each update using Morphia Java

Question: I want to update update_at attribute in MongoDB for each update on a document so later I can retrieve documents based on the last update_at filed. There are two ways I came across for this scenario.

Update update_at in each DAO call like
public void updateMemberDetails(Long memberId, Sring email) {
UpdateOperations<Member> ops =   getDs().createUpdateOperations(Member.class);
Query<Member> query = basicQuery(memberId);
ops.set("email", email);
ops.set("update_at", new Date());
getDs().update(query, ops);
}

Other ways is to call Mongo's life cycle method in model (http://mongodb.github.io/morphia/1.4/guides/lifeCycleMethods/)
@PrePersist
  public void prePersist() {
    update_at = new Date();
  }

Problem :-
Method 1 works perfectly fine but the only disadvantage of method 1 is I have to add ops.set("update_at", new Date()); in each DAO update method that I don't want to update in each method.
In method 2 prePersist() method called only in operation db.save(), prePersist() method is not called in db.update() operation. So I am not able to update date when DAO method call db.update().
Answer: This is less performant than using update() since it will load the object in order to do a save, but what about:
public void updateMemberDetails(Long memberId, Sring email) {
  Datastore ds = getDs();
  UpdateOperations<Member> ops = ds.createUpdateOperations(Member.class);
  QueryImpl<Member> query = basicQuery(memberId);
  Member member = query.get();
  member.setEmail(email);
  ds.save(member);
}

It also gives you the option to add validation logic into the setEmail() function.
Note: the get() method is in QueryImpl via the QueryResults interface and not part of the Query interface.


Group Views results by split year (academic, fiscal, etc.)

Question: I have several content types with Date fields. I would like to build a View that groups that content by our academic year, e.g. 2015-2016, 2016-2017, 2017-2018, etc.
I realize I would have to define those start and end dates somewhere (i.e. August 1 through July 31). It could be similar to a fiscal year as well.
I could do taxonomy terms, but I was hoping to not have to introduce another field if the date fields can accomplish this.
I am using Drupal 8.
Answer: Use Grouped Exposed Filter
Using a Grouped Exposed Filter for the Authored on field is the quickest and easiest way to filter out by academic year.
When you Expose a Filter, you can choose between Single filter and Grouped filters:

If you choose Grouped filters you can define your own items for the Exposed filter. In your case two academic years would be configured like this:

I haven't included time but you probably should to make sure that content created on July 31 and August 1 doesn't get exluded. Maybe something like 2017-08-01 00:00:00 and 2018-07-31 23:59:59 would work.
Add as many entries as you have academic years. Then when viewing your Views results choose the appropriate academic year option:

I've noticed grouped filters have some bugs in D8 when dealing with taxonomy terms, but I haven't noticed any problems with AuthoredOn field.

Contextual Filter Content: Created year + month
If you include this Contextual Filter and choose to Display a summary:

you get links of months and years you click through to see content posted within those dates:

If that alone isn't enough maybe that can inspire you to create a similar custom Contextual filter with a bit more logic inside to do the same but for a configurable set of periods.
Comment: Thanks. Between both of those, it's close to what I want, but I'm not looking to filter -- only to group. I may be able to work up something similar with a custom field and group on that.
Comment: A custom solution will give you the most flexibility. If you don't know how and can't afford it and there aren't that many years to deal with, you can create an attachment for each academic year and display them one below the other on a page ;)


Is it worth to create one partion filling whole disk on Linux?

Question: Let imagine that we have a disk. The whole disk is going to be use for one mount point or LVM physical volume. Is there a point to create separate partition covering the whole disk? Or maybe put filesystem directly on disk?
Answer: There are some utilities that are less than pleased if the disk has no partition table, but if you'll be using it as one volume, you can just format the device directly.
What do you think you'll lose if you don't ?
Comment: I prefer to have only necessary layers of software. Recently I've dived depper into I/O performance and started to wonder I got (or lost) anything with and without partition table, in situation where the whole disk was assigned to one partition. BTW  When I was working with a lot of VMs I made LVM directly onto a 'disk' and put everything on it. I didn't have any problem, but wonder if it possible was just a luck.


Configurar Tomcat com SSL

Question: Eu segui o tutorial no site Tomcat que manda basicamente fazer 2 coisas:

Criar um .keystore com password changeit através do Keytool.exe. Salvei o arquivo resultate em C:\Users\Vinicius
Descomentar e modificar o conector do server.xml localizado em C:\Program Files\Apache Software Foundation\Tomcat 8.0\conf

E ficou assim:
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="200" SSLEnabled="true" scheme="https" secure="true"        keystoreFile="C:\Users\Vinicius\.keystore" keystorePass="changeit"
clientAuth="false" sslProtocol="TLS" />

Após isso, em teoria, é só acessar a minha pagina pelo https://localhost:8443/ mas recebo o erro:

A conexão com localhost foi recusada.

Fiz algo errado?
Comment: Veja o erro no catalina.out e poste aqui
Answer: Para configurar um certificado no tomcat siga essas etapas:
Primeiramente você deve criar um p12 com o openssl assim:

openssl pkcs12 -export -in fullchain.pem -inkey chavePrivada.pem -out
  tomcat.p12 -name tomcat

será solicitado uma senha para o keystore, coloque changeit.
Após isso você devera criar o seu JKS dessa maneira:

keytool -importkeystore -deststorepass changeit -destkeypass changeit
  -destkeystore tomcat.jks -srckeystore tomcat.p12 -srcstoretype PKCS12 -srcstorepass changeit -alias tomcat

Com isso será criado um arquivo chamado tomcat.jks
Logo você devera configurar o server.xml que está localizado na pasta $CATALINA_BASE/conf seguindo assim:
<Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol" URIEncoding="UTF-8" maxThreads="150" SSLEnabled="true" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" keystoreFile="/path/para/sua/jks/tomcat.jks" keystorePass="changeit" keyAlias="tomcat" keyPass="changeit"/>

Feito isso reinicie o tomcat e verifique se deu tudo certo acessando: https://localhost:8443/
Comment: Primeiramente, obrigado pela rapidez João. Eu instalei o OpenSSL e rodei o seguinte comando no CMD:

`C:\OpenSSL-Win64\bin>openssl pkcs12 -export -in fullchain.pem -inkey chavePrivada.pem -out tomcat.p12 -name tomcat`

Recebi como output essa msg:
`pkcs12: Cannot open input file fullchain.pem, No such file or directory
pkcs12: Use -help for summary.`
Comment: o fullchain.pem é a junção do seu certificado junto com o chain (certificado da sua certificadora) por exemplo se seu certificado for site.com.crt voce deve juntar ele com o CA.crt que provavelmente veio acompanhado
Comment: Desculpe, mas pra mim esse assunto é muito novo e sou muito novato. Eu não estou querendo usar um certificado de uma CA. Um self-signed Certificate pra mim já bastaria. Eu criei um .keystore cujo path é **C:\Users\Vinicius\.keystore** e modifiquei o server xml cujo path é **C:\Program Files\Apache Software Foundation\Tomcat 8.0\conf** assim:
`
`
Comment: Então em vez de fullchain.pem use suaChave.crt
Comment: Acho que estou iniciando o tomcat de maneira errada. Não consigo nem acessar o `https://localhost:8080` pra chegar na pagina default do tomcat (da erro 404). Mas se uso `http://localhost:8080/Projeto_Final/index.jsp` consigo acessar minha pagina.
Comment: Veja isso...
https://www.digicert.com/csr-ssl-installation/tomcat-keytool.htm

Configurar Tomcat com SSL


should I do a correlation?

Question: I don't know anything about statistics, but I am trying my best to learn :) I have two sets of data of a city. First one is the median of the personal net monthly income per district, and the second one is the per capita green space per district. I wanna know if the income will predict the amount of green space, so I'm not sure if what I need to use here is a correlation test? Thank you very much
Answer: Yes, you can do a correlation. If it is positive, then your data suggests a positive relation between income and green space at the district level within your city. If it is negative, then as one goes up, the other goes down. The larger the correlation in either direction, the stronger the relationship in that direction.
I would even add that before you do a correlation, use some software, maybe excel to produce a plot of district income on the x-axis and green space on the y. If the plot is intelligible, and you can make sense of it, this may be of more benefit to you than any correlation value you compute. If you can't make sense of it, then you should be cautious interpreting the correlation in the manner I have up top. If the trend you find deviates markedly from a straight line, then the correlation you calculate will struggle to capture the relationship you can see in the plot, and the plot is many times better.
This is as far as I'd advise you go. It is not a good idea to attempt to do statistics when one does not "know anything about statistics". Stay away from p-values, they may not even be relevant to you. Plot and if you can understand the trend from the plot, interpret the result of the correlation in a manner similar to what I've written.
My response assumes you're not going to suddenly learn statistics.
Answer: Equivalently you can run a simple regression of $y = \alpha + \beta x + u$, where $y$ is per capita green space and $x$ is median income. Then test whether $\beta$ is significantly different from zero. If so, income can (partially) explain the distribution of green space.
Comment: While true, this is likely beyond this particular individual.

should I do a correlation?


Export DynamoDB to S3 data using AWS Datapipeline

Question: I have a DynamoDB table storing 1Gb of data. RCU and WCU are 1000 each.
I set up a Data pipeline to export this 1 GB of data to s3. The entire 1GB of data is exported to s3
in partitions. My question is what decides the number and size of these partitions?
Answer: mightyMouse,
In his recent video "AWS Re:Invent Amazon DynamoDB advanced design patterns – Part 1," Rick Houlihan demonstrates setting 100k WCU provisioned capacity at table creation and mentions that each extra 1000 WCU provisioned will add 1 partition, thus his table starts with around 100 partitions. Partitions are internally limited to 10gb, splitting into two partitions if a partition hits this limit, but otherwise they will stay within one. This suggests that potentially all of your data still sits just within one partition.
All this seems to be abstracted/hidden away from users, but generally you should be able to calculate the estimated number of partitions.
With On-Demand mode AWS says they will automatically increase the throughput of your table by double the previous limit. The wording is a little bit weird, but I believe this ends up with them creating more partitions for you as a partition gets queried or written to faster than it can handle.
Something to note is that many people have mentioned that once a partition has been provisioned you can lower the number of WCU to what you actually need and still keep the provisioned partitions.


Files transfer to HDFS

Question: I need to bring the files (zip, csv, xml etc) from windows share location to HDFS. Which is the best approach ? I have kafka - flume - hdfs in mind. Please suggest the efficient way.
I tried getting the files to Kafka consumer.
producer.send(
                    new ProducerRecord(topicName,key,value),
Expect an efficient approach
Answer: Kafka is not designed to send files, only individual messages of up to 1MB, by default.
You can install NFS Gateway in Hadoop, then you should be able to copy directly from the windows share to HDFS without any streaming technology, only a scheduled script on the windows machine, or externally ran
Or you can mount the windows share on some Hadoop node, and schedule a Cron job if you need continuous file delivery - https://superuser.com/a/1439984/475508
Other solutions I've seen use tools like Nifi / Streamsets which can be used to read/move files
https://community.hortonworks.com/articles/26089/windows-share-nifi-hdfs-a-practical-guide.html
Comment: Thanks for the info. Actually I am splitting the files and sending to kafka as bytearray. Then in consumer end, I am converting those byte arrays to string, then writing to files. This way I am transferring the files from windows share to kafka consumer. Now my task is to transfer these files to HDFS. Sorry if my earlier question was bit confusing. Please suggest.
Comment: As long as you only have one topic partition and aren't sending multiple files into the same topic at the same time , that might work, but otherwise you can't guarantee your get your file splits back in the same order

Files transfer to HDFS


T-invariant subspace has a T-invariant complement implies minimal polynomial has nice form

Question: Let $V$ be a finite dimensional vector space over a field $K$ and let $T\in \mathcal{L}(V)$ be a linear operator on $V$. Let $U$ be a $T$-invariant subspace of $V$, and let $T|_U$ be the restriction of $T$ to $U$. Denote passage into the quotient by $U$ of $T$ by $\overline{T}$.
Now assume that $U$ has a $T$-invariant direct complement (i.e., $\exists W\le V$ with $W$ $T$-invariant and $V = U \oplus W$). Let $m(t)$, $m_1(t)$, and $m_2(t)$ be the minimal polynomials for $T$, $T|_U$, and $\overline{T}$ respectively. I am asked to prove that $m(t) = \operatorname{lcm}\{m_1(t),m_2(t)\}$.
Here's what I've tried so far:
Consider the division algorithm of $m_1$ and $m$, i.e. let $p, r \in K[x]$ be the unique polynomials such that $m = pm_1+r$ with $\deg(r) < \deg(m_1)$. Then $r = m-pm_1$ and $r(T|_U) = m(T|_U) -p(T|_U)m_1(T|_U) = 0 - 0 = 0$, contradicting the minimality of degree of $m_1$, so that $r = 0$ and $m_1 | m$. Similarly, $m_2 | m$ so that $\operatorname{lcm}\{m_1,m_2\} | m$
I'm not quite sure how to proceed. As of yet I haven't used the invariant complement condition, and I realize intuitively it's that $\overline{T}$ is the same as $T|_W$ so that $T = T|_U + T|_W$ but I can't quite get it to work. I've seen an approach that uses matrices but I'd rather stick with operators if possible.
Answer: In establishing that $m_2 \mid m$, you have indeed used the invariant complement condition, since if $W$ were a complement that was not $T$ invariant, it could be that $p(\overline{T})$ annihilates $V/U$ although $p(T)$ does not annihilate $W$ (so long as $p(T)$ sends $V$ into $U$).
The part of the proof you are still working on is actually the easy part: if $m_1, m_2 \mid p$, then $p$ annihilates $V$.

If you have learned some ring theory: in general, if $R$ is a principal ideal domain, and $M, N$ are $R$ modules where $(r_1) = \text{Ann}_R(M)$, and $(r_2) = \text{Ann}_R(N)$, then $\text{Ann}_R(M \oplus N) = \text{Ann}_R(M) \cap \text{Ann}_R(N) = \text{lcm}(r_1, r_2)$.


Erro em programa de Python

Question: Boa tarde
Alguém me pode explicar porque é que o meu codigo nao dá o resultado pedido e o que posso fazer para obter a solução pedida?
Aparece o erro:
total = round(soma,NDec[k])TypeError: 'list' object cannot be interpreted as an integer
Implemente uma função com três parâmetros, que, para um dado ângulo em graus (primeiro parâmetro), um vetor N (segundo parâmetro), com valores crescentes do numero de termos da serie a usar, calcula e retorna um vetor com o valor da aproximação da função co-seno obtida com cada um dos Ni termos da serie de Taylor, para o angulo dado.
O número de casas decimais a usar no resultado para cada numero de termos é dado pelo vetor NDec (terceiro parâmetro), com o índice i do vetor indicando o numero de casas decimais a apresentar para o numero de termos definido no índice i do vetor N. O vetor N não deve ser modificado pela função.
import math
def taylor(ang,N,NDec):
ang_rad = math.radians(ang)
res = []
soma = 0
for i in range(len(N)):
    for k in range(len(NDec)):
        for j in range(N[i]):
            aprox_cos = (-1)**j/(math.factorial(2*j)) * ang_rad**(2*j)
            soma = soma + aprox_cos
        total = round(soma,NDec[k])
    res.append(total)
return res

Eu utilizei na consola
ang = 180
N=[3, 4, 6, 10, 20]
NDec=[4, 6, 8, 10, 10]
A solução é:
[0.1239, -1.211353, -1.0018291, -1.0000000035, -1.0]

Nota:

Obrigado a quem puder ajudar!
Answer: Pelo que percebi, está faltando fechar um parêntesis na linha 7 e tem um colchete a mais na linha 9.
Acredito que corrigindo isso os erros não aparecem. Testei em um ambiente online de python.
Comment: Obrigado pela resposta, já corrigi isso e editei a pergunta, mas continua a não me dar o resultado pedido
Answer: O problema é simples, você esta passando o angule em graus e a função deveria receber o angulo em radianos.
Eu refatorei um pouco o código porque não entendi aquela soma sua inicializada fora dos loops. Criei 2 métodos, um chamado taylor, que gera os resultados pra cada quantidade de elementos e uma compute_cos, que usa a série de taylor pra calcular pra 1 elemento.
def taylor(angle, vector, decimals):
    """Calcula a aproximacao do cosseno usando o metodo de Taylor

    Parameteres
    ----------
    angle : int angulo em graus
    vector : list com a quantidade de iteracoes a serem usadas pra aproximar o resultado
    decimals : quantidade de casas decimais do resultado
    """
    results = []

    for (i, element) in enumerate(vector):
        _sum = compute_cos(element, angle)

        dec = decimals[i]
        result = round(_sum, dec)
        results.append(result)

    return results

def compute_cos(iterations, angle):
    """Calcula aproximadamente o coseno de um angulo usando series de Taylor

    Parameters
    ----------
    iterations: quantidade de iteracoes na serie
    angle : int angulo a ser calculado o coseno em graus
    """
    _sum = 0

    angle = math.radians(angle)
    for n in range(iterations):
        fact = math.factorial(2 * n)
        dividendo = (-1) ** n
        cos = (dividendo / fact) * (angle ** (2 * n))
        _sum += cos

    return _sum

Rodando esses resultados, obtemos:
angle = 180
elements = [3, 4, 6, 10, 20]
decimals = [4, 6, 8, 10, 10]
taylor(angle, elements, decimals)
>> [0.1239, -1.211353, -1.0018291, -1.0000000035, -1.0]

Que bate com o resultado que você espera.
Comment: Obrigado pela resposta  mas podias explicar-me porque é que aparece o erro: total = round(soma,NDec[k])TypeError: 'list' object cannot be interpreted as an integer , no codigo que editei?  eu no primeiro loop fiz com que i percorre todos os elementos de N , no segundo loop para dar as casas decimais que pretendo e no terceiro loop para percorrer os elementos de N[i] (estou a tentar so usar uma funcao)
Comment: As casas decimais não precisam de loop, o round só deve ser chamado uma vez pra cada elemento de N.
Comment: percebido, mas entao como é que fica o total?  Se fizer:  total = round(soma,NDec[i])
aparece-me o erro na mesma.
Comment: Nada indica no seu código pq desse erro. Esse erro deveria acontecer se NDec fosse uma lista de listas, mas não eh o que esta escrito no código que você postou.
Comment: Ja corri o programa assim e dá-me o resultado [0.1239, -1.087443, -2.08927202, -3.0892720247, -4.0892720247], ou seja so o primeiro valor esta correto. como resolvo isto?
Comment: Voce inicializou a soma dentro do primeiro for?
Comment: Ja meti a soma dentro do primeiro for e ja me deu o resultado correto. Faz sentido pois o que eu quero somar é os elementos de  "for j in range(N[i]):" Muito obrigado pela ajuda!

Erro em programa de Python


Scrolling text in form title bar

Question: I have written a simple code to scroll the text in the title bar of the form. It is working fine till the length of the text reach 159. After that the text cuts of in the title bar . It does not reach the end of the title bar rather cuts off in the middle of the title bar. Why does this happen?
tempheader is a variable that stores the me.text value at form load.
This is the code in the timer tick event with an interval of 100
 Me.Text = " " & Me.Text
        If Len(Me.Text) = 159 Then Me.Text = tempheader

Comment: It depends how big your form is.
Comment: Isn't this dependent upon how wide your form is?  My guess is your form is wider than the 159 character limit you have included in your code.  Lessen the width as it's running and see what happens.
Comment: My form is the MDIform and it is maximized. My form is wider than 159, but like i said it cuts at length of 159 , which is why i included the above code. Without the above code, when the len reaches 159, the text disappears.
Comment: Show us the rest of the code. The line of code that you put in to work around something isn't useful - the code that 's broken is useful!  What's `tempHeader`?  Also, which version of Windows are you running here, and is this WinForms or WPF?
Comment: Intriguingly, I can replicate this in a WinForms app - but the length my caption is cut off is 255 chars.  This appears (by eye) to be the maximum length of text that would fit in a maximised window on my screen - but if I resize the window across two monitors it won't exceed that limit.
Comment: i hope there is a solution for this with the form displayed in one screen!!
Comment: I was also able to replicate by removing the limit as well, but it limits for me to @ 230 characters. at 1600x900 resolution.  It doesn't matter how wide I start the form either (I thought it might be limited by the startup size).  My guess, since we all got different length values) is that it is resolution dependent perhaps?
Comment: I think it depends on the text size. My text length was 9.
Comment: Also, even though I use multiple monitors, it wrapped to the other monitor before disappearing.
Comment: Yeah, I'm thinking it may be a limit of 255 characters based upon the way old versions of vb worked.  My suggestion to @Nelson is to perhaps create a docked label at the top that will allow the scrolling and hide the title bar.  Just a thought.
Comment: it happens only when you are dynamically trying to change the title. For static title ,it takes any length.
Answer: Try this ..
Dim g As Graphics = Me.CreateGraphics()

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Static sPace As String

    sPace &= " "
    Me.Text = sPace & Me.Text
    If g.MeasureString(Me.Text, Me.Font).Width >= Me.Width Then
        Me.Text = tempheader
        sPace = ""
    End If

End Sub

Comment: @Nelsons .. I've been tried it in my VS 2005 and it worked ! .. What result you've got ?
Comment: It still doesnt go till the end of the form. It cuts off at position 159.
Comment: @Nelsons .. There's running text till the right side of form and then changed with other text .. that in my VS 2005 .. now, I'm not so sure what's really problem here ..
Answer: Lol I know this is an old post but I came across it whilst looking for something else anyway I just use a custom titlebar for scrolling text. Just create an empty form, doubleclick it delete all of the code and add the code from below. Go back and delete the form from the project and save it as a dll. You just need to import it back and add it to your toolbar and you can use it in any projects.

Imports System.Drawing
Public Class CustomTitlebar
Inherits Windows.Forms.Panel
  Public Sub ColourTitleText(ByRef panelBG As Color, ByRef txtBG As Color, ByRef txtFC As Color)
    Dim textbox1 As New Windows.Forms.TextBox
    Dim Psize As New Point(26, 200)
    Me.Size = New Point(26, 200)
    Me.BackColor = panelBG
    Me.BorderStyle = Windows.Forms.BorderStyle.None
    Me.Dock = Windows.Forms.DockStyle.Top
    Me.Font = New System.Drawing.Font("Tahoma", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
    textbox1.Name = "Textbox1"
    textbox1.BackColor = txtBG
    If Not txtFC = Nothing Then
        textbox1.ForeColor = txtFC
    End If
    textbox1.BorderStyle = Windows.Forms.BorderStyle.None
    textbox1.Size = New Size(Psize.X - 4, 20)
    textbox1.Location = New Point(3, 3)
    textbox1.Font = New System.Drawing.Font("Tahoma", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
    textbox1.Multiline = False
    textbox1.Text = "Coded by tHE_alCHMist 2010"
    Me.Controls.Add(textbox1)
  End Sub
End Class

Put this in a timer "CustomTitlebar1.Text = MarqueeLeft(CustomTitlebar1.Text)"

and then put this function somewhere
Public Function MarqueeLeft(ByVal Text As String)
    Dim Str1 As String = Text.Remove(0, 1)
    Dim Str2 As String = Text(0)
    Return Str1 & Str2
End Function

Finally remember to dock it with the top of the form and I hope someone finds this code useful.

Scrolling text in form title bar


Timer Task always return false

Question: I have this code
<code>ischanged = false;
    public void doTimerTaskforXML(final GeneralObject Gen_Obj) {
        XMLTimerTask = new TimerTask() {
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        String NewXML = "";
                        XMLParser parser = new XMLParser();
                        NewXML = parser.getXmlFromUrl(Gen_Obj.URL);
                        if (NewXML != null && NewXML != ""
                                && NewXML.length() > 0) {
                            if (!Gen_Obj.XML.equals(NewXML)
                                    || Gen_Obj.XML.length() != NewXML.length()) {
                                ischanged = true;
                                Log.i(TAG, "XMl has been changed");
                            }
                        }
                    }
                });
            }
        };
        XMLTimer.schedule(XMLTimerTask, 0, 60000);
        Log.i(TAG, "XNL not change");
    }

    public boolean IsChanged(GeneralObject Gen_Obj) {
        doTimerTaskforXML(Gen_Obj);
        Log.i(TAG, "ischanged= " + ischanged);
        return ischanged;
    }
</code>
which check for xml change
When I call function IsChanged and take it's return it alwayes return false
what the wrong in this code
?
Answer: It looks as the method IsChanged executes completely before doTimerTaskforXML's run method is called. and thats why you get default value as false. You need to use sync approach, if you want the return value immediately in the same call.
Alternatively, ( async approach) you can implement AsyncTask class which is best for parsing xml  in background. It has two methods doInBackground and onPostExecute. You'll have to override both of them, put your parsing in doInBackground method and when the parsing is done onPostExecute callback will be run.
Comment: But I want to work this timer at different times, for example, the first time for 5 minutes the second time for 10 minutes, and so on
Comment: How I can do that using  AsyncTask ?
Comment: @user3604882 i didn't understood your codeflow. But I assume that IsChanged method is called only once, So can you avoid returning any boolean value from this method. Instead call another method when you set isChanged = true, to take actions based on that.

Timer Task always return false