How to query multiple users from LDAP

Question: How to query multiple users from LDAP.
I am using
DirContext.search(base,filter,scope); in my java program
as of now its working fine with one value filter. filter=("uid=name")
but my requirement is to pass multiple names to the filter at a time like
filter=("uid=name1,name2,name3....")  .

Comment: Possible duplicate of [Ldap filter multiple UIDs](http://stackoverflow.com/questions/30486333/ldap-filter-multiple-uids)
Answer: LDAP uses a "PREFIX" notation for its filters.
For example:
OR condition
(|(attr1=val1)(attr2=val2)(attr1=val2))

AND condition
(&(attr1=val1)(attr2=val2)(attr1=val2))

In your case, the filter criteria will be this:
filter = "(|(uid=name1)(uid=name2)(uid=name3))"

The above filter means:

Find any user who has uid=name1 OR uid=name2 OR uid=name3.

This should list you users whose user IDs are name1, name2 or name3.

More Exmples:
Equality: (attribute=abc)     , e.g. (&(objectclass=user)(displayName=JohnDoe))
Negation: (!(attribute=abc))     , e.g. (!objectClass=group)
Presence: (attribute=*)        , e.g. (mailNickName=*)
Absence:  (!(attribute=*))        , e.g. (!proxyAddresses=*)
Greater than: (attribute>=abc)    , e.g. (storageQuota>=100000)
Less than:    (attribute<=abc)    , e.g. (storageQuota<=100000)
Proximity:    (attribute~=abc)    , e.g. (displayName~=JohnDoe)
*(~= may not be compatible with all directory servers !!)
Wildcards:    e.g. (sn=J*) or (firstname.lastname@example.com) or (givenName=*John*)

Hope this helps!
Comment: Is there a limit to how many ids that can be passed in? Would 2000 userids be unreasonable?

How to query multiple users from LDAP


Google Search Appliance: Limiting Number of Results

Question: I am attempting to limit the number of results that are displayed as a result of dynamic result clustering on the Google Search Appliance. I've looked through the XSLT, but I've only come across the following two user-modifiable options:

<xsl:variable name="show_res_clusters">1</xsl:variable>
<xsl:variable name="res_cluster_position">right</xsl:variable>
Are there more options that I'm unaware of that I could use to limit the results? Is there another way that I'm missing?
Answer: I found the answer. You simply edit out the XSLT that generates the HTML for where the results are rendered. I tried this yesterday, but it didn't work (not sure what is different about today).


What is the relation between $\mathbb{C}[M]$ and $\mathbb{C}[M/U]$.

Question: Let $M$ be a variety and let $U$ be a group. By definition, $M/U$ is the space of all $U$-orbits of $M$. Now we take coordinate rings $\mathbb{C}[M]$ and $\mathbb{C}[M/U]$. What is the relation between these two rings? What are the elements in $\mathbb{C}[M/U]$ look like? Thank you very much.
Answer: If $U$ acts on $M$, then it acts on $\mathbf{C}[M]$ too. $\mathbf{C}[M/U]$ "ought to be" the subring of fixed points of $U$; think of them as functions on $M$ that are constant when restricted to orbits of $U$. I don't know if there are any technical subtleties that will cause problems in the algebraic geometry setting.
Answer: Given your action of $U$ on $M$, there exists in the  category of topological spaces a quotient topological space $M/U $and a continuous map  $\pi: M\to M/U$ with all sorts of nice properties.
The catch, however is that in general there is no reasonable way to endow $M/U$ with the structure of complex manifold:
A counterexample is $M=\mathbb C^n$ and $U=GL_n(\mathbb C)$ acting in the obvious way.
The quotient topological space has two points, one  corresponding to the set $\mathbb C^n \setminus \{0\}$ of non-zero vectors and the other to the singleton set $\{0\}$.
It is connected but not Hausdorff and there is no reasonable  structure of complex manifold on that quotient.
A reasonable sufficient for a quotient manifold to exist is that $U$ be a Lie group and that the action be free and proper.
Examples are $U=$discrete group,  which yields a covering space, but also the non discrete $U=\mathbb C^*$ acting on $\mathbb C^n \setminus \{0\}$ and yielding projective space $\mathbb P^ {n-1}(\mathbb C)$.
The case of algebraic varieties (or rather schemes) is a whole branch  of algebraic geometry: Mumford wrote a book on the subject which earned him a Fields medal in 1974.
Answer: If $M$ is an affine variety and $U$ is a finite group then $M/U$ is also an affine variety (this is proved by Hilbert - Noether in a more general settings). More generally, if $U$ is a reductive group then $M/U$ is an affine variety (this result is due to Nagata). In this case, $\mathbb{C}[M/U] = \mathbb{C}[M]^U,$ the invariant subring of $\mathbb{C}[M].$ But for general group $U,$ the invariant subring $\mathbb{C}[M]^U$ may not be finitely generated algebra over $\mathbb{C}$ and hence it will not have any variety structure. For the case of projective variety, there are notions of good quotient and geometric quotient. This branch of algebraic geometry is called Geometric Invariant Theory. You can look at "Introduction to Moduli Problems and Orbit Spaces" by P. E. Newstead.


How do I use ldapdelete to delete an improperly set up olc database?

Question: I've been walking through this tutorial and kept getting errors -- likely because I was typing it in manually -- so I retried, executing it after entering in
# Load dynamic backend modules
dn: cn=module,cn=config
objectClass: olcModuleList
cn: module
olcModulepath: /usr/lib/ldap
olcModuleload: back_hdb

# Database settings
dn: olcDatabase=hdb,cn=config
objectClass: olcDatabaseConfig
objectClass: olcHdbConfig
olcDatabase: {1}hdb
olcSuffix: dc=example,dc=local
olcDbDirectory: /var/lib/ldap

It worked, so I typed in the rest and re-executed:
sudo ldapadd -Y EXTERNAL -H ldapi:/// -f backend.example.com.ldif

and now it says
ldap_add: Other (e.g., implementation specific) error (80)
    additional info: <olcSuffix> namingContext "dc=home,dc=local" already served by a preceding hdb database

Which, as I would guess, means that it can't complete the ldapadd because one already exists under the same name.
I tried deleting it using (from here):
sudo ldapdelete 'dc=example,dc=local'

and it's asking for a password, of which my password doesn't work and there was nothing set as the olcRootPW in the initial setup.
How do I use ldapdelete in this context so I can re-setup this database?
Answer: Generally the initial setup process for cn=config isn't very easy and there are plenty of ways to shoot yourself in the foot in the process. However, remember that cn=config is stored in LDIF format files in slapd.d (usually in ${prefix}/etc/openldap/) and can be edited by hand (carefully and while slapd isn't running). So if you've locked yourself out (no RootDN/RootPW) or completely mangled your cn=config somehow, you can always fix it there.
A good way to get a basic config going is to actually do it in the old style slapd.conf fashion and then convert it to slapd.d (using slaptest -f -F) once the basic stuff (databases, modules and a RootDN/RootPW) is sorted.
Comment: Oh my God I have been avoiding a problem of duplicated `ppolicy` overlays for six months now and you have just ... wow ... thank you!!!
Comment: According to [this thread](https://www.openldap.org/lists/openldap-technical/201307/msg00219.html) `cn=config` simply does not support deletions until slapd 2.5
Answer: Wasn't able to figure out how to delete the database, but I had just started so I purged slapd and ldap-utils.
sudo apt-get purge slapd ldap-utils

and reinstalled.
Comment: Downvoted because although uninstalling and then reinstalling may work, it is rarely the correct answer. What Ignmar said below is much better advice.


Router link is being called all the time

Question: I have the below code
 routerLink="{{onSelect(id)}}.

this method is being called all the time, and when i click to go to another tab this takes over, is there anyway in angular that this function will be called only when i click or right-click(new Tab)?
Thanks in advance!
My code is like this
HTML{{prod?.name}}
Ts.
onSelect(prod){
    setTimeout(() => {
        this.onSelectedEmmiter.emit(prod);
      }, 0);
}
SO i can not use (click) cause i need the option to open new tab in right click.
Using return [`/x/x/] or navigate work only the first time

Comment: Why wont you just call `(click)="onSelect(id)"` on your tabs?
Comment: i need the option to open the new tab with right click.
Answer: You are using it wrong . I should be (click)="onSelect(id)" (assuming that onSelect is supposed to respond to used click). Besides that, answer to WHY it is called all the time:
This is because that particular binding is evaluated every time on the change detection cycle. Such cycle is started on every mouse/keyboard event as async task completion.
Comment: i need the option to open the new tab


how to pass arguments into a nested class in python

Question: I have the following model:
def get_my_model(name1, name2):
    class MyModel(Model):
       class Meta:
             table1 = name1
             table2 = name2
    return MyModel

I am trying to write this without the function and want to pass the arguments name1 and name2 directly to the Meta class but I'm not sure how. I tried using constructors but it somehow doesn't work.
class MyModel(Model):
       def __init__(self, name1, name2):
             self.name1 = name1
             self.name2 = name2

       class Meta:
             table1 = self.name1
             table2 = self.name2

I also tried setting the constructor on the meta class but didn't work either. Anyone an idea?
Comment: There are no metaclasses here... Do you mean the class nested inside your `MyModel` class that is named `Meta`?
Comment: It can be hacked to work with metaclasses too, but it is **not** related to metaclasses; if you want to use metaclasses regardless, I suggest you read [this great post](https://stackoverflow.com/a/6581949/11647025) about them.
Comment: Why did you think the `__init__` in `MyModel` would be at all related to some nested class, `Meta`? I'm assuming this is django related? Outside fo that, nested classes aren't often used in Python. In any case, it isn't exactly clear what behavior you are expecting
Answer: TL;DR:

any reachable variable from MyModel or any higher scope's variable up from the class named Meta, that's already defined
modify ModelBase's metaclass (patch the file or inherit from)

It's not a metaclass! It's just a class in other class's scope named Meta. What's happening is that Python has separate contexts/scopes once the execution environment starts building:

interpreter
global (the original namespace you're given once you start the interpreter, globals())

then the nested ones within the global namespace:

module/file
class
function
perhaps some other(s)

You can't pass a parameter to the Meta class because it's just declared in there. It's not called. Parallel to this would be passing a parameter to a class declaration from the module scope:
# module.py
class MyClass:
    value = <how?>

Once you find the place where it's called, then you can inject the parameters by modifying the caller function.
class Main:
    class Meta:
        def __init__(self, *args, **kwargs):
            print("Meta", args, kwargs)

    def __init__(self, name):
        Main.Meta(name)

print(Main(123))

If I don't explicitly call Main.Meta(), the Meta class in this example won't be instantiated.
In case of Django, the Meta class is pulled via getattr() for the model class here, therefore you need to target ModelBase.__new__() with super()/copy-paste to modify the function so it accepts custom arguments, or, pass them as just class variables (how it's mostly done in Django / DRF).
class Main:
    class Meta:
        class_var = 123

Judging from the implementation of Model class in Django you might be able to swap the metaclass value, but I'm not sure about the inheritance as the __new__() of a metaclass is executed when you declare the class that uses it:
# the original ModelBase from class Model(metaclass=ModelBase)
class Meta(type):
    def __new__(cls, *_, **__):
        print("Hello")
        return cls

class MyMeta(Meta):
    def __new__(cls, *_, **__):
        print("Hi")
        # implement your stuff here or copy-paste + patch
        return cls

class Model(metaclass=Meta):
    pass

class CustomModel(metaclass=MyMeta):
    pass

class CustomModelWithInheritance(Model, metaclass=MyMeta):
    pass

For metaclasses check:

this question
this essay
docs
its tests

Regarding self: The naming itself doesn't matter, nor will work where you use it, because the self is just an implicitly passed instance of a class into a method (a function with a reference to a class instance):
class MyClass:
    def func(self_or_other_name):
        print(self_or_other_name)
MyClass().func()

The same way behaves a cls argument in a __new__() method when creating a class within a metaclass i.e. it's a reference to the metaclass instance (a class declaration in a namespace), for which the "description" is the metaclass that creates it.
cls = type("MyClass", (), {})  # create an instance of "type"
cls  # <class '__main__.MyClass'>
# "cls" is class and an instance at the same time

The only "special" variable you can use to refer to the class scope are locals() + anything defined within the class scope as a variable + anything in a higher scope be it from a nested class, module or others:
Edit:
So for the class variable it was a screw up, this is the correct explanation. For your case it'll be either a function or metaclass patching because we're dealing here with finding the beginning of a "chicken & egg" problem. And that we can do by either looking from above - introducing a function scope and setting values prior the defining of the upper class is finished -, or looking from inside of the creation process (metaclass).
We can't use a class variable, because we're still in the process of defining a class. We also can't use the __init__ to reference the class (or Meta nested class) to inject a value there, because we're already in a situation where the metaclass' __new__() method has already been executed, thus anything you set there may be used in your case, but won't be present while creating the MyModel class.
class MyModel(Model):
    def __init__(self, name):
        MyModel.name = name  # MyModel not defined yet
        # but we can use self.__class__ in the post-poned execution
        # once MyModel is defined (case when calling __init__())
    # we haven't even started to define the Meta nested class

    # starting to define Meta nested class
    class Meta:
        # MyModel not defined yet because the code block
        # of MyModel class isn't finished yet
        table = MyModel.name
        # can't reference because it doesn't exist yet,
        # same applies for Meta, the only thing you have now is
        # the __qualname__ string

But!
from pprint import pprint

class RealMetaClass(type):
    def __new__(cls, *_, **__):
        # create a new class - "Main" because it uses "metaclass" kwarg
        new_class = super().__new__(cls, *_, **__)
        # once we have the "Main" class, we can reference it the same way
        # like *after* we define it the normal way
        nested_meta = getattr(new_class, "NestedClassNamedMeta")

        # ~= pprint(getattr(Main, "NestedClassNamedMeta"))
        pprint(("in metaclass", nested_meta))
        pprint(("in metaclass", dir(nested_meta)))
        pprint(("in metaclass", vars(nested_meta)))
        return new_class

class CustomMetaClass(RealMetaClass):
    def __new__(cls, *_, **__):
        new_class = super().__new__(cls, *_, **__)
        nested_meta = getattr(new_class, "NestedClassNamedMeta")
        # set a new class variable without affecting previous __new__() call
        new_class.custom_thing = getattr(nested_meta, "custom_thing", None)
        # do my stuff with custom attribute, that's not handled by Django
        return new_class

class Main(metaclass=RealMetaClass):
    pprint("defining Main class")

    def __init__(self, name):
        pprint(("in instance", self.__class__.NestedClassNamedMeta.name))
        # works, because it's called after the Main class block
        # is finished and executed i.e. defined
        self.__class__.NestedClassNamedMeta.new_value = "hello"

    class NestedClassNamedMeta:
        name = "John"
        custom_thing = "custom"

class CustomMain(Main, metaclass=CustomMetaClass):
    class NestedClassNamedMeta:
        name = "John"
        custom_thing = "custom"

instance = Main("Fred")
# custom_thing is ignored, not added to instance.__class__
pprint(("after init", vars(instance.__class__), vars(instance.NestedClassNamedMeta)))

instance = CustomMain("Fred")
# custom_thing is processed, added to instance.__class__
pprint(("after init", vars(instance.__class__), vars(instance.NestedClassNamedMeta)))

Comment: Welcome, hopefully it helps! If you by any chance find a way for `CustomModelWithInheritance(Model, metaclass=MyMeta)` feel free to ping or edit. I has to work somehow, but I'm probably too tired for today and missing some basic silly thing :D Also, `Meta` in Django and DRF from what I've observed, is just a fancy dictionary so you don't need to use custom functions to prepare the model, or in other words, the core-devs just moved the logic to more abstract layer to make it more user-friendly and automatic.
Comment: woaaaahhhh,thank you so much for the long answer!
Comment: @Tom please check again after the edit, the class variable won't work. Or at least not in the way you might expect it to work (have values in a `ModelBase` metaclass).
Comment: @Tom also, re the inheritance, as I've thought, silly thing, I forgot adding `(type)` so the class inherited from `object` instead of type, thus the MRO borked.


"Private key is missing or invalid. It should be service " when making BigQuery call with credential

Question: I'm following this data prediction using Cloud ML Engine with scikit-learn tutorial for GCP AI Platforms. I tried to make an API call to BigQuery with:
def query_to_dataframe(query):
  import pandas as pd
  import pkgutil
  privatekey = pkgutil.get_data('trainer', 'privatekey.json')
  print(privatekey[:200])
  return pd.read_gbq(query,
                     project_id=PROJECT,
                     dialect='standard',
                     private_key=privatekey)

but got the following error:
Traceback (most recent call last):
  [...]
TypeError: a bytes-like object is required, not 'str'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/root/.local/lib/python3.7/site-packages/trainer/task.py", line 66, in <module>
    arguments['numTrees']
  File "/root/.local/lib/python3.7/site-packages/trainer/model.py", line 119, in train_and_evaluate
    train_df, eval_df = create_dataframes(frac)
  File "/root/.local/lib/python3.7/site-packages/trainer/model.py", line 95, in create_dataframes
    train_df = query_to_dataframe(train_query)
  File "/root/.local/lib/python3.7/site-packages/trainer/model.py", line 82, in query_to_dataframe
    private_key=privatekey)
  File "/usr/local/lib/python3.7/dist-packages/pandas/io/gbq.py", line 149, in read_gbq
    credentials=credentials, verbose=verbose, private_key=private_key)
  File "/root/.local/lib/python3.7/site-packages/pandas_gbq/gbq.py", line 846, in read_gbq
    dialect=dialect, auth_local_webserver=auth_local_webserver)
  File "/root/.local/lib/python3.7/site-packages/pandas_gbq/gbq.py", line 184, in __init__
    self.credentials = self.get_credentials()
  File "/root/.local/lib/python3.7/site-packages/pandas_gbq/gbq.py", line 193, in get_credentials
    return self.get_service_account_credentials()
  File "/root/.local/lib/python3.7/site-packages/pandas_gbq/gbq.py", line 413, in get_service_account_credentials
    "Private key is missing or invalid. It should be service "
pandas_gbq.gbq.InvalidPrivateKeyFormat: Private key is missing or invalid. It should be service account private key JSON (file path or string contents) with at least two keys: 'client_email' and 'private_key'. Can be obtained from: https://console.developers.google.com/permissions/serviceaccounts

When the package runs in local environment, the private key loads fine, but when submitted as a ml-engine training job, the error occurs. Note that the private key fails to load only when I use GCP RUNTIME_VERSION="1.15" and PYTHON_VERSION="3.7", but can load with no problem when I use PYTHON_VERSION="2.7".
In case it's useful, the structure of my package is:
/babyweight
    - setup.py
    - trainer
        - __init__.py
        - model.py
        - privatekey.json
        - task.py

I'm not sure if the problem is due to a bug in Python, or where I placed privatekey.json.
Comment: I agree with @JohnHanley. To solve the bytes problem you need to encode it as utf-8. Why do you need to use this private_key attribute? Maybe you can use the credentials attribute
Comment: @mlo Feel free to summarize this as an answer or let me know if I can that
Comment: 1) Convert the string to bytes: `private_key=privatekey.encode('utf-8'))`. 2) What is privatekey.json? Is this a Google Service account JSON key file or something you created?
Comment: @JohnHanley yes privatekey.json is used to make calls to BigQuery API.
Comment: @rmesteves following your suggestion I changed from `private_keys` to `credentials` attribute as shown [here](https://pandas-gbq.readthedocs.io/en/latest/howto/authentication.html), and then build an absolute path to privatekey.json as shown [here](https://stackoverflow.com/questions/40416072/reading-file-using-relative-path-in-python-project/40416154). Now the job is able to run without error.
Answer: I was able to solve the problem after I changed read_gbq's attribute for reading BigQuery access key from private_keys to credentials, as recommended by @rmesteves, and as shown here. I then set the value as the absolute path to privatekey.json, as shown here. Now the job is able to run without error.
Note: I only encountered this problem with Python 3+, but not with Python 2.7. I'm not sure why. It could possibly be due to the implementation of read_gbq.


Confusion in Softmax function in CNN

Question: I have recently started working on binary classification using Convolution Neural Network (CNN). While training i am getting two outputs a Binary error (BinErr) and the output of the loss function (Objective) of softmax classifier which is converging to zero.

Studying about the softmax classifier first, I understand that in the machine learning we have to minimize the objective function w.r.t to the parameters (weights and bias). The Objective function consists of loss function and regularization function. I found these slides for the understanding of softmax.
The Loss function of the Softmax classifier is defined as:
\begin{equation}
p_j = \frac{e^{o_j}}{\sum_k e^{o_k}}
\end{equation}
I couldn't understand after that as in the slides $o$ is shown that it is the output of the final layer of the NN and first input to softmax classifier and the second input $y$ is the actual features.
I am totally confused how it works about that. Anyone can help me to understand how softmax works in the CNN.
Answer: The formula you've written is not a loss function; it's just the formula for softmax.
The softmax activation is normally applied to the very last layer in a neural net, instead of using ReLU, sigmoid, tanh, or another activation function. The reason why softmax is useful is because it converts the output of the last layer in your neural network into what is essentially a probability distribution. If you look at the origins of the cross-entropy loss function in information theory, you will know that it "expects" two probability distributions as input. That's why softmax output with cross entropy loss is very common.
Just to reiterate; softmax is typically viewed as an activation function, like sigmoid or ReLU. Softmax is NOT a loss function, but is used to make the output of a neural net more "compatible" with the cross entropy or negative log likelihood loss functions.

Confusion in Softmax function in CNN


"public" not supported or disabled in libcurl error

Question: I'm learning how to create a custom JSON migration and referring to the migrate_json_example module, I see the following code in migrate_plus.migration.product.yml.
urls:
    - 'public://migrate_json_example/products.json'
  # An xpath-like selector corresponding to the items to be imported.
  item_selector: product

Can someone please tell me how to use that public:// part of the URL?
I understand it's a path to the JSON file, but it's a relative path. I don't know how public:// is handled and how Drupal knows where to look for the files.
Both modules are installed on the same site. However, when I try using the same public:// URL in my module, I get the following error.

Error message: cURL error 1: Protocol "public" not supported or disabled in libcurl (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) at public://migrate_stuff/resources/people1.json.
Answer: public:// is the sites public file system path. You can change it by navigation to admin/config/media/file-system.
    There you can set the public file system path, the default path is sites/default/files.
Comment: Thank you. I see my mistake now
Comment: For anyone else referring to this question, my mistake was I thought the migrate code was reading the json file located in the example module. However, in the module.install file, the json is copied into sites/default/files where it actually reads from - hence public:// makes complete sense.


Understanding the Taylor expansion of a function

Question: Suppose
$$f(x) = \frac{1}{1+x^2}$$
We know this function is defined everywhere and is continuous everywhere and so on...
Using the geometric series, we can write
$$ \frac{1}{1+x^2} = \sum (-x^2)^n = \sum (-1)^n x^{2n} $$
But, this only converges iff $|-x^2|<1$ iff $|x|<1$. Why does this converge only in $(-1,1)$ when we know it is defined everywhere, though?
Comment: You can also create other series representations that will work on different intervals: $\sum_n f^{(n)}(a)/n!(x-a)^n$. That will possibly converge on some interval centered at $a$.
Answer: This is a great question.  It shows in a nutshell why analysis should be done in the complex plane, not on the real line.
The function $f(x) = \dfrac{1}{1+x^2}$ is defined everywhere on the real line, as you pointed out — but it is not defined everywhere on the complex plane.  In particular, it's not defined at $x=i$ or $-i,$ because the denominator becomes $0$ for those values of $x.$
The Maclaurin series for this function, $\sum_{n=0}^\infty (-1)^n x^{2n},$ has a circle of convergence in the complex plane, centered at the origin.  This circle cannot have radius greater than $1,$ since the series doesn't converge at $i$ and $-i,$ which are at a distance of $1$ from the origin.
In fact, the circle of convergence for this power series is the unit circle.  That means that it will converge everywhere inside the unit circle, and it will diverge everywhere outside the unit circle.  (As for points on the circumference of the circle, you would need to look more closely to see for which of those it converges and for which it diverges.)
For completeness, I should add that not every Maclaurin series has a circle of convergence: some converge everywhere, and some converge only at the origin.  But between these two extremes, there will be a circle centered at the origin such that the series converges inside the circle and diverges outside the circle (with the points on the circumference requiring further investigation).
Comment: In particular, Hadamard (i believe) showed that if $f$ is analytic on a domain in $\Bbb C$, and is maximally extended (that is, there is no analytic function $g$ defined on a larger domain that is equal to $f$ on its domain), then the Taylor series of $f$ at some point $a$ will have a radius of convergence equal to the distance from $a$ to the nearest point not in the domain of $f$.
Comment: @celtschk "A function that only converges at the origin certainly has a circle of convergence; that circle has radius $0.\!"$ Sure, but if I hadn't spelled out that special case, somebody would have posted to say I was wrong, that that's not a circle!  (And they would have been right.)  The situation is similar for the case where the radius of convergence is infinite.
Comment: @Mehrdad If you enjoy this type of material, I highly recommend reading some complex analysis, or taking a course in it. It may be the most beautifully coherent theory in all of mathematics (and I say this as someone who specialized in mathematical logic, not analysis).
Comment: It is clear what the last paragraph means, but is there any theorem about power series that would fail if radii $0$ or $\infty$ were included?
Comment: One thing that's always confused me is why we look at *radii* of convergence. Why radius (implying a circle)? Why not a rectangle, or a star, or some other shape? Would you mind addressing this if possible? I ask because merely saying that the radius on the imaginary axis is 1 doesn't really say anything about the radius on the real axis to someone who doesn't already know the answer...
Comment: A function that only converges at the origin certainly has a circle of convergence; that circle has radius $0$.
Comment: @zyx asked: "...is there any theorem about power series that would fail if radii $0$ or $\infty$ were included?"  Of course in some sense these are just circles of radius $0$ or $\infty,$ so there isn't really a difference. On the other hand, if the radius of convergence is $0,$ then there's no region on which the series converges, and if the radius is $\infty,$ the power series represents an entire function, and all the theorems about entire functions apply to it.
Comment: @Mehrdad This isn't an arbitrary convention. There's a theorem: If a power series $\sum_{n=0}^\infty a_n z^n$ converges at a point $z_0,$ then it converges for all $z$ of magnitude $\lt|z_0|.$ If it diverges at a point $z_0,$ then it diverges for all $z$ of magnitude $\gt|z_0|.$ It follows that there's a circle $C$ centered at $(0,0)$ such that the sum converges in the interior of $C,$ and diverges in the exterior of $C$ (no claim is made about convergence/divergence for points on the circumference), with the caveat that it's possible for $C$ to be a "circle" of radius $0$ or radius $\infty.$
Comment: @Mehrdad Other series, of different forms, may have differently-shaped regions on which they converge: a circle centered at a point other than the origin, the exterior of a circle, a half-plane, etc. For example, for a half-plane, check out a series of the form $\sum_{n=0}^\infty a_n e^{nz}$ (which can be viewed as a power series in $e^z).$
Comment: @MitchellSpector: You should mention this in the answer! :) What theorem is this?
Comment: @Mehrdad I think it's called the Cauchy-Hadamard theorem. This was mentioned in Paul Sinclair's comment. It's a staple in any complex analysis book.  (As I recall, Ahlfors' text does it well, but it's been many years since I've looked at that book, and the theorem is covered in many other books too.)
Comment: @MitchellSpector: Thanks!! I haven't taken complex analysis so I guess that's why I didn't know it :) it just always bugged me ever since I started doing series in high school since it came with zero explanation.
Comment: @MitchellSpector: Of course the circle with radius $0$ is a circle. That's unlike the case of radius infinity, where there's indeed no circle, as there are no points at infinite distance of a given point.
Comment: @celtschk Yes, you could argue that the "circle" with radius $0$ is a circle, and in some cases (like the one here) that would make sense, although if someone wanted to count it as a circle in a mathematical paper, they would specify that for clarity (it's an edge case that people might or might not consider a circle in practice).  But it differs in some important ways from a circle of radius $\gt 0;$ for example, its interior isn't a region (a region is defined as a *non-empty* connected open set).  [And if I had called it a circle in my answer, someone would still have objected to that too.]
Comment: That shifts the question to whether there is any situation where non-emptiness of the interior of the circle is important.  The empty set is open and connected, and the circle of radius R=0 does contain all circles of smaller radius (which are empty) in its interior.
Comment: @celtschk It's just a minor question of nomenclature, of the sort that would, for clarity's sake, be spelled out one way or the other in any paper that relied on whether the term "circle" should be taken to include circles of radius $0$ or not. (The interior being empty isn't a trivial difference though; you can't usefully integrate around the circumference, for instance. In general, if you admit these $0$-radius circles, you're  going to have to be very careful that everything you claim for circles is really true for them too. )
Answer: The series $\sum_{n=0}^\infty (-1)^nx^{2n}$ is the power series representation on $(-1,1)$ of the function $f(x)=\frac{1}{1+x^2}$.
The series does not represent the function $f$ for $|x|\ge 1$.
We can find a series representation of $f(x)$ that is valid for $|x|>1$.  To do so, we write
$$\begin{align}
\frac{1}{1+x^2}&=\frac1{x^2}\frac{1}{1+1/x^2}\\\\
&=\frac1{x^2}\sum_{n=0}^\infty (-1)^nx^{-2n}\\\\
&=\sum_{n=0}^\infty (-1)^n x^{-2(n+1)}
\end{align}$$
which converges for all $|x|>1$ and diverges elsewhere.
Note that the latter series is given in terms of reciprocal powers of $x^2$.  If $x$ is extended to be complex, this is the Laurent series for $|x|>1$.
Answer: A more graphical interpretation for this case. Not a proof, more insights.
Mostly because $f$ is a function that tend to $0$ at $\pm \infty$. This is not a natural behavior for polynomials, and even less so when they have higher degrees.
However, the function is very smooth far away from $\pm \infty$, that is, around $0$. Here, higher degree polynomials fit the function much better, even more at higher degrees. This is illustrated in the following pîcture, the top one showing that the behavior is very different between $0$ neighborhoods or $+ \infty$, the bottom one only at the vicinity of $0$.

The quality of the approximation, and the radius of convergence, is highly related to the behavior of the coeficients $a_n$ multiplying the terms  $x^n$. Here, the  reason why the border is at $x=1$ is due to the fact you have $|a_n|=1$, which leads to a divergence of the series at $x=\pm 1$. Would the coefficients decrease at a different speed  (for instance $|a_n|\sim \frac{1}{r^n}$), this would modify the radius of convergence to $r$.
Comment: This argument is not completely convincing. For example, the Maclaurin series for $g(x)=e^{-x^2}$ has infinite radius of convergence, and still $g(x) \to 0$ as $x \to \pm\infty$...
Comment: @HansLundmark My answer needs caveat, true


Como faço para o video do POP-UP pare ao fechar a janela da pagina?

Question: Bom, eu não tenho muito experiência em HTML, jÁ tentei e não consigo fazer com que o video pare de ser reproduzido ao fechar a janela do POP-UP.
Se alguém puder ajudar ou dar uma dica agradeço.

<!DOCTYPE html>

          <button type="button" class="close full-height" data-dismiss="modal" aria-hidden="true">X</button>

Donna Galletta- Showreel

Answer: Olá! Para fazer o vídeo parar é necessário incluir a API do player do Youtube e chamar a função stopVideo() via javascript.
No link do vídeo no iframe é necessário acrescentar o parâmetro enablejsapi=1. Também acrescentei um id="player" apenas para facilitar a chamada no javascript.

Depois você precisa chamar o script do frame API:

e criar o script para manipular o player:

Ficou assim no final:

<!DOCTYPE html>

          <button type="button" class="close full-height" data-dismiss="modal" aria-hidden="true">X</button>

Donna Galletta- Showreel

Abraço!
Comment: Mas seu eu tiver algo assim, como que faço?

Comment: Nesse caso, dentro do script, vc pode apagar a parte de criação do player e substituir o `player.stopVideo();` dentro do evento de clique por `var media = document.querySelector("#player"); media.pause(); media.currentTime = 0;`. E acrescentar também um `id="player"` na tag
Comment: Valeu! Obrigado pela ajuda! Funcionou pra mim!


Changing the colour of selectInput entries in Shiny R

Question: I have the following code:
library(shiny)

# Remove all numbered colour names
col.list <- colours()[!grepl("\\d", colours())]

ui <- fluidPage(
  selectInput(inputId = "col",
              label = "Colour",
              choices = col.list, selected = "maroon"),
)

server <- function(input, output) {

}

shinyApp(ui = ui, server = server)

It creates the following ui control:

It's a list of all R colours (excluding the numbered ones).
Is it possible to make it that each entry is coloured according to the actual colour, instead of all being black?
Comment: See [this](https://groups.google.com/forum/#!topic/shiny-discuss/1DXjpB_uaRA).  Answer by Dean Attali, so probably reliable.
Answer: Maybe you can try shinyWidgets package where you an style it inside the choicesOpt. change the background argument to color if you want to change the color of the entries and not the background
library(shiny)
library(shinyWidgets)
col.list <- colours()[!grepl("\\d", colours())]
colors <- paste0("background:",col.list,";")

ui <- fluidPage(
    pickerInput("col", "Colour", multiple=T, choices = col.list,
                choicesOpt = list(
                    style = colors))
)

server <- function(input, output){}

shinyApp(ui, server)


Chord Notation: Superscript number in brackets

Question: I'm a beginner piano student and have come across a type of chord notation I'm not familiar with, and can't find anything on the internet.
Below is a photo of part of the chord chart for the worship song 'A thousand Hallelujah's by Brooke Ligertwood.

I believe the superscript numbers mean 'add the 2nd degree of the tonic scale' - so G♭² is a G♭ major chord with the 2nd degree of the G♭ scale added. That is, Gb - Ab - Bb - Db.
What does it mean when a superscript number has brackets around it though? E.g. A♭⁽⁴⁾?
Thank you!
Comment: This is just a guess: It could be that the 2 without brackets means suspended 2nd, which means there's no third - as in Gb - Ab - Db, and the (4) with the brackets means it's an added 4th, with the third also, as in Ab - C - Db - Eb. One reason why I'm suggesting that is if you imagine this being played on guitar with a capo on the first fret and played in C, and then you leave a finger on the first fret (above the capo) of the B string and then play these chords while leaving that finger there, you would get Db (C with capo), Gbsus2 (Fsus2), and Abadd4 (Gadd4).
Comment: I guess @ToddWilcox is already writing an answer. I should add that the superscripts, subscripts and parentheses don't matter, they are used only help to make the symbol easier to read. See also https://music.stackexchange.com/questions/86953/standard-chord-naming-conventions for some better examples of notating chords.
Comment: OP, if you're satisfied you know the answer now, please consider [writing an answer to your own question](https://music.stackexchange.com/help/self-answer) so this post can be marked as answered.
Comment: Based on this video, I think my theory might be right, although it doesn't look like she's holding the C for the Abadd4: https://youtu.be/XM6Ap_JuJlk
Comment: This video is better, and I think this is the person who came up with the guitar part, which is where the chord shapes came from: https://youtu.be/MYHdgEa493g If you're going to do this in a band, I suggest talking to the guitarist about what they intend to play to make sure your keyboard part goes with it. If you're doing it alone, then I'd suggest playing around with sus2, sus4, add2, and add4 and see what sounds best to you.
Comment: This is really helpful advice @ToddWilcox. Not being a guitarist I would never have thought to check how these cords might interact with a capo! Thank you!
Comment: I've been searching through the public domain scores on the SongSelect website (where the above score originated), but I can't find any that use those symbols. However, I found several "sus" markings, which is the standard abbreviation for sus4. That would suggest that the parenthetical (4) is not a "sus4", though it's possible their scoring isn't wholly consistent.
Comment: @Aaron thanks for the sleuthing! From the other scores I've looked at form SongSelect I also believe they aren't consistent across different songs.
Comment: It could even be just an alternative chord - either use Ab or use Ab sus,  but that would only work when everyone playing agreed on which chord they were all going to play. Since Ab is the dominant, it could also be a strange way to write Ab11.
Comment: I've talked with a music teacher friend of mine who is familiar with this song, and with the SongSelect database, and they confirmed that this is just a rarely used notation for a sus chord - that is, the number in brackets replaces the 3rd of the chord.
Answer: Based on discussions with a friend who is a music teacher, and is familiar with the SongSelect chart database, it seems that the brackets are a type of notation used for sus chords. That is, the number inside brackets is supposed to replace the 3rd note of the chord.
So A♭(4) is actually A♭sus4, or the notes A♭ - D♭ - E♭.


How to link (a menu item) to the RSS feed?

Question: In our Drupal installation there is a menu item for the RSS feed, pointing to path de/rss for the German feed.
This path appears unchanged in the frontend and is invalid, hence results in a 404.
The correct URL is /de/rss.xml or just /rss.xml.
Weird thing is, that Drupal accepts the non-working path, while it rejects the correct ones:

The path 'de/rss.xml' is either invalid or you do not have access to it.

What's going on?
Note: I'm using the i18n module. And when I call /de/rss.xml it gets redirected to /rss.xml.
Comment: Are you using i18n module? Is your site in multiple languages?
Comment: Yes. And when I call /de/rss.xml it gets redirected to /rss.xml.
Answer: If you're using i18n module, and after you have installed module Variable, you should enable the i18n_variable module (one of the i18n submodules that requires the Variable module, among others).
Then navigate to /admin/config/regional/i18n/variable (= the Variables tab within '
Multilingual settings'). There you'll be able to specify all sorts of variables for which you want multi language support enabled also, using an appropriate sub-tab there, such as for "Site information", "Menu settings", etc.). Within sub-tab other, there is also "RSS feed for front page" (=The RSS feed for the front page, default is rss.xml). That "other" sub-tab should be between "Menu Settings" (1st sub-tab) and "Site Information" (3rd sub-tab).
I'd be curious to hear if your issue is resolved after you enable that option (by checking the checkbox).
Comment: Thanks for the tipp. In *other* there's only _Pages or PHP code_. In the tab *Feed settings* there's only _Feed description_. I couldn't find _RSS feed for front page_ in any of the tabs /: Version is 7.35
Comment: Looks like we're making progress / coming close. I slightly enhanced my answer (added the 'i18n_variable' part of it). Can you confirm you have that submodule enabled also? And then provide another status update (comment)?
Comment: Module _Variable translation_ is enabled.
Comment: What's your answer to my PS in my comment in the question, ie: do you have only 1 language enabled (de) or maybe both "en" and "de" or so?
Comment: _de_ is default and _en_ is enabled as well.


How to extract part of RAW response body (not JSON!) in INSOMNIA Rest Client

Question: I am using the Insomnia REST client to debug some mobile API. I need to extract part of one value in the response body and put it into a second request.
Request
The request is an Oauth request for an authorization token. This request is normally sent from a mobile app.
Example Response
The backend responds with a redirect_uri that contains the authorization_code. This format is used in oauth when the request (normally in PROD) comes from a mobile app.
{
    "redirect_to": "redirect_uri=com.acme://oauth?client_id=abcde&response_type=code&scope=authenticate_user&authorization=H068bFHTXXXXXXXXXXX.....XXXXXXX"
}

How can I extract the value of the authorization parameter from this response in INSOMNIA?
** How can I extract only the part after "&authorization=....."**
I know how to extract the full value of the "redirect_to" JSON attribute. But then how to parse it? For example with a regex?
Answer: it is possible to do so, but it is kind of tricky. The most obvious way would be to use some plugin, but here is what I came up with:
Firt of all you need to make a variable which will save your response redirect_uri=com.acme ...  =authenticate_user&authorization=H068bFHTXXXXXXXXXXX.....XXXXXXX.
You can do this by pressing:

CTRL + E

This will open your environment variables, you can really make it in any enviroment, but probably the best would be to do in Base Enviroment so it is accessable no matter which environment you are using.
Create a variable like this:
placeholder variable
Then you need to get the redirect_uri by pressing the following keys between the quotation marks:

CTRL+SPACE

This will bring up the quick menu, where you can type Response and choose body attribute. Click on it, and set it like this.
I am pretty sure most people are familiar till this point.
Now you have saved the response to a variable you can use it. Navigate to the request where you want to use it, and you can type (basically in any field) {{ }}.
Inside this variable write the following (with your own variable name).
{{ redirect_uri.match('authorization=([^&]+)')[1] }}
This is basically javascript, using a simple regex to match the url parameter.
If you did everything correctly you will see something like this, and by clicking on it you should see your token.
Note: It might be red, until you get some values into the variable that you made.
I really hope it helps.


Como criar um conjunto de tabelas no banco de dados via PHP

Question: Eu estou com problemas enquanto a criação do banco de dados de forma automática via PHP.  Estou desenvolvendo um projeto em MVC da faculdade e queria importar o arquivo sql e através de uma query criar as tabelas.
Na parte anterior do código é feita a conexão com o banco de dados e também a criação do banco de dados também via query e ambos funcionam perfeitamente; porém na hora de criar as tabelas nada acontece nem erros, o código é o seguinte:
$sql = file_get_contents(BASE_URL."database/arquivo.sql");
echo $sql;
$this->connection->multi_query($sql);

Já tentei com query() e multi_query() e nada acontece, o que pode estar de errado?
Galera, o link do arquivo sql é esse: https://www.dropbox.com/s/edp8uhifnl2mw97/lapesa.sql?dl=0
está indicando o seguinte erro:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_' at line 12

Se eu deleto essa linha, o erro continua para as linhas seguintes, não estou conseguindo resolver.
Comment: Poderia colocar parte do conteúdo de arquivo.sql? veja se dessa forma retorna algum erro: `$res = $this->connection->multi_query($sql);
if(!$res){
   echo $this->error;
}`.
Comment: O conteúdo do arquivo sql é gerado pelo phpmyadmin, portanto não tem erros de sintaxe ou algo semelhante, só preciso gerá-lo automaticamente porque terei que exportar o projeto
Comment: Eu testei aqui parte do arquivo sql e tive o mesmo erro, então removi a cabeçalho(comentários) e na tabela `administrador` mudei a chave primária de `id` para `id_admin`
Comment: Havia esquecido de comentar isso na pergunta
Comment: A tela fica em branco? verificou se a exibição dos erros não está oculta.
Comment: A exibição de erros está habilitada e a tela não ficou branca, está mostrando toda a view montada
Comment: Poderá ser a sua connection...
Comment: ai funcionou perfeitamente?
Comment: perfeito, funcionou certíssimo
Answer: Testei aqui e todas as tabelas foram cridas mesmo com os comentários/cabeçalhos no arquivo. O único problema foi que em todas as tabelas a chave primária é id so que essa coluna não existe em nehuma tabela. Então você corrigir os nomes.
obs: suprimi alguns campos da tabela deixando apenas o id_algo
CREATE TABLE IF NOT EXISTS `administrador` (
  `id_admin` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Estrutura da tabela `apresentacao`
--

CREATE TABLE IF NOT EXISTS `apresentacao` (
  `id_apresentacao` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

O código do teste foi o seguinte:
$sql = file_get_contents('sql.sql');

if(!$db->multi_query($sql)){
    echo $db->error;
}else{
    echo 'tabelas criadas com sucesso';
}

Utilize multi_query() para processar várias instruções sql de uma só vez, lembrando que elas devem ser separadas por ponto e virgula.


How to get the frequency of a time-domain signal with limited sample length?

Question: Let's say there is a signal who only has one peak in its power spectrum. I would like to know the frequency at which the peak is (the magnitude of power is not important to me). But I only have very limited sampling length, which leads to a poor resolution in the frequency domain. Can I pad the time-domain signal with zeros before taking the FFT, to get an approximation?
For example, a time-domain signal $x(t)=sin(\omega t)$, where $\omega$ is around 5.5 $rad/s$. The total sample time T is 6.28s, (there is no way to increase T) which means the resolution in the frequency domain is $\frac{2\pi}{T}$ $rad/s$ $\approx$ 1 $rad/s$. If I only want to know the frequency of this time-domain signal (the magnitude is not important to me), can I pad it with zeros to get the approximate value?
Then what is the side-effect of doing so?
Comment: It is not clear because you are talking of a finite length discrete signal but then you say $x(t) = \sin(\omega t)$ which is a continuous time signal with infinite length. What is your sampled signal $y(n)$ ? Once you have it, you can use  zero-padding (and windowing) to find the frequency of the largest peak in $Y(k)$, but it won't be exactly the frequency of the largest peak of $X(f)$ (mainly because of the Shannon sampling theorem)
Comment: I'm not entirely clear with what you're trying to achieve. However it looks like you're up against the Heissenberg priciple. As you have limited sampling length you're bound to have poor resolution in the frequency domain.
Comment: @skyking sorry for confusion. Let's say a human operator moves a joystick, the position trajectory is mainly sinusoidal. I would like to know the motion frequency of the joystick. But the measurement time is very short, which means poor resolution. Due to this I can't get a good approximation of the true motion frequency. I'm thinking, if padding the measurement with zeros can help?
Comment: @user1952009 Sorry for the confusion. As for the example, the sample frequency is much higher than the signal frequency. The observation period is only a few seconds, 6.28s in this case. So the power of the signal would mainly show on 5 and 6 $rad/s$ in the discrete Fourier transform. Because there is only one peak in the power spectrum, would zero-padding the sampled signal achieve interpolation in the frequency domain (since doing so results in a peak between 5 and 6 rad/s) ? Can I use the peak's location revealed by the interpolation as an approximate of the true frequency of the signal?
Answer: The processing you are considering consists of three steps:

truncate the infinite signal $x(t)=\sin(\omega t),t\in \mathbb{R}$, to its part corresponding to the finite obsrcation interval $[0,T]$.
sample the truncated signal with a sampling period $T_s$, resulting in a finite length discrete-time sequence of $N=\lfloor T/T_s \rfloor$ samples.
extend the discrete time sequence to $M\geq N$ samples by zero padding and perform an $M$-point FFT to investigate its frequencies.

The limitations of this approach are mainly introduced at step $1$. When you truncate the infinite signal, you are essentially considering a "windowed" version of the original signal, of the form $x(t) w(t)$ where $w(t)=1,t\in [0,T],$ and $w(t)=0, t\notin [0,T]$. The Fourier transform of the windowed signal is the convolution $X(\omega)*W(\omega)$, with $W(\omega)$ a sinc-like function with a main lobe length that is inversely proportional to $T$. You need to have $T$ sufficiently large so that $W(\omega)\approx \delta(\omega)$, otherwise you will experience poor frequency resolution, which cannot be resolved, no matter what (discrete-time) signal processing you perform next on the windowed signal.
Actually, the discrete-time processing can only result in additional distortion. This will be the case when the sampling period $T_s$ is so large that aliasing occurs. However, even when the sampling period is sufficiently small so that the aliasing effect is negligible, using a large size FFT (i.e., $M\gg N$) will only increase the resolution of the sampled windowed signal and not the original signal.
Comment: Note that a (zero-padded or not) FFT essentially performs a sampling of the Discrete-Time-Fourier-Transform (DTFT) of the discrete-time signal. Introducing zero padding, i.e., increasing the size $M$ of the FFT, results in a more "dense" sampling of the DTFT. Note that all the frequency information about the discrete-time signal can be obtained by computing directly the DTFT. We typically compute the FFT instead, as it is more efficient. The accuracy of considering the peak of the DTFT as an estimate of the actual frequency is application-dependent, which you should investigate yourself.
Comment: @ W.Fu Thinking more about it, the peak of the DTFT will actually correspond to the actual frequency, *if the original signal consists of a single frequency*, as is the case here. Therefore, for a sufficiently large $M$, the frequency of the FFT peak will be close to that of the DTFT peak, therefore, it will provide a good estimate of the frequency.
Comment: Thank you! I understand the effects from step 1 and 2, but I have a question regarding the step 3. As the example in the question, the power of the signal would mainly show on 5 and 6 $rad/s$ in the discrete Fourier transform. However the true location of the peak (Dirac impulse) is 5.5 $rad/s$. Considering there is only one peak, so would zero padding before taking FFT just act as interpolation (as doing this results in a peak between 5 and 6 rad/s)? Can I use the peak revealed by the interpolation as an approximate as the true frequency of the signal? What would be the side effect?
Comment: Thank you! Can I consider zero padding as two cascaded windowing effects? The sampled signal has $N$ points, and after zero-padding the extended one has $M$ points. Then can I consider the reverse to have a equivalent effect, i.e., the original signal is windowed to have $M$ points and then this $M$-point observation is windowed again to have $N$ non-zero point? Then in the frequency domain this leads to the DTFT to convolve with two different sinc-like functions (one is the result from the first window and the other is from the second). The effect of zero padding is known. But is this right?
Comment: @ W.Fu Once you perform "step 2", you are dealing with a sampled and windowed version of the original signal. You *cannot* "undo" the windowing operation, whose effects will appear in the DTFT of the signal. The size of the FFT only affects how densely the DTFT is sampled. Nothing more than that
Comment: Now I understand! Thank you very much!


Infinitely real-differentiable function with $f(0)=0$ but $\int_{\partial B_1(0)}\frac{f(z)}{z}dz\ne0$

Question: I'm searching for a infinitely real-differentiable function $f:\mathbb{C}\to\mathbb{C}$ with $f(0)=0$ but $$(*)\;\;\;\;\;\int_{\partial B_1(0)}\frac{f(z)}{z}dz\ne0$$
where $$B_r(z_0):=\left\{z\in\mathbb{C}:|z-z_0|<r\right\}$$ Cauchy's integral formula yields that $f$ can't be holomorphic.

In addition: I want to show that $(*)$ holds, if $f$ is holomorphic and $\text{Re}(f(z))>0$ for all $z\in\partial B_1(0)$.
Comment: @SantoshLinkha It can't be an holomorphic function because of cauchy's integral formula.
Comment: @oxbadfood It *can't* be.
Comment: @SantoshLinkha You forgot to multiply by the derivative of the parametrization.
Comment: @SantoshLinkha If $f:G\to\mathbb{C}$ is holomorphic with $0\in G$ and $r>0$ with $\overline{B_r(0)}\subset G$, Cauchy's integral formula yields $$f(0)=\frac{1}{2\pi i}\int_{\partial B_r(0)}\frac{f(\zeta)}{\zeta}$$
Comment: @GitGud $f$ is a function $\mathbb{C}\to\mathbb{C}$. The term "real-differentiable" means, that $\text{Re }f$ and $\text{Im }f$ are differentiable (considered as functions $\mathbb{R}\to\mathbb{R}$).
Comment: @SantoshLinkha May I suggest, you, me and the OP delete all these useless comments?
Comment: @GitGud I've deleted my comments.
Comment: @oxbadfood The edit confuses me, $f$ can't be holomorphic. I deleted my answer because, as you pointed out, I had forgotten about one of the conditions.
Comment: @GitGud Maybe it's too confusing. I will update my question. The horizontal rule should point out, that the above and the below are separate. First I need a function $f$ that is infinitely real-differentiable with $f(0)=0$, but the given integral is $\ne 0$. Then, I want to show, that this integral is always $\ne 0$ when $f$ is holomorphic and $\Re(f(z))>0$ for all $z\in\partial B_1(0)$. These questions are so strongly related, that I didn't want to ask two different questions.
Comment: Well, the second part follows easily from Cauchy's integral formula. Do you see how?
Comment: @GitGud Would I ask if I can see it? ;)
Comment: @oxbadfood Forget it, I misread something. Sorry.
Comment: @GitGud No problem, not that easy as it looks like.
Answer: Put $f(z):=|z|^2=x^2+y^2$. Then $f(0)=0$, and $f(z)=1$ when $|z|=1$. It follows that
$$\int_{\partial D}{f(z)\over z}\ dz=\int_0^{2\pi}{1\over e^{it}}\>i\>e^{it}\ dt=2\pi i\ne0\ .$$
Answer: Let $f:\mathbb{C}\to\mathbb{C}$ be holomorphic with $\Re (f(z))>0$ for all $z\in \partial B_1(0)$. By definition it holds $$I:=\int_{\partial B_1(0)}\frac{f(\zeta )}{\zeta}d\zeta =i\int_0^{2\pi}f(e^{it})dt$$ Since $e^{it}\in \partial B_1(0)$ for all $t\in [0,2\pi]$ we should be able to conclude $I\ne 0$.


Aptana 3 Javascript Syntax Validator doesn't work

Question: I've installed Aptana 3 right now but the Javascript Syntax Validator doesn't work. What i'm doing wrong? I've testet the JSLint & Javascript Style Validator and they are working..

Answer: If you click on the Javascript Syntax Validator, you will notice that it's empty by default.
That's why.
Comment: hmm yeah it is. but i've don't changed anything and restore defaults doesn't work too.


Como fazer o custom select da tela "Fornecedores" buscar informações (NomeEmpresa) na tabela "Empresa"

Question: Estou desenvolvendo uma aplicação em Asp.Net usando MVC 5. Criei um select na tela de Fornecedores e gostaria de saber como posso buscar as informações do meu banco e mostrá-las nesse custom.
Minha aplicação possui duas telas: Empresas e Fornecedores. Na tela de fornecedores, possuo um select onde gostaria de pegar os nomes de empresas cadastrados na tela de "Empresas".
No banco de dados possuo duas tabelas: Fornecedores e Empresas.
Código do select:

            Empresa:
            <select name="Empresa" id="txtEmpresa"  class="custom-select">
                <option selected>Escolha uma empresa...</option>
                <option value="@Model.Empresa">One</option>
                <option value="@Model.Empresa">Two</option>
                <option value="@Model.Empresa">Three</option>
            </select>

            &nbsp

                Nova Empresa

Comment: Por que você não usa Razor? Outro detalhe, adiciona o fonte da sua `controller`.
Comment: Conseguiu verificar a resposta?
Answer: Considerando o próprio template MVC do Visual Studio e adicionando os Controllers e Views usando a opção Add > New Scaffolded Item..., o resultado que vc espera pode ser obtido com os seguintes métodos de criação e edição:
        // GET: Suppliers/Create
        public IActionResult Create()
        {
            ViewData["CompanyId"] = new SelectList(_context.Company, "Id", "Name");
            return View();
        }

        // POST: Suppliers/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Name,CompanyId")] Supplier supplier)
        {
            if (ModelState.IsValid)
            {
                _context.Add(supplier);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            ViewData["CompanyId"] = new SelectList(_context.Company, "Id", "Name", supplier.CompanyId);
            return View(supplier);
        }

        // GET: Suppliers/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var supplier = await _context.Supplier.FindAsync(id);
            if (supplier == null)
            {
                return NotFound();
            }
            ViewData["CompanyId"] = new SelectList(_context.Company, "Id", "Name", supplier.CompanyId);
            return View(supplier);
        }

        // POST: Suppliers/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,Name,CompanyId")] Supplier supplier)
        {
            if (id != supplier.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(supplier);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!SupplierExists(supplier.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["CompanyId"] = new SelectList(_context.Company, "Id", "Name", supplier.CompanyId);
            return View(supplier);
        }

A parte importante de todo esse código é new SelectList(_context.Company, "Id", "Name"). O 1o parâmetro do SelectList são os objetos listados, o 2o é o id utilizado como chave e Name é a propriedade que vc deseja exibir no select. A view é exatamente a criada pelo Visual Studio.
Answer: Considere o seguinte cenário:
Na Controller:
List<Empresa> lstEmpresa = new List<Empresa>();
lstEmpresa.Add(new Empresa() { ID = 1, Nome = "Empresa 01"});
lstEmpresa.Add(new Empresa() { ID = 2, Nome = "Empresa 02"});
lstEmpresa.Add(new Empresa() { ID = 3, Nome = "Empresa 03"});

ViewBag.EmpresaList = new SelectList(lstEmpresa, "ID", "Nome");

Na View:
@Html.DropDownListFor(model => model.Empresa, new SelectList(ViewBag.EmpresaList, "Value", "Text"), new { @class = "form-control" })

Existem vários modelos de preencher, em minhas aplicações que desenvolvo utilizo este conceito básico. Preencher o List, você escolhe a forma como sua aplicação faz isto, mas a estrutura apresentada é o modelo básico para entendimento.


Apache Simple Configuration Issue: Setting up per-user directory permission denied problem

Question: I am just getting Apache 2.2 running on Fedora 13 Beta 64-bit.  I am running into issues setting my per-user directory.  The goal is to make localhost/~user map to /home/~user/public_html.  I think that I have the permissions right because I have 755 to /home/~user, and I have 755 to /home/~user/public_html/ and I have 777 for all contents inside of /home/~user/public_html/ recursively set.
My mod_userdir configuration looks like this:
<IfModule mod_userdir.c>
#
# UserDir is disabled by default since it can confirm the presence
# of a username on the system (depending on home directory
# permissions).
#
UserDir disabled root
UserDir enabled huckphin

#
# To enable requests to /~user/ to serve the user's public_html
# directory, remove the "UserDir disabled" line above, and uncomment
# the following line instead:
#
UserDir public_html

The error that I am seeing in the error log is this:
[Sat May 15 09:54:29 2010] [error] [client 127.0.0.1] (13)Permission denied: access to /~huckphin/index.html denied

When I login as the apache user, I know that /~huckphin does not exist, and this is not what I want.  I want it to be accessing ~huckphin, not /~huckphin.  What do I need to change on my configuration for this to work?
[Added after comments]
Hi Andol, thank you for your suggestions.  So, first off, you said that you assume that I have the userdir module enabled, but I am not sure what that means exactly.  That could be part of the problem.
I do have the Module loaded, using the LoadModule directive.  I have this:
LoadModule userdir_module modules/mod_userdir.so

I also did a find on where mod_userdir is, and I found it located here:
[huckphin@crhyner-workbox]/% find / . -name '*mod_userdir.so*' 2> /dev/null
/usr/lib64/lighttpd/mod_userdir.so
/usr/lib64/httpd/modules/mod_userdir.so

Is there something else I need to enable?
Also, my directory configuration was mentioned.  I have uncommented the default configuration given.  I have not looked into what all of the configurations mean, and this could probably explain the issue.  Here is the Directory that I have for the user directories:
<Directory "/home/*/public_html">
AllowOverride FileInfo AuthConfig Limit
Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
<Limit GET POST OPTIONS>
    Order allow,deny
    Allow from all
</Limit>
<LimitExcept GET POST OPTIONS>
    Order deny,allow
    Deny from all
</LimitExcept>
</Directory>

Answer: Actually, when Apache refers to /~foo/ in its log files, it is talking about the url, and not the file system path. In other words, there's nothing suggesting that it's looking at the wrong place.
I assume you also have the userdir module enabled, not just the configuration? What about the Directory configuration for /home/*/public_html? Also, what about the file system permissions for /home?
Comment: make sure the user's directory can be traversed by apache. it needs full read permissions to `/home/user/public_html` i.e. `chmod 755 /home/user/public_html` and execute permissions on `/home/user/`, i.e. `chmod 711 /home/user` if i recall correctly, 711 is the minimum.
Comment: Hi cpbills, thanks for the suggestion.

I have logged in as the apache user using root, and I am able to traverse the /home/user/public_html directory, so I believe that I have set the permissions correctly.  I do have /home/user set to 755, and /home/user/public_html set to 755, and everything under /home/user/public_html/* to 777, so I think that my permissions are set.
Comment: Hi andol.  I have added my settings for .  Also, my permissions for home is set to 755.
Answer: I'm a little upset.  I found the answer, but it was just a guess.  Sure enough, nothing about my configuration was incorrect.  I stopped SELinux by going to System -> Administration -> SELinux Management (I am using GNOME for my window manager, btw), and shutdown SELinux, and I was able to view my user directory webpage.
So, I have found out that SELinux was causing the problem.  I am not sure if I want to go through and enforce a policy specifically for SELinux.  I think that might be another thread, but I have found the problem!
Thank you for the help, though.  It made me think in a different direction, which helped me come to this conclusion!  I appreciate the help!


How to catch silent failure of wdDialogFileSaveAs if file is locked?

Question: I created a dialog with three buttons, where the third should save a Word document (Office Pro Plus 2013, BTW) as a PDF file.
Private Sub Button_Dokument_mit_Grafik_als_PDF_speichern_Click()
    Dim Grafik As Boolean
    Grafik = Options.PrintDrawingObjects
    Options.PrintDrawingObjects = True
    With Dialogs(wdDialogFileSaveAs)
        .Format = wdFormatPDF
        ' .Format = 17 '17 = PDF
        .Show
    End With
    Options.PrintDrawingObjects = Grafik
End Sub

If the PDF exists I can choose to overwrite it, which does work in most cases.
If the PDF to be overwritten is already open, in Adobe Reader for instance, then the file isn't saved, as it is locked. I don't get any notification that the file is locked.
How can I catch this and pop up the same message that I get when saving manually within Word?
EDIT:
To explain why my question is different to others that have been answered:
I don't need to check if the file is open in Word already. I'm saving the file as a PDF not as a Word file.
I need to check if the file is open and locked in any other application, such as Adobe Reader, Edge or whatever.
This check is done by Word (and/or the OS?) already, and THIS is the event I need to catch. I don't understand why I need to catch it at all, as the result of the check if the file does exist does come up, but the result of the check if the file is locked seems to be ignored.
The VBA code behaves as if the file has been saved, but it is not, if locked by any application other than Word.
I have no clue which code snippet exactly I would need to grab from Detect whether Excel workbook is already open
Comment: Your post is OK, except that the question has been asked many, many times before. A Google search on "test if file is locked" turns up multiple "hits", including on StackOverflow. See https://stackoverflow.com/questions/9373082/detect-whether-excel-workbook-is-already-open
Comment: Possible duplicate of [Detect whether Excel workbook is already open](https://stackoverflow.com/questions/9373082/detect-whether-excel-workbook-is-already-open)
Comment: (The code works for Word, same as Excel)
Comment: Thanks, Cindy, but: I'm not sure if we're really talking about the same thing.

First: I have seen so many posts in the net that Excel and Word VBA are that different, that I didn't even dare to look for Excel VBA.

Second: I don't want to check if the file is open in Word, but if the file to be saved is open in a different application (in this case Adobe Reader).
Comment: Third: Word (and/or the OS itself) does this check already anyway (at least outside VBA), and I'd like to catch THIS Event inside VBA. Currently it looks as if the file would be saved, but it's not.

Please note that saving a Word doc as PDF is a lot different from saving a Word doc as a Word file.

Huh, answering to a comment here is quite limited in terms of number of characters and time...
Comment: We're talking about exactly the same thing... The code is neutral as to what application calls it and what application the file is open in. If the file is locked on the system, the code detects it.
Comment: OK. I wasn't sure because if I rephrase the Excel related question to "Detect whether Word file is already open" it does not address my problem. The document may not even be saved as a word file already at all, it will in most cases be a freshly created and still unsaved document. Furthermore, there were so many different approaches that I had no clue which of them is the best one to use. Not to speak about how to merge it with my code in detail. The solution from @CSS does help already, but is still not the final one as it does not exactly what it should do. See  my (later) response to it.
Comment: @Cindy, are you able to remove the link "This question may already have an answer here:" above? If so, I kindly ask you to do so. The word specific solution given here by @CSS ist not posted there at all, especially not in combination with the ``wdDialogFileSaveAs`` dialog and the ``.Display`` method (and exactly that was part of the problem). Furthermore, can you probably shed some light on the -1 vs. -2 button issue (see comments from @CSS and myself below)?
Answer: Here is what you might be looking for:
Sub SaveAsPdf()
    Dim Grafik As Boolean
    Grafik = Options.PrintDrawingObjects
    Options.PrintDrawingObjects = True

    Dim fDialog As FileDialog
    Set fDialog = Application.FileDialog(msoFileDialogSaveAs)

    fDialog.Title = "Save a file"
    'works only in Word2016 not in word 2013;
    'fDialog.InitialFileName = "*.pdf"
    'we can use the filterindex property instead
    fDialog.FilterIndex = 7

    If fDialog.Show = -1 Then
        Dim selectedFilePath As String
        selectedFilePath = fDialog.SelectedItems(1)
        If IsFileInUse(selectedFilePath) Then
            MsgBox "The target pdf file you are trying to save is locked or used by other application." & vbCrLf & _
            "Please close the pdf file and try again.", vbExclamation
        Else
            ActiveDocument.SaveAs2 selectedFilePath, wdFormatPDF
        End If
    End If

    Options.PrintDrawingObjects = Grafik
End Sub

Private Function IsFileInUse(ByVal filePath As String) As Boolean
    On Error Resume Next
    Open filePath For Binary Access Read Lock Read As #1
    Close #1
    IsFileInUse = IIf(Err.Number > 0, True, False)
    On Error GoTo 0
End Function

If you would like to use wdDialogFileSaveAs dialog, you can try the below code:
The Display method will display the dialog box without executing the actual functionality. You can validate the result of the display to identify the button clicked and use the execute method to execute the actual functionality.
'Save As Pdf using wdDialogFileSaveAs dialog
'However, it doesn't work as expected.
'The Display method should
Sub SaveAsPdf()
    Dim dlg As Dialog
    Dim dlgResult As Long
    Set dlg = Dialogs(wdDialogFileSaveAs)
    With dlg
        .Format = wdFormatPDF
        dlgResult = .Display
        If dlgResult = -1 Then 'user clicks save button;
            If .Name <> "" Then
                If IsFileInUse(.Name) Then
                    MsgBox "The target pdf file you are trying to save is locked or used by other application." & vbCrLf & _
"Please close the pdf file and try again.", vbExclamation
                Else
                    .Execute
                End If
            End If
        End If
    End With
End Sub

Please note that, the above code (wdDialogFileSaveAs dialog) doesn't work as expected in Word 2016 at least in my local enviornment. The Display method executes the actual functionality once the save button is clicked. Also it returns -2 as a dialog result if Save button is clicked.
Comment: Thanks so much, @CSS. But unfortunately, the code doesn't do exactly what it should do. The thing with _fDialog.InitialFileName = "C:\temp\1.pdf"_ doesn't work as intended (a file name _1.docx_ and the file type _*.docx_ are preselected instead). And even if it would work, it's not exactly what I need. The file name field should be empty, the file type should be *.pdf, and the directory shouldn't be _C:\temp_. Nonetheless, the function itself works, although the details of the code still escape me (I'm simply not familiar enough with VBA). I'll try to fiddle around myself a bit with this.
Comment: Tried this and that, but haven't been successful. Also, I still don't understand why an own function is required at all. If I save a document in Word as PDF manually, it is automatically detected as being locked. Why not when running the VBA code in my initial question? Can someone shed some light on that?
Comment: You can specify the initial filename as *.pdf or you can modify as you wish.
`fDialog.InitialFileName = "*.pdf"`
Comment: With regards to file locking issue, the method I gave is how it works. Word will not give everything as per our need, as it will change for every business case. In this case you are expecting Word should tell you if the file is locked without writing a code. If you use a unique filename (which doesn't exists) which cannot be duplicate then there is no need to check whether the file is already exists/locked.
Comment: No, sorry, `fDialog.InitialFileName = "*.pdf"` doesn't work. The file name then is _"*.docx"_, and the file type is _"Word-Dokument (*.docx)"_. Also, the dialog is the wrong one, (not the one that should come up when saving a Word document as PDF). Did you test your code yourself and it does work as intended? If so, with which version of Word/Office? IMO, this `wdFormatPDF` thing is missing in this part of the code. But I have no clue how to implement it.
Comment: As to your comment _"Word will not give everything as per our need, as it will change for every business case. In this case you are expecting Word should tell you if the file is locked without writing a code."_ Yeah, sure - because that's exactly what Word (or Windows?) is doing when I'm doing exactly the same procedure manually **outside VBA**. **That** is what I don't understand. I mean, it even detects that the file does exist already when running the VBA code - why is no special function required for this detection, but for the locking issue it is required...?
Comment: With regards to file locking issue, what I am trying to say is when Word tries to save the file they will internally check whether the file is locked or not which is not exposed to end user via VBA. So it requires a additional function to validate the same.
Comment: I use Word 2016. The code I gave works fine for me. Yes the dialog is different though. The default one has some additional save options for saving PDF. If the user only needs to save the file as PDF then the dialog I used in my code is enough. Also you are saying *.pdf doesn't work. What do you mean by that? Is it throws any errors?
Comment: Tested the code in Word 2013 and found that `fDialog.InitialFileName = "*.pdf"` doesn't work correctly. Instead of that we can use the FilterIndex property. Updated my post with changes. Please check.
Comment: Thanks again, @CSS, for looking after it, and sorry for late reply. Indeed, the changed code does now show PDF files only in the dialog. But the dialog itself is still not the one that should come up when saving a Word document as a PDF (and from time to time, I do need the specific options of this dialog). Is there really no way do the same as in my original code...
`With Dialogs(wdDialogFileSaveAs)
    .Format = wdFormatPDF
    .Show
End With`
...and by the same time checking if the file is locked?
The answer to this question seems not to be that easy as @Cindy did initially state. ;)
Comment: No. It is not possible to automatically check whether the file is locked. We need to write code to validate the same.
Comment: You are welcome :-) The "right" way to thank for a useful contribution is to upvote (arrows to the left). To mark something as "the" answer, click the checkmark to the left. This 1) gives the person "points" and 2) lets others who may have a similar requirement know that the contribution answered the question. ref: https://stackoverflow.com/help/someone-answers
Comment: I know how to thank for a contribution, but I wanted to wait until we're really done. ;) This is not the case yet, as my code brings up the right dialog but doesn't do the lock check, your code does the lock check but doesn't bring up the right (PDF specific) dialog. I'm still hoping for the "perfect" solution. Can't we specify that in the ``Set fDialog = Application.FileDialog(msoFileDialogSaveAs)`` statement somehow?
Comment: I have t split this in two comments: I just discovered another problem with your code: if the word document is saved as a word file already, the default file name is empty and the default directory is C:\Windows\System32. But the file name should be the one of the saved file, just with the extension ".pdf" instead of ".docx", and the directory should point to the directory where the word file has been saved.
Comment: That's what happens automatically when using ``wdDialogFileSaveAs``, but we're using ``msoFileDialogSaveAs`` instead. To me it looks as if this might be part of the problem. Is there really no way to use ``wdDialogFileSaveAs``? I tried that, but just replacing the string ``msoFileDialogSaveAs`` in your code with ``wdDialogFileSaveAs`` throws a runtime error (as I said, I'm a VBA noob).
Comment: Also, in the meantime I'm aware that we "have to write code" ;), I wasn't expecting (anymore) that it works automatically. My question six comments above was more meant how to combine "my" initial code with your function ``IsFileInUse`` so that it will work as expected. Nonetheless, it still somewhat escapes me that Word checks the existence of a file (= no VBA code needed), but not if the file is locked (= VBA code needed). When doing the same manually via Backstage, it does **both** things automatically. If VBA code would be needed for **both** things, this would appear more logical to me.
Comment: I have updated my post with code which uses wdDialogFileSaveAs dialog. However, it doesn't work as expected. That's why I have suggested using msoFileDialogSaveAs.
Comment: Thanks, @CSS, I'll check this on Word 2013. At least an attempt that might help.
Comment: Your code is working, @CSS :). You're just checking the wrong button with ``If dlgResult = -2``, this should read ``If dlgResult = -1`` instead. Furthermore, there's a logic error - if the file is in use, ``.Execute`` is not the right action to be taken. ;) If I change the code as shown below, then everything appears to be working (still have to do some testing in detail, though). But anyway, currently it looks as if this would indeed be the perfect solution I was looking for.
Comment: Thanks a lot for this! It's a bit embarrassing that I didn't get the idea to use the ``.Display`` method myself, although I did read about it somewhere before - I just had no clue how to interpret the result of the dialog without instantly executing it.
Comment: Interesting. In 2016 version, I am getting -2 when save button is clicked and the actual functionality is getting executed even if we set the break point on `If dlgResult = -2 Then`. So, you must be careful while you upgrade your office version. Or it might be an issue with my environment. Add some reminder notes in your code :)
Comment: In fact, I'm also getting ``-2`` if I send ``dlgResult`` to a MsgBox. Weird! Probably a VBA bug...? Anyway, please test the code with ``-1`` in Word 2016 - does it work then? BTW: You still have the logic error with ``.Execute`` in your code, please correct that before testing (see "my" Code below).
Comment: Fixed the .execute logic error in my code now. Yes. I am getting -2 if the user presses save button and 0 if the user presses the cancel button.
Comment: Weird, but thanks again for your help. :) BTW, do you have a clue what the argument "LockAnnot" is doing?
Answer: Thanks to the help of @CSS (see answer and comments above), this is the full currently working code (unless I'd still find any flaws):
Private Sub Button_Dokument_mit_Grafik_als_PDF_speichern_Click()
    Dim Grafik As Boolean
    Grafik = Options.PrintDrawingObjects
    Options.PrintDrawingObjects = True

    Dim dlg As Dialog
    Dim dlgResult As Long
    Set dlg = Dialogs(wdDialogFileSaveAs)
    With dlg
        .Format = wdFormatPDF
        dlgResult = .Display
        If dlgResult = -1 Then 'user clicked save button
            If .Name <> "" Then
                If IsFileInUse(.Name) Then
                    MsgBox "The target PDF file you are trying to save is locked or used by other application." & vbCrLf & _
                    "Please close the PDF file and try again.", vbExclamation
                Else
                    .Execute
                End If
            End If
        End If
    End With

    Options.PrintDrawingObjects = Grafik
End Sub

Private Function IsFileInUse(ByVal filePath As String) As Boolean
    On Error Resume Next
    Open filePath For Binary Access Read Lock Read As #1
    Close #1
    IsFileInUse = IIf(Err.Number > 0, True, False)
    On Error GoTo 0
End Function

Thanks to @CSS again. :)
You may want to edit your answer, though, so that it does reflect the finally working code. I've given appropriate thanks.


Ajax response conversion

Question: I have this array that is returned by ajax:
console.log(res);
["07Apr|1", "06Apr|3", "05Apr|12", "04Apr|11", "03Apr|0", "02Apr|0", "01Apr|6", "31Mar|0", "30Mar|7", "29Mar|16", "28Mar|5", "27Mar|5", "26Mar|12", "25Mar|9", "24Mar|4", "23Mar|10", "22Mar|16", "21Mar|2", "20Mar|19", "19Mar|22", "18Mar|10", "17Mar|11", "16Mar|10", "15Mar|19", "14Mar|0", "13Mar|4", "12Mar|14", "11Mar|5", "10Mar|26", "09Mar|7", "08Mar|5"]

I convert this array using JSON.stringify:
(The variable "res" is the response of my ajax -as shown above)
            var obj = [];
            var daysBack = 30;
            var objItem = {};
            for(var x = 0; x <= daysBack; x++){
                var currObj = res[x];
                var objCombo = currObj.split("|");
                var objItem = "{date: '"+objCombo[0]+"', downloads: '"+objCombo[1]+"'}";
                objItem = JSON.stringify(eval("(" + objItem + ")"));
                obj.push(objItem);
            }

When I dump the "obj" to the console I get:
console.log(obj);
["{"date":"07Apr","downloads":"1"}", "{"date":"06Apr","downloads":"3"}", "{"date":"05Apr","downloads":"12"}", "{"date":"04Apr","downloads":"11"}", "{"date":"03Apr","downloads":"0"}", "{"date":"02Apr","downloads":"0"}", "{"date":"01Apr","downloads":"6"}", "{"date":"31Mar","downloads":"0"}", "{"date":"30Mar","downloads":"7"}", "{"date":"29Mar","downloads":"16"}", "{"date":"28Mar","downloads":"5"}", "{"date":"27Mar","downloads":"5"}", "{"date":"26Mar","downloads":"12"}", "{"date":"25Mar","downloads":"9"}", "{"date":"24Mar","downloads":"4"}", "{"date":"23Mar","downloads":"10"}", "{"date":"22Mar","downloads":"16"}", "{"date":"21Mar","downloads":"2"}", "{"date":"20Mar","downloads":"19"}", "{"date":"19Mar","downloads":"22"}", "{"date":"18Mar","downloads":"10"}", "{"date":"17Mar","downloads":"11"}", "{"date":"16Mar","downloads":"10"}", "{"date":"15Mar","downloads":"19"}", "{"date":"14Mar","downloads":"0"}", "{"date":"13Mar","downloads":"4"}", "{"date":"12Mar","downloads":"14"}", "{"date":"11Mar","downloads":"5"}", "{"date":"10Mar","downloads":"26"}", "{"date":"09Mar","downloads":"7"}", "{"date":"08Mar","downloads":"5"}"]

Now, I want to change the above array format from this one:
["{"date":"07Apr","downloads":"1"}", "{"date":"06Apr","downloads":"3"}", "{"date":"05Apr","downloads":"12"}", "{"date":"04Apr","downloads":"11"}", ....]

to that one:
[{"date":"07Apr","downloads":"1"}, {"date":"06Apr","downloads":"3"}, {"date":"05Apr","downloads":"12"}, {"date":"04Apr","downloads":"11"}, ....]

I mean to eliminate the double quotes that enclose the objects in curly braces.
Any ideas would be appreciated...
Comment: Just don't stringify, no?
Comment: @erkaner Don't try custom JSON parsing - you'll introduce more problems than you'll solve.
Comment: how about this: `.replace('"{"', '{"');` and `replace('"}"', '"}');`
Answer: Stringify the entire structure when it is ready, not segments.
Don't use eval ever, use JSON.parse() instead.
        var obj = [];
        var daysBack = 30;
        var objItem = {};
        for(var x = 0; x <= daysBack; x++){
            var currObj = res[x];
            var objCombo = currObj.split("|");
            var objItem = {date: objCombo[0], downloads: objCombo[1]};
            //objItem = JSON.stringify(eval("(" + objItem + ")"));
            obj.push(objItem);
        }
        obj = JSON.stringify(obj);

Comment: I agree, is much better to stringify the entire array rather than it's segments... However, I still have the curly braces enclosed in double quotes -which is actually what I'm trying to eliminate! Before my console would show ["{"date":"07Apr","downloads":"1"}", "{"date":"06Apr","downloads":"3"}", "{"date":"05Apr","downloads":"12"}", ...] now it is: ["{date: '07Apr', downloads: '1'}","{date: '06Apr', downloads: '3'}","{date: '05Apr', downloads: '12'}", ...]
Answer: You can parse the data you received from the ajax response to create the array.
var populateArray = function (ajaxResponse) {
    var newArray = [];
    ajaxResponse.forEach(function (item, index) {
        var props = item.split('|');
        var obj = {
            date: props[0],
            downloads: props[1]
        };
        newArray.push(obj)
    });

    return newArray;
}

To demonstrate, try
console.log(populateArray(["07Apr|1", "06Apr|3", "05Apr|12", "04Apr|11", "03Apr|0", "02Apr|0", "01Apr|6", "31Mar|0", "30Mar|7", "29Mar|16", "28Mar|5", "27Mar|5", "26Mar|12", "25Mar|9", "24Mar|4", "23Mar|10", "22Mar|16", "21Mar|2", "20Mar|19", "19Mar|22", "18Mar|10", "17Mar|11", "16Mar|10", "15Mar|19", "14Mar|0", "13Mar|4", "12Mar|14", "11Mar|5", "10Mar|26", "09Mar|7", "08Mar|5"]));

Comment: Thank you for pointing out a whole new approach than mine! Which by the way, worked like a charm! The result was exactly what I needed!

Ajax response conversion


Writing List of tuple into a file in Scala

Question: I have some data in a variable called windData with information below.
ListBuffer((2001-01-01T00:00:00.000+01:00,578,WIND projekt GmbH),
(2001-01-01T01:00:00.000+01:00,420,WIND projekt GmbH),....)

I need to write this data to csv file.
Code I have written
def printToFile(f: java.io.File)(op: java.io.PrintWriter => Unit) {
    val p = new java.io.PrintWriter(f)
    try { op(p) } finally { p.close() }
  }
 printToFile(new File("/Users/krishna/Experiment/Internship/wind.csv")) { p =>
    windData.foreach(p.println)
  }

Output
(2001-01-01T00:00:00.000+01:00,578,WIND projekt GmbH)
(2001-01-01T01:00:00.000+01:00,420,WIND projekt GmbH)

Expected Output:
2001-01-01T00:00:00.000+01:00,578,WIND projekt GmbH
2001-01-01T01:00:00.000+01:00,420,WIND projekt GmbH

How to I get rid of the tuple before and after in a line.
Answer: This would work for list of Tuples of any length - using productIterator.mkString(",") to serialize the Tuple into a String without accessing each field explicitly:
printToFile(new File("/tmp/wind.csv")) { p =>
  windData.foreach(tuple => p.println(tuple.productIterator.mkString(",")))
}

Answer: Here is an example:
scala> val d = ListBuffer((1,2,3),(4,5,6))
d: scala.collection.mutable.ListBuffer[(Int, Int, Int)] = ListBuffer((1,2,3), (4,5,6))

scala> d.foreach(x => print(x._1 + "," +  x._2 + "," +  x._3 + "\n"))

Result:
1,2,3
4,5,6

Comment: You can also provide a partial function inside `foreach`, for readability: `foreach { case (first, second) => print....`
Answer: You can do
windData.foreach { tuple =>
  println(tuple._1)
  println(tuple._2)
}

Comment: I still see the same problem.
Comment: This will give you back a tuple since you are using the comma operator.


Transitioning Controllers Animation - Variable binding in a condition requires an initializer

Question: I am trying to follow a simple tutorial on making a circular transition from one viewController to the secondViewController.
However Xcode gives me an error that isn't encountered in tutorial and not sure how to deal with it.
Variable binding in a condition requires an initializer error
import UIKit

class CircularTransition: NSObject {

    var circle = UIView()

    var startingPoint = CGPoint.zero {
        didSet {
            circle.center = startingPoint
        }
    }

    var circleColor = UIColor.white

    var duration = 0.3

    enum CircularTransitionMode: Int {
        case present, dismiss, pop
    }

    var transition:CircularTransitionMode = .present
}

extension CircularTransition:UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return duration
    }

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let containerView = transitionContext.containerView

        var CircularTransitionMode: CircularTransitionMode
        if CircularTransitionMode == .present {
            if case let presentedView == transitionContext.view(forKey: UITransitionContextViewKey.to) {

                let viewCenter = presentedView.center
                let viewSize = presentedView.frame.size

                circle = UIView()

            }
        }
        else{

        }

    }

}

Answer: There are some issues with the animateTransition function.
First the line with the error should be this:
if let presentedView = transitionContext.view(forKey: UITransitionContextViewKey.to) {

because you don't need the case check and you are trying to assign not compare so it's = not ==.
Second you create a variable of type CircularTansitionMode but don't assign anything to it in this line:
var CircularTransitionMode: CircularTransitionMode

and then immediately try to use it.
Fixing your original error will then flag this second one up on the next line saying it is being used without being initialised.
You also have a lot of unused variables but maybe you just haven't posed the complete code.


MissingBackpressureException with OperatorOnBackpressureDrop applied before OperatorObserveOn

Question: The following MissingBackpressureException is occurring with OperatorOnBackpressureDrop applied before OperatorObserveOn:
rx.exceptions.MissingBackpressureException
at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.onNext(OperatorObserveOn.java:162) ~[rxjava-1.1.10.jar:1.1.10]
at rx.internal.operators.OperatorOnBackpressureDrop$2.onNext(OperatorOnBackpressureDrop.java:98) ~[rxjava-1.1.10.jar:1.1.10]
at rx.subjects.PublishSubject$PublishSubjectProducer.onNext(PublishSubject.java:305) ~[rxjava-1.1.10.jar:1.1.10]
at rx.subjects.PublishSubject$PublishSubjectState.onNext(PublishSubject.java:220) ~[rxjava-1.1.10.jar:1.1.10]
at rx.subjects.PublishSubject.onNext(PublishSubject.java:73) ~[rxjava-1.1.10.jar:1.1.10]

I've applied OperatorOnBackpressureDrop before OperatorObserveOn (shown in above stacktrace) as suggested in JavaDoc.
From Observable.observeOn(Scheduler) JavaDoc:

"This operator honors backpressure from downstream and expects it from the source Observable. Violating this expectation will lead to MissingBackpressureException. This is the most common operator where the exception pops up; look for sources up the chain that don't support backpressure, such as interval, timer, {code PublishSubject} or BehaviorSubject and apply any of the onBackpressureXXX operators before applying observeOn itself."

My specific use case is a Worker Thread calling a hot observable PublishSubject.onNext() every ~600 ms and the observers being notified on the JavaFX Application Thread.
Not sure what I'm doing wrong here or if this is a RxJava bug that should be reported.
Environment: RxJava 1.1.10, Java 1.8.0_102
Answer: You can get a MissingBackpressureException downstream of onBackpressureDrop if your observable does not honour the Observable contract (in particular that emissions need to be serial). If you are using a PublishSubject and calling subject.onNext from different threads then you need to serialize its emissions:
 PublishSubject<T> subject = ...;
 subject
   .serialize()
   .onBackpressureDrop()
   .observeOn(...)
   ...

Comment: Thanks, this makes sense. I will try it out and see if it works.
Comment: Turns out there were multiple threads calling subject.onNext so this is likely the solution. Thanks again.


How to detect mobile viewport with in twig?

Question: Is there a way to detect screen display with in twig? I have a block and I want to render in a twig template using the twig tweak module, but only in mobile screen. It is surely possible to just hide it in CSS, but can it be done in twig? - https://www.drupal.org/project/twig_tweak
Comment: The maximum you can detect is if the browser is mobile or not, as far as I know, and even for that you'd need to preprocess that from within PHP, plus need to ensure to cache-bust that somehow.
Answer: There is a Browser Object in twig which using that you can get some data about user's browser but it does not provide properties like screen width.
its recommended to use css or javascript in these situations but if you want to hide your block in server side so user might access only using a mobile phone then I recommend this steps:

first of all you should provide a value to check if user is using mobile or not, for this you should use a preprocess function (hook_preprocess_page I guess as will fire for any pages loaded) , there use a code like this to detect mobile, then add a boolean value to page which should be TRUE if user is using mobile.
after that in twig you will have that value, check if it is true and display your block
Comment: Its okay by me to just hide it using css or Js. The thing i am concerned is whether having a block which does not need to be in a mobile view is a bad thing for SEO or not.Any thoughts on that? @Alireza Tabatabaeian
Comment: I doubt the browser object is available in Twig. The linked docs are from Grav CMS.