Upload an image in a form programmatically

Question: I'm doing a form programmatically. I need to give an option to upload an image and give an option to resize it ( like cropping option ).
I don't know how to do it,  I know that I need to upload the image to a directory and also I suppose that I need to show a relation between the node and the image in the database.
I've created a field called field_img.
So, how can I do it?
This is the form that I've done but I don't know how to give a relation in the database...
form['group_anuncio']['imagen'] = array(
        '#title' => t('Image'),
        '#type' => 'managed_file',
        '#upload_validators' => array('file_validate_extensions' => array('jpeg jpg png gif')),
        '#upload_location' => 'public://sites/default/files',
        '#progress_indicator' => 'throbber',
        '#status' => FILE_STATUS_PERMANENT,
        '#progress_message' => 'One moment while we save your file...',
);

Comment: This question appears to be off-topic because it is about code you wrote, for which you want to write better code, or you want to understand why it doesn't work, but you didn't show the code you are using, or the part of the code that is relevant for the question.
Comment: I would like to know how to give the option to upload an image in a form. I don't know where to start... I've seen that I can create the field like a field type or managed_file...
Comment: You said you are "doing a form programmatically". That implies you have a code for that, don't you? if no, then what king of form is it?
Answer: I would strongly suggest to use nodes and one of these modules
Comparison of image cropping and resizing modules
If you dont want nodes then you still should be able to use one of crop modules which works with image fields if you use entities, you can use Entity Construction Kit (ECK) module  to create custom entity types
Answer: The best practice is to use the File Entity module with the entity approach. When you have installed it, the points are:

Create a form input (you've made it)
Store the new file in a temp folder
Create a new File() object
Use the save() method

This method will store your file like an object, and will be easy to recover it as you want
Comment: With #upload_location variable I can say where I want to upload the file, I suposse that is like the second step that you have told. But, I don't know who to do it the thrird and the fourth ones. Have you got any example? Thank you.


Not able to map name query result to POJO class

Question: I am implementing microservices using spring jpa.

Follwing is my repository interface:

public interface FormsRepository {
    public List findCustomer(Integer Id);
}

Impl class for above :

@Repository
public class FormsRepositoryServiceImpl implements FormsRepository {
    @Autowired
    private EntityManager entityManager;

@Override
    public List findCustomerFieldDetails(Integer persId) {
         Query query = entityManager.createNamedQuery("findCustomer", CustomerDetails.class);
         query.setParameter(1, persId);
         List custDetail =query.getResultList();
        return custDetail;
    }
}

The Named native query is present in orm.xml and the CustomerDetails.class is a normal POJO class and not an entity class. We are not creating entity classes. We are creating consolidated POJOs.

I am not able to map the results to the POJO fields.

Suppose the query is : select a.id ,b.name from a,b and both id and name are present in the POJO class how do we map it?

Getting below error:
org.springframework.dao.InvalidDataAccessApiUsageException: java.lang.ArrayIndexOutOfBoundsException: 0; nested exception is java.lang.IllegalArgumentException: java.lang.ArrayIndexOutOfBoundsException: 0

Also, if we do not use result class in createNamedQuery method, the data returned is a type Object and while iterating through that as well we are getting ClassCastException:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.accenture.apsp.document.service.domain.CustomerDetails
Answer: You can use the @SqlResultSetMapping annotation for this purpose like this:
@NamedNativeQuery(
    name = "findCustomer",
    query =
        "select a.id ,b.name from a,b",
    resultSetMapping = "findCustomer_dto"
)
@SqlResultSetMapping(
    name = "findCustomer_dto",
    classes = @ConstructorResult(
        targetClass = CustomerDetails.class,
        columns = {
            @ColumnResult(name = "id", type = Long.class),
            @ColumnResult(name = "name", type = String.class)
        }
    )
)


Custom font with online Vega editor?

Question: Is there a way to specify a custom font with online Vega editor?
I'm looking at a bug which only happens with custom font.
Answer: Loading the font via Chrome Developer Tools. worked for me.

Custom font with online Vega editor?


How to add result to a list c#

Question: I have a piece of code that collects a site's img's href links. I want to add them to a static list so I can compare them later with:
var list3 = list2.Except(list1);

This is my code :
        firstlist = new List<string>();
        HtmlWeb web = new HtmlWeb();
        HtmlAgilityPack.HtmlDocument doc = web.Load("https://www.example.com/vasita?sorting=date_desc");
        var Thumbnail = doc.DocumentNode.SelectNodes("//td[@class='searchResultsSmallThumbnail']");
        if (Thumbnail != null)
        {
            var firstlinks = Thumbnail.Descendants("a")
            .Select(node => node.GetAttributeValue("href", "").ToString()).ToList();
            textBox2.Text = string.Join(Environment.NewLine, firstlinks); //shows the results on a textbox
            firstlist.Add(firstlinks);
        }

I am new at coding and I do not know how to add to a static list.
I tried firstlist.Add(firstlinks); but is giving me an error :

Error CS1503  Argument 1: cannot convert from
  'System.Collections.Generic.List' to 'string'

Thank you.
Comment: Is `firstLinks` here a `List` or a `List`?
Answer: You're trying to add the list of string into the other list of strings.
And to make that you need to use AddRange method instead of Add (see below):
firstlist.AddRange(firstlinks);

Hope it will help.

How to add result to a list c#


How to keep accelerating in 100m race?

Question: How do I keep accelerating in a 100m race? Does holding my breath work, or is it a good start that matters?  I'm a 15 year old sprinter.
Comment: Do you mean accelerating within one race (being faster after 60m than after 20m), or do you mean improving your 100m times from race to race (last week 13.2s, next week 12.9s)?
Comment: I mean being faster after 60m than after 20m
Answer: The rate of change of acceleration is the differential of the acceleration function (the secondary acceleration). This is a fairly subtle concept, but important to understanding how your body distributes its energies efficiently.
I found a paper that covers the concept of optimal pacing in running at the of American Association of Physics Teachers:
Optimal pacing for running 400- and 800-m track races
which covers (obviously) 400m and 800m, but I imagine the strategies are similar for 100m and 200m.
Note that the world record for 100m is faster for the 150m race where we measure from 50m to the finish. This is because the first 50m allows the athlete to build momentum, and therefore not having to start from 'cold' and not having spent all their energy, they can travel the next 100m quicker.
Usain Bolt ran 100m in 8.72 seconds this way (5.64s at 50m, 14.36s at 150m):
Usain Bolt 150m Manchester 2009

How to keep accelerating in 100m race?


ClassNotFoundException em Testes com mockito em Java

Question: Olá,
Ao testar uma classe usando o Mockito, me deparei com o erro "ClassNotFoundException". Infelizmente não consigo resolver este erro.
Todas as minhas dependências estão instaladas, mas o erro persiste.
Já verifiquei inúmeros tópicos aqui mesmo no StackOverflow, mas todas as soluções não conseguiram resolver meu problema, mesmo eu recriando a estrutura de pastas do projeto
Segundo minhas pesquisas, o problema seria como as pastas seriam organizadas (src/projeto...), mas desde o inicio de meu projeto sempre segui os padrões de boas práticas em meus códigos.
A respeito da instalação dos paths JARs, todos foram instalados manualmente, e suas versões estão especificadas nas imagens abaixo
Answer: As suas classes de teste do JUnit devem ficar em um diretório paralelo. Por exemplo, se seu código está em
projeto/src/main/java/br/com/pizzaria/...

Seus fontes de teste devem ficar em, por convenção:
projeto/src/test/java/br/com/pizzaria/...


Run command before and after printing with CUPS?

Question: Problem

A CUPS-Printer needs to be turned on automatically as soon as there are unfulfilled jobs

Tried Solutions

A shell script watches the queue on the server (lpstat -o) and turn on the printer when there is a job. If the queue is empty for 10 minutes it turns the printer off.

Original Question:

this is a home setup. A central printer server (Linux) manages the queue, a HP 2430DTN is attached to it via 100Mbit/sec Ethernet. The printer is hooked up to a managable power source. A shell script watches the queue on the server (lpstat -o) and turn on the printer when there is a job. If the queue is empty for 10 minutes it turns the printer off.
Now this setup messes up, stops the printer etc. after a couple of weeks and is in general "not so reliable". I now know how to change the stop-printer thing, but:
Is there a way to run my turn printer on script and turn printer off script directly from cups without watching the queue? That would be so cool!
Answer: My suggestion is to use tea4cups.
tea4cups serves as a generic wrapper around any standard CUPS backend. It allows you to configure any command to run before and after sending the job off via the real backend.
tea4cups specifically allows (any number of) commands to be run before the job is sent off: prehooks. A prehook command which exits -1 can cancel the job.
tea4cups also allows (any number of) commands to be run after the job is sent off: posthooks (unless a prehook with exit -1 cancelled the job).
Prehooks can send data to the posthooks through pipes.
tea4cups can also run filters (which may modify the print data before sending them off to the real printer through the real backend).
From now on, only your own creativity is a limit to what you can do with this framework.
Comment: Tea4Cups seem to be dead.  Is there any successor or equivalent free software system, @kurt-pfeifle?


Determine point value in quadrilateral

Question: This is a rephrased question after I gained a better understanding of the problem.
I have an X,Y plane with one point in each quadrant. Each point represents a value, it is a function result for which (x,y) is input. I want to calculate the outcome for a particular point within the quadrilateral based on the known values of the
quadrilateral's corners.
I learned (after being pointed in the right direction) there is a method for doing this on squares (with only horizontal and vertical sides) called bilinear interpolation. Great. I can just about grasp this and I think I would be able to map this into computer code.
I also learned there is a way to do this for arbitrary quadrilaterals by first mapping the quadrilateral to a square. This method, as described here however is over my head. I do not have the mathematic base to follow it and convert it to computer code.
I also learned about the existence of a mathematical code library for Microsoft .NET named Math.NET Numerics which looked promising. It has support for interpolation but unfortunately I could not find anything that seemed to match my problem.
I feel I have most of the parts of the puzzle yet I did not manage to put it all together. My goal is a formula I can enter 4 coordinates into with their values, the coordinates of my unknown value, and get a result value. I do not mind having to perform multiple steps to achieve this, it just gets hard when I encounter vector notation that I do not know how to map to code using straight +-*/ arithmetic.
Comment: Try to formalize your question with symbols, otherwise you could get an answer to a problem that is different with respect to what you have in mind. Forget about the physics for a moment and just focus on the "input" you have and the "output you want" in an abstract way. if my interpretation of you problem is correct, then what you need is a "bilinear interpolation" (it allows to extrapolate values of a function defined ona plane starting from four known values). https://en.wikipedia.org/wiki/Bilinear_interpolation
Comment: So basically you have $(x_i,y_i)$  and $f_i = f(x_i,y_i)$ for $i=1,2,3,4$, where the exact definition of $ f$ is unimportant (but you know the numerical values of $x_1..x_4,y_1..y_4,f_1..f_4$). You are asking for a way to estimate $f_0 =f(0,0)$, right?
Comment: @mrc  Ehr... I think so, yes. The function is indeed not defined, it is a physical thing. One of the inputs is temperature (say, X). For any given temperature the function will be a predictable curve but this will vary for different temperatures. So the idea is to do some measurements and use those to determine a reasonable value for any XY-combo.
Comment: @mrc Yes! This seems to be exactly what I am after. Thanks a lot. I have to map this into C# code now which is more in my comfort zone again. Great help. If you care for the points, paste it as an answer and I will accept it as the answer. It is good for my ego to see that it is not THAT straight forward after all.
Comment: Then again, this is for a perfect rectangular grid. My 4 points are arbitrarily positioned around the point of interest... I guess I could take the average x and the average y of the two points I interpolate between.
Comment: For 4 generic points have a look here: https://www.particleincell.com/2012/quad-interpolation/
Comment: @mrc Thanks. I looked at it but it was too complicated for me. I found an alternative way more compatible with my math skills (and then answered my own question). I would not have been able to find it without your pointers though so thanks again.
Answer: This turned into some serious rubber-ducking. I found a way that works for me here:
It is about triangles but it works just the same for quadrilaterals.
I had this idea before but could not convert it into a calculation. The idea is that the closer a neighboring point is, the more "weight" it should contribute to the outcome of the requested point value. Weight is the reciprocal value of the distance to the requested point.
So, for points p1, p2, p3 and p4 in Q1, Q2, Q3 and Q4 respectively, we have d1, d2, d3 and d4 for the distances of these points to the origin. Then the weights for the four reference points are w1=1/d1, w2=1/d2, w3=1/d3 and w4=1/d4. Let's call the values of the reference points v1, v2, v3 and v4. The calculated value of any point p within the bounds of the quadrilateral is:
(v1 * w1 + v2 * w2 + v3 * w3 + v4 * w4) / (w1 + w2 + w3 + w4)
This produces pretty nice continuous results, which can be visualized by filling a plane with grey dots (all RGB color components are set to the point value and we make sure that we assign values to reference points ranging from 0 to 255, 0 being black and 255 being white).
An example with these reference values (x, y, v)
p1 = ( 100,  100,   0)
p2 = (-100,  100, 255)
p3 = (-100, -100, 255)
p4 = ( 100, -100, 255)

results in this image (which ranges from -100 to +100 in both the x and y directions):

And we can see this works. p1 is black, the others are white. Anything in between nicely expresses the pull strength of all points. The middle is relatively pale because we have 3 points pulling towards white and only one pulling towards black.
This example is for a square to make it easily verifiable with the eye but it isn't more difficult for any other shape or even number of reference points.
If we recreate the image for this larger quadrilateral:
p1 = (+101, +331,   0)
p2 = (-421, +101, 255)
p3 = (-175, -601, 200)
p4 = (+101, -101,  55)

we get an image that looks to be just one grey color because the image is only a small part of the quadrilateral and values do not vary that much withing that area:

But if we flood-fill the image with some random colors we can see the attracting reference points at work again:

I am satisfied with this result. The purpose is not to be exact but to produce setpoints for an actuator based on a limited number of calibration measurements. It will be verified whether the predicted values are close enough to the real values by doing some more measurements. Then it is to be determined how many reference points are needed to calibrate the device sufficiently (the more reference points, the more accurate but we do not want to waste time on calibration by being more accurate than necessary).

Determine point value in quadrilateral


Partition of sum of two bounded functions

Question: Following my previous question about Riemann-Stieltjes integration, I'm asking this problem.

Let $f_1$ and $f_2$ be bounded on $[a,b]$ and $\alpha$ is increasing on $[a,b]$. Define $f = f_1 +f_2$. Either prove the statements or give a counterexample to show that the given statements are false:
$1.$ $U(P,f,\alpha) \le U(P,f_1,\alpha) + U(P,f_2,\alpha)$
$2.$ $L(P,f,\alpha) \le L(P,f_1,\alpha) + L(P,f_2,\alpha)$

My try: The first statement is correct. We know that $$U(P,f,\alpha) = \sum_{i =1}^{n} M_i \Delta \alpha_i , \ M_i = \sup\{f(x):x\in [x_{i-1}, x_i]\} \\ U(P,f_1,\alpha) = \sum_{i =1}^{n} N_i \Delta \alpha_i , \ N_i = \sup\{f_1(x):x\in [x_{i-1}, x_i]\} \\ U(P,f_2,\alpha) = \sum_{i =1}^{n} Q_i \Delta \alpha_i , \ Q_i = \sup\{f_2(x):x\in [x_{i-1}, x_i]\}$$ So we have $$U(P,f_1,\alpha) + U(P,f_2,\alpha) = \sum_{i =1}^{n} N_i \Delta \alpha_i + \sum_{i =1}^{n} Q_i \Delta \alpha_i = \sum_{i =1}^{n} (N_i+Q_i) \Delta \alpha_i \ge \sum_{i =1}^{n} M_i \Delta \alpha_i = U(P,f,\alpha)$$ The inequality comes from the fact $$\sup(A+B)\le \sup(A) + \sup(B)$$
The second one is false. Let $f_1 = x$ and $f_2 = -x$ and $a = 0,b=2, P = \{0,1,2\}$. Therefore $$L(P,f_1,\alpha) = 1,L(P,f_1,\alpha) = -3 \\ L(P,f,\alpha) = 0$$ Obviously $0 \not \le -2$ and this is false.
Is my answer correct? If not please explain why.
Comment: This looks good.
Comment: @RRL Thank you so much. If you like, make your comment to an answer so that I can mark the question as answered.
Comment: You're welcome.  I expanded a bit more on this in the answer.
Comment: @RRL That's great, thanks.
Answer: Your counterexample for case (2) is correct.
More generally for any interval $I$ we have for all $x \in I$,
$$\inf_{x \in I} f_1(x) + \inf_{x \in I} f_2(x) \leqslant f_1(x) + f_2(x) = f(x),$$
which implies
$$\inf_{x \in I} f_1(x) + \inf_{x \in I} f_2(x) \leqslant \inf_{x \in I}f(x), \\L(P,f_1,\alpha) + L(P,f_2,\alpha) \leqslant L(P,f,\alpha)$$
Together the inequalities
$$L(P,f_1,\alpha) + L(P,f_2,\alpha) \leqslant L(P,f,\alpha) \leqslant  U(P,f,\alpha)\leqslant U(P,f_1,\alpha) + U(P,f_2,\alpha)$$
can be used to prove that if $f_1$ and $f_2$ are Riemann-Stieltjes integrable, then so is $f = f_1+f_2$.  The converse is not true and this is connected to the fact that the reverse of the LHS inequality is false.


Application Processes "On Demand"-option missing (Oracle Apex)

Question: I'm using Oracle Database 12c + Application Express (Product Build 18.1).
In the documentation for release 18.1 you can find that while "Creating an Application Process" the option "Point" must have the value "On Demand".

Point - Identify the point during the processing of each page in the application that this process would run. Note the option, On Demand, only runs when requested by a page process.

But I can't find this option:

How can I create an "On Demand" process?
Answer: An On-Demand Process is an Ajax Callback. It's just named differently in the real world than in the documentation.


Do polynomials attain their infimum?

Question: Assume $p\colon\mathbb{R}^d\to\mathbb{R}$ is a polynomial such that $I:=\inf_{x\in\mathbb{R}^d} p(x)>-\infty$. Does there exist $x\in\mathbb{R}^d$ such that $p(x)=I$?
Answer: Yes for $d=1$.
Not always for $d\geq 2$. The idea is to find two polynomials $q_i$, $i=1,2$ whose zero sets are disjoint but infinitely close at infinity, and set
$$
p(x):=q_1(x)^2+q_2(x)^2>0.
$$
For example, choose $d=2$, $q_1(x)=x_1$ (zero set: $x_2$-axis), $q_2(x)=(x_1x_2-1)$ (hyperbolic zero set approaching $x_2$-axis) and consider $x^{(n)}=(1/n,n)$.
Comment: I would say that the answer in the case when $d\geq 2$ depends on the polynomial $p$.
Comment: You're right. I edited my answer

Do polynomials attain their infimum?


Converting PHP String having a unix timestamp value to a MySQL Timestamp value

Question: I am setting a Database value within from a PHP file. In php file i have a string variable which stores unix timestamp value.
MySql table i am having is having a schema where i have to store these timestamp values in login field which is of timestamp datatype.
i tried sending
date('Y-m-d G:i:s', strtotime($userLogin));

to my database but all it stores is 0000-00-00 00:00:00
Comment: Have you confirmed the value of $userLogin is valid?  It's possible that strtodate() is returning FALSE (zero).  To debug, you should consider breaking the statement into two steps:

1) assign the return value of strtotime() to a variable so you can validate it, and
2) call date() using that newly created variable.
Answer: MySQL has FROM_UNIXTIME() function for this.
Answer: MySQL provides the FROM_UNIXTIME( ) and UNIX_TIMESTAMP( ) functions to converta Unix timestamp to a MySQL date format, and vice versa.
Example:
$sql = "INSERT INTO yourtable(date, ..., ...) VALUES (FROM_UNIXTIME($yourdate), ..., ...)";

Answer: strtotime () is intended for converting strings in various date formats into UNIX timestamps.  If the string is a timestamp already then it won't look like a meaningful formatted date/time to strtotime () and it will fail.
If the string is already a timestamp, then you don't need to do anything more to it than cast it to integer (strictly speaking even that step shouldn't be necessary, but casting will strip out any non-numerical characters, so it doesn't usually hurt to cast)
Additionally, MySQL is capable of parsing UNIX timestamps (with FROM_UNIXTIME(), I think, I'd have to look it up to be sure)
Answer: If $userLogin holds timestamp value than you don't need to use strtotime(),
For example, this one should work -->
$userLogin = time();
date('Y-m-d G:i:s', $userLogin);

Answer: I had to add
    $login = date('Y-m-d H:i:s',(int)($userLogin/1000));

and it worked...


Accidental error in setting php_value in .htaccess?

Question: So when I currently view phpinfo() in PHP, my error_reporting is set to some number, which represents the sum of all the error constant values, right?
Let's say, I accidentally set the value of error_reporting to some weird value by accident in .htaccess for example:

-1
Value that is bigger than E_ALL (32768 for example, if I'm correct)
When setting it with a string, I do a typo (**E_AL** & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED) - typo in E_ALL

What would happen, would it be set to some default value? Or from php.ini? I tried setting all the values above and they all were set in the Local Value without any problems.
I'm curious what will happen with any other value as well, will it default to php.ini or what?
Thanks!
Answer: PHP uses bitwise operators to determine whether the error level should be reported.. so whatever your integers value is as binary it would bitwise & to see if the error is reported.
E.g.
if E_DEPRECATED were (not saying this is accurate):  01, E_WARNING is 10, E_NOTICE is 100, using E_DEPRECATED | E_WARNING | E_NOTICE would give the binary 111, thus when an error is reported, like E_WARNING, it would take the value set, and bitwise & it to determine whether the report is displayed:
111 & 010 = True, so the error would be reported.
if you just used E_DEPRECATED | E_NOTICE, the binary is 101, so 101 & 010 = False, so the error won't be reported.
Each of these binaries can be converted to base10, 01 = 1, 10 = 2, 100 = 4 etc.
So if you were curious as to which errors would be reported with your random integer you can do:
int & E_WARNING in your PHP parser, if its True then the error will be shown, if its FALSE then the error will be ignored.
This is a good convention to learn, as its very useful when implementing logging on your application too, you can use the same system, and so you don't have to implement a long switch or if .. elseif .. block to determine whether a log level should be logged or not according to config.
  /**
   * Determines whether this message should be logged based on the provided type and the set threshold
   * @access protected
   * @param  int $type
   * @param  string   $name name of the log to check.
   * @return boolean
   */
  protected function should_log($type,$name='default') {
    return (bool) ($this->getConfig($name)->threshold & $type);
  }

so the threshold would be a binary number in your config (which uses constants for readability) then it bitwises & against the provided log type which returns True or False to determine whether to log the message to the logger by name $name... much more optimised.
Comment: Thank you very much, the bitwise & between my current error setting and active error makes sense, that helped me understand more how it works.
However, I used the `error_reporting` more as an example, even though I want to understand how it works aswell.
**The question I'm still curious about is**: what if we make a typo in `.htaccess` or in `php.ini`, what would happen? If it's in `.htaccess` will it take the value from `php.ini`? If there's a typo in `php.ini`, what then?
I tried experimenting and the value changed only in the `Local Value`. So how does `php.ini` get it's values?


Saving duplicate entries in a Flask SQLAlchemy association table

Question: I am designing a schema to audit which user has which monitors.
For a given audit, we have users. And each user can have zero or many monitors.
Also, a user can have many of the same monitor.
Here is my User class:
class User(db.Model):
    id = db.Column(db.Integer, db.Sequence('user_id_seq'),
                   autoincrement=True, primary_key=True)

    login = db.Column(db.String(140), unique=True)

    def __init__(self, login):
        self.login = login

    def __repr__(self):
        return '<User %r>' % self.login

Here is my Audit class:
class Audit(db.Model):
    id = db.Column(db.Integer, db.Sequence('audit_id_seq'),
                   autoincrement=True, primary_key=True)

    start_date = db.Column(db.DateTime)
    end_date = db.Column(db.DateTime)

    def __init__(self):
        self.start_date  = datetime.now()

    def __repr__(self):
        return '<Audit %r>' % self.id

Here is my Monitor class:
class Monitor(db.Model):
    id = db.Column(db.Integer, db.Sequence('monitor_id_seq'),
                   autoincrement=True, primary_key=True)

    description = db.Column(db.String(140), unique=True)

    def __init__(self, description):
        self.description = description

    def __repr__(self):
        return '<Monitor %r>' % self.description

Here is my UserAudit class:
class UserAudit(db.Model):
    id = db.Column(db.Integer, db.Sequence('user_audit_id_seq'),
                   autoincrement=True, primary_key=True)

    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship('user',
        backref=db.backref('user_audits', lazy='dynamic'))

    audit_id = db.Column(db.Integer, db.ForeignKey('audit.id'))
    audit = db.relationship('Audit')

    monitors = db.relationship('Monitor',
                                secondary=userAuditMonitor.association_table,
                                backref='user_audit_monitors')

    def __init__(self, user, audit):
        self.user = user
        self.audit = audit

    def __repr__(self):
        return '<UserAudit %r>' % self.id

And finally, here  is my UserAuditMonitor class which glues the whole thing together:
class UserAuditMonitor():
    association_table = Table('user_audit_monitor', db.Model.metadata,
        Column('user_audit_id', db.Integer, db.ForeignKey('user_audit.id')),
        Column('monitor_id', db.Integer, db.ForeignKey('monitor.id'))
    )

The above association table is super useful as I can simply use the .append() method and add more monitors to a UserAudit sqlalchemy object.
Example:
>>> u = UserAudit.query.get(1)
>>> monitors = [Monitor.query.get(3), Monitor.query.get(4)]
>>> u.append(monitors)
>>> print u.monitors
[<Monitor u'HP'>, <Monitor u'Dell'>]
>>> db.session.commit()
>>> print u.monitors
[<Monitor u'HP'>, <Monitor u'Dell'>]

However, if I try and append more than one of the same monitors to a UserAudit object, only one monitor gets stored.
Example:
>>> u = UserAudit.query.get(2)
>>> monitors = [Monitor.query.get(3), Monitor.query.get(3)]
>>> u.append(monitors)
>>> print u.monitors
[<Monitor u'HP'>, <Monitor u'HP'>]
>>> db.session.commit()
>>> print u.monitors
[<Monitor u'HP'>] # ONLY ONE MONITOR GOT SAVED HERE!!!

How do I configure the UserAuditMonitor class to save duplicates?
Thanks!
Comment: Relationships are used to track relationships between objects, so I think SQLAlchemy is detecting the duplicate link between the two objects and not adding the second.
Comment: Have you ever found a solution for that? Got he same problem here
Comment: ended up refactoring the whole thing.
Answer: My guess is that UserAuditMonitor doesn't have an explicitly defined primary key, so SQLA is using user_audit_id x monitor_id as the key and de-duplicates the relationship. Perhaps try adding an autoincrement primary key to the association_table?
Comment: Just added a primary key and still it does not save duplicates: Column('id', db.Integer, db.Sequence('user_audit_monitor_id_seq'), autoincrement=True, primary_key=True)
Comment: This actually helped me with this problem. Though I didn't use sequence like SeanPlusPlus tried, simply added an id column like my other models had... "id = db.Column(db.Integer, primary_key = True)" and called it good. Seemed to fix it up right away. Thanks for the suggestion.


Is an affine transformation of a symmetric random variable also symmetric?

Question: If the random variable X has a probability distribution function that is symmetric around the mean, does the random variable Y=a+bX has a symmetric probability distribution?
Also, what is the covariance and the correlation between X and Y?
Thanks!
Comment: Using the definition of symmetry offered at https://stats.stackexchange.com/a/29010/919, the answer is immediate, because the event $bX+a\ge b\mu+a$ (for any number $\mu$) is equivalent to either $X\ge \mu$ or $X\le \mu$ provided $b\ne 0$ (and when $b=0$ the variable $Y$ is constant, making it obviously symmetric).
Answer: By the change of variables formula, the pdf of $Y$ is given by $$f_Y(y) = f_X\left(T^{-1}(y)\right)\left\vert \frac{\mathrm d}{\mathrm dy}T^{-1}(y)\right\vert,$$
where $T(x) = a + bx$. Thus, $T^{-1}(y) = \frac{y - a}{b}$ and $\frac{\mathrm d}{\mathrm dy}T^{-1}(y) = \frac 1b$. So we have that $$f_Y(y) = f_X\left(\frac {y-a}b\right)\frac{1}{\vert b\vert}.$$ Let $\mu$ and $\nu$ denote the means of $X$ and $Y$, respectively. Note that $\nu = a + b\mu$. Now does it hold that $f_Y(\nu + y) = f_Y(\nu - y)$ for all $y\in\mathbb R$?
It holds that $$f_Y(\nu + y) = \frac{1}{\vert b\vert}f_X\left(\frac{\nu + y - a}{b}\right) = \frac{1}{\vert b\vert}f_X\left(\frac{a+b\mu - y -a}{b}\right) = \frac{1}{\vert b\vert}f_X\left(\mu - \frac yb\right)$$ and $$f_Y(\nu - y) = \frac{1}{\vert b\vert}f_X\left(\frac{\nu - y - a}{b}\right) = \frac{1}{\vert b\vert}f_X\left(\frac{a+b\mu - y -a}{b}\right) = \frac{1}{\vert b\vert}f_X\left(\mu + \frac yb\right).$$ For every $y\in\mathbb R$, let $x = \frac yb$. Then, since by assumption, $f_X(\mu + x) = f_X(\mu-x)$ for all $x\in\mathbb R$, we have that the distribution of $Y$ is symmetric.
Let $\sigma^2$ denote the variance of $X$. Then $b^2\sigma^2$ is the variance of $Y$. The covariance between $X$ and $Y$ is given by $b\sigma^2$, which can be verified easily by applying the usual laws for variance and covariance. Thus, the correlation between $X$ and $Y$ is given by $$\frac{b\sigma^2}{\sqrt{\sigma^2 b^2\sigma^2}} = \pm 1.$$
Note that since $X$ and $Y$ are perfect linear combinations, it's already clear that both variables are perfectly correlated.
Comment: It is not necessary to assume $Y$ has a pdf.  Indeed, the answer greatly simplifies when you don't assume this.
Answer: The answer from @Imaosome is already good, but I would like complement the first part and provide an answer that does not rely on the change of variables formula.
We say that $X$ is symmetric in around $\mu$ if $\mathbb{P}(X < \mu - x ) = 1 - \mathbb{P}(X > \mu + x ), \, \forall x \in \, \mathbb{R}$. Notice that $X$ might not have a density function, e.g. can be discrete. If the density exists, it is equivalent to $f_X(\mu - x) = f_X(\mu + x), \, \forall x \in \, \mathbb{R}$.
Assume $X$ is symmetric around $\mu$ and let $Y = a + bX$. We will prove that $Y$ is symmetric around $\gamma = a+b\mu$.
\begin{align}
\mathbb{P}(Y < \gamma - z) &= \mathbb{P}(Y < a + b\mu - z)\\
&= \mathbb{P}(a+bX < a + b\mu - z) \\
&= \mathbb{P}(X < \mu - z/b) \\
&= 1 - \mathbb{P}(X > \mu + z/b) \quad\textbf{(X symmetry)}\\
&= 1 - \mathbb{P}(Y > a + b\mu + z) \\
&= 1 - \mathbb{P}(Y > \gamma + z),
\end{align}
proving the result. Notice that $\mu$ does not necessarily have to be $E[X]$. In fact, $E[X]$ might not even exist, and the result still holds.
Comment: If $X$ is a discrete random variable taking on values $\pm 1$ with equal probability $\frac 12$, I think that most people would agree that $X$ has a symmetric distribution about $\mu = 0$ but for $x=1$, $F_X(\mu-1) = F_X(-1) = \frac 12$ whereas $F_X(\mu+1) = F_X(1) = 1$ and so it is _not_ true that $F_X(\mu-x)$ equals $1 - F_X(\mu+x)$ for _all_ $x \in \mathbf R$; it fails for $x=1$. More generally, for discrete random variables, the claim fails at every $x$ that is one of the possible values of the discrete random variable $X$. You need a better definition of symmetry.
Comment: This is the right approach.  However, you implicitly assume $b\gt 0.$  The demonstration works a little differently in the cases $b=0$ and $b\lt 0.$  For the "better definition of symmetry" requested by @Dilip, see the beginning of my post at https://stats.stackexchange.com/a/29010/919.  It shows that you are correct.  That request arises by confusing $\mathbb P$ with $F_X,$ but they are subtly different.
Comment: @whuber yes, the proof is slightly different if $b$ is not positive, thanks for pointing it out. Also, it is interesting to see the more general approach to symmetry in probability using group theory.
Comment: @DilipSarwate Indeed, good observation. The problem was that one sided included the equality sign, while the other did not. It probably can be stated using the c.d.f. and adding the mass probability (difference between right and left limit) in one of the sides, but I changed the definition to use the probability measure directly since it seems more readable. I think it will now cover the discrete cases.


Same module with different versions in several places

Question: This the directory structure of my drupal 8 installation:
├── composer.json
├── composer.lock
├── drush
├── LICENSE
├── load.environment.php
├── phpunit.xml.dist
├── README.md
├── scripts
├── vendor
└── web
    ├── autoload.php
    ├── core
    ├── index.php
    ├── modules
    │   └── custom
    │       └── xyz (version 1.0)
    ├── profiles
    │   └── custom
    │       └── qwer
    │           └── modules
    │               └── custom
    │                   └── xyz (version 1.1)
    ├── robots.txt
    ├── sites
    │   └── example.com
    │       └── modules
    │           └── custom
    │               └── xyz (version 1.2)
    ├── themes
    ├── update.php
    └── web.config

Which version of xyz module "win" in this structure ? For example:
- A site installed with qwer profile (sites/example.com).
- A site installed without qwer profile  (sites/example.com).
- Another option ?
I would like to know the preference that Drupal has when it have the same module with different versions in several places
Comment: From my experience the one that's been installed first will "win". But unsure how it will work with a fresh setup and `xyz` not installed at all but listed on the /admin/modules page. The only person who can test this quickly is you.
Comment: I know in D7 the sites overrode everything and I *think* modules overrode profiles.  However not sure if this logic survived the conversion to symphony et. al.
Answer: If each copy of the module in the directory structure is in fact a different version (the module's .info file must specify a version number), you can inspect the version listing either via Drush or on the modules listing (install) page.
Version Listing from the Modules Listing page

Navigate to /admin/modules
Find module "xyz" and expand the
description section to reveal which version is being
detected/loaded.
Refer to the example screenshot below, where
Activity Tracker has been expanded.

Version Listing via Drush

Run 'drush pm-list --no-core --status Enabled' to show a list of all modules other than those included with Drupal Core.
Scroll through the list to find your custom module and note the version number in the right column.
Refer to example screenshot below.

What if there are no version numbers, or they are all the same version?

Temporarily modify the version number in the info file.
Push the updated code to your server (if not a local copy of the site).
Flush Drupal Cache, rebuild the registry.
Follow the instructions above to detect which one is used.
Reset the version number and push the updated code to your server (if not a local copy of the site).

Drupal Multisite Note:
If you are running Drupal Multisite, each site with the custom module enabled may be referencing it from a different path (depending on where the module was located at the time the site was being built).

In this situation, check the versions on each site using the instructions above.
Find the most updated version being used so that you can consolidate all the other sites to use the same version/instance.

Consolidating duplicate instances of the module
Since this is a custom module, be sure to check that the functionality provided between versions is in fact the same and that there is an upgrade path between them before consolidating. Sometimes, lesser experienced developers will copy a custom module and completely overhaul its functionality for use on a similar or different site without understanding best practices.

Backup your code and databases, just in case you need to rollback.
Remove older versions/unused copies, ideally keeping/moving your one copy of the module in /web/modules/custom/.
Push the updated codebase to your server.
Clear caches and rebuild the registry.
Run update.php or drush updatedb to ensure any update hooks for the module are applied.
Test the functionality the module provides on each site (for some custom modules, you may need to edit/resave the configuration settings for the module to properly function).
If all is working, it's recommended to create a new restore point backup; otherwise troubleshoot until you get it working or rollback.


How to export my java application that is linked to sql server to an exe file?

Question: I finished my application and now i want to use it in other computers. It is linked to sql server database, so the question is, how can i export it to a file than can be installed in other computers, and all the informations to be stored in a file? I exported it to jar file but it only works in my computer because of my sql server. I searched for this thing but I didnt find any question that fits my question.
Comment: a properties file maybe?
Answer: If the sql server is local to the machine running the application (i.e. not a shared server at a single company), then you'll have to provide that database as part of the installation of your app/jar file, and the user will have to have SQL Server installed (perhaps the express edition).  If that's the case, have you considered using Derby or Sqlite instead?
If the server is shared and everyone running your application will be able to connect to it, a properties file to hold the connection information makes sense.
Answer: Agree with @ScaryWombat. When you distribute a program which require some configuration and you want those configuration to be changed and configured based on the target environment you want to include a mechanism for that.
A simple approach , if you have one or two configuration, those can be implemented to be read from the command line argument parsing.
if there are too many in that case you want to make use of property files.
In either case, i always suggest people to distribute their software application with a following directory structure as a package.
<code>basepackage_folder
--- bin ( place executable scripts here )
--- lib ( place the libraries here )
--- log ( folder to log your application logging messages )
--- etc ( place for configuration files )
--- README ( A file which is helpful for end user of your program on how to install and run )
</code>


Parameterise LINQ GroupBy

Question: The following C# code takes a large datatable with many columns and an array of 2 column names. It will give a new datatable with two rows where there are duplicate rows for the two fields supplied  staff no & skill.
This is too specific and I need to supply any number of fields as the groupby.
can someone help me?
<code>string[] excelField = new string[0]; // contains a list of field name for uniquness
excelField[0] = "staff No";
excelField[1] = "skill";
DataTable dataTableDuplicateRows = new DataTable();
dataTableDuplicateRows.Clear();
dataTableDuplicateRows.Columns.Clear();

foreach (string fieldName in excelField)
{
    dataTableDuplicateRows.Columns.Add(fieldName);
}

var duplicateValues = dataTableCheck.AsEnumerable()
    .GroupBy(row => new { Field0 = row[excelField[0]], Field1 = row[excelField[1]] })
    .Where(group => group.Count() > 1)
    .Select(g => g.Key);

foreach (var duplicateValuesRow in duplicateValues)
{
    dataTableDuplicateRows.Rows.Add(duplicateValuesRow.Field0, duplicateValuesRow.Field1);
}
</code>
Answer: I think what you require is something make the linq more dynamic, even though you could achieve it by using expression tree, the DynamicLinq library would appear to solve your issue in an easier way.
For you case, with the library, just use the GroupBy extension method with a string value.
More info about DynamicLinq library:
Scott Gu's blog

Parameterise LINQ GroupBy


Nearest neighbour problem (a quite simple one)

Question: I have the following traveling salesman problem:

My answers for these are 98 and 104 but the book's answers are 103 and 110 respectively. Who is right?
Comment: Upper bound on what?
Comment: The upper weight (maximum weight, or upper limit). It is a traveling salesman problem
Comment: Your attempt would be clearer by telling us the cycles you found.
Comment: The circles on the table show the path that I've found:
AECBDA and ADCBEA
Comment: @saulspatz: the OP means an upper bound on the length of the shortest cycle.
Answer: Using nearest neighbour to find a tour starting at A goes like this: 19 to E, 18 to C, 14 to B, 21 to D, and 26 to A, for a total path length of 19+18+14+21+26=98. Thus it looks like the book answer is wrong here.
Using the second distance matrix, you would find: start at A, 17 to D, 18 to C, 22 to B, 31 to E, and 22 to A, for a total of 17+18+22+31+22=110. Looks like here you miscalculated.
Comment: Sorry I mistyped the book's answers. It is as it is now.


Using Selection on dataTable primefaces

Question: I have a problem in primefaces using datatable.
I use the propertie selection but i can't take the object that I selected.
Take a look at my code

            <f:facet name="header">
                <h:outputText value="Registro de Produtos" />
            </f:facet>

                                <h:outputText value="#{p.id}" />

                <f:facet name="header">
                    <h:outputText value="Nome" />
                </f:facet>
                <h:outputText value="#{p.nome}" />

                <f:facet name="header">
                    <h:outputText value="Descrição" />
                </f:facet>
                                <h:outputText value="#{p.descricao}" />

                <f:facet name="header">
                    <h:outputText value="Valor Un." />
                </f:facet>
                                <h:outputText value="#{p.valorUnitario}" />

                <f:facet name="header">
                    <h:outputText value="Remover" />
                </f:facet>
                <f:ajax event="click" render="@form"
                    listener="#{produtoBean.remove(p)}">
                    <h:commandLink value="Remover" />
                </f:ajax>

                    <f:facet name="footer">

                    </f:facet>

                     <h:panelGrid id="display" columns="2" cellpadding="4">
                         <h:outputText value="Nome" />
                         <h:outputText value="#{produtoBean.selectedProduto.nome}" />
                     </h:panelGrid>

My Managed Bean
@ManagedBean
public class ProdutoBean{
    @ManagedProperty(value = "#{entityManager}")
    private EntityManager entityManager = Persistence.createEntityManagerFactory("PrimeiroTeste").createEntityManager();

    private Produto produto = new Produto();
    private List<Produto> produtos;
        private Produto selectedProduto = new Produto();

    public void save(){
        ProdutoRepository produtoRepository = new ProdutoRepository(this.entityManager);
        produtoRepository.save(this.produto);

        this.produto = new Produto();
        this.produtos = null;
    }
    public void remove(Produto produto){
            ProdutoRepository produtoRepository = new ProdutoRepository(this.entityManager);
            produtoRepository.remove(produto);

            this.produtos = null;
    }
    public List<Produto> getProdutos(){
        if (this.produtos == null){
                    ProdutoRepository produtoRepository = new ProdutoRepository(this.entityManager);
                    this.produtos = produtoRepository.getProdutos();
                }
        return this.produtos;
    }
    public Produto getProduto(){
        return this.produto;
    }
    public void setProduto(Produto produto){
        this.produto = produto;
    }

    public void setEntityManager(EntityManager entityManager){
        this.entityManager = entityManager;

    }
    @SuppressWarnings("unused")
    private EntityManager getManager() {
        FacesContext fc = FacesContext.getCurrentInstance();
        ExternalContext ec = fc.getExternalContext();
        HttpServletRequest request = (HttpServletRequest) ec.getRequest();
        return (EntityManager) request.getAttribute(" EntityManager ");
    }

    public Produto getSelectedProduto() {
        return this.selectedProduto;

    }

    public void setSelectedProduto(Produto selectedProduto) {
        this.selectedProduto = selectedProduto;
    }
}

When I open my dialog it don't bring the selectedProduto.nome
Someone can help me?
Answer: Take a look at the Primefaces ShowCase
You always create a new Product for your selectedProduto
private Produto selectedProduto = new Produto();

try it with this code:
private Produto selectedProduto;

the getters and setters are already there as is saw.
Comment: Hi, I was following the ShowCase, but that part don't work for me. I don't know what I do wrong. And I made that change but nothings happen.

Using Selection on dataTable primefaces


Views Send with multiple email fields

Question: I've just got Views Send to work. I have a custom node type, with two email fields. One field contains a~single email address, the second field can contain more email addresses. Using Views Send, I can send mail to either field (even when one field can contain more email addresses).
The question is, can I use Views Send to send an email to both fields at the same time? Now I can only select one field containing emails. Sometimes it is necessary to send the same mail to both fields.
Yves
Answer: I had a look at this interesting module and I am afraid I didn't see a way to do this. I tried Views rewriting, to collect all email addresses from first and second email field into a third one. Standard Views presented the new dynamic field fine... But, this is not supported by the Views Send module. It seems like it would need the data available in the database, and not dynamically generated.
If you want to have that working in an easy way, you could try adding a Computed Field to your content-type. This computed field would then store all the emails from your first and second field. And this concatenated string would be available to Views Send.
Would that be a way out for you? If so, here is an 'draft' version for the code to put in the "Computed Code (PHP)" textarea:
<code>$field_main = field_get_items($entity_type, $entity, "field_main");
$field_additionals = field_get_items($entity_type, $entity, "field_additional");

if(isset($field_main[0])) {
  $emails[] = trim($field_main[0]["value"]);
}

foreach($field_additionals as $field_additional) {
  if(trim($field_additional['value']) !== '') {
    $emails[] = trim($field_additional['value']);
  }
}

$entity_field[0]["value"] = implode(', ', $emails);
</code>
Voila! Your computed field is readily available in your Views and Views Send containing all the emails from both fields.

Views Send with multiple email fields


Proof by Induction involving divisibility

Question: I'm trying to inductively prove:
$(a-b) | (a^n - b^n)$ where a,b are real numbers, and n is a real number and also 0
I've done my base case at zero, and made my inductive hypothesis:
$(a-b) | (a^{k+1} - b^{k-1}))$
I'm stuck here, a majority of the induction proofs I'm using involve proving something divides another, and would like some help on what to do with these. I have considered writing:
$(a^{k+1} - b^{k-1})) = s * (a-b)$, where $s$ is an element of the integers, but am still stuck there
thanks for answering!
Comment: I hope you know how to prove this without induction and that induction is called for only for induction practice: $a^n-b^n = (a-b)(a^{n-1}  + a^{n-2}b + \cdots  + b^{n-1})$.
Comment: If $a,b$ are real numbers, I'm not even sure what that divisibility means. If I take $(a,b)=(4.7,2.1)$ then $a-b=2.6$, $a^3-b^3 =94.562$ and the ratio is clearly not integer.
Answer: Hint (if sticking to induction): $a^{k+1}-b^{k+1}=a^{k+1}-ab^k + ab^k-b^{k+1}=a(a^k-b^k)+b^k(a-b)$


Can we give a precise definition to say "$b$ is $m$- times greater than $a$?"

Question: Let $a,b\in R$ and $a<b.$ Can we give a precise definition to say "$b$ is $m$- times greater than $a$?" in general. For the positive $0<a<b$ it is clear. "We say that $b$ is $m$-times greater than $a$ if $\frac{b}{a}=m.$" How about if both are negative or one negative the other one is positive?
Comment: @MIYY: Please include specific concerns (eg, negatives) as part of the question itself, so that people don't waste time giving responses you're prepared to rebut. (I'd thought your concern might relate to how "$b$ is $100\%$ bigger than $a$" means $b=a+a=2a=a\cdot 200\%$, yet some people (wrongly) say "$a$ increased by $300\%$" to mean $a\to a\cdot 300\%$.) ... In any case, common language is ambiguous, so formal translation can depend upon context. It might be good to ask how best to *informally* translate $b=ma$, since "$m$-times bigger" may not always *sound* right (eg, with negatives).
Comment: This means $b = ma$.
Comment: Good point, actually. It's so simple to accidentally assume that variables are positive ...
Comment: @Toby Mak. I don't think so
Comment: I would agree with Toby. What makes you disagree, MIYY? Do you have a particular example for this?
Comment: @Matti P. Let's take $a=-8$ and $b=-2$ try to write $b$ is 4 time bigger than $a$
Comment: @Blue My concern is the following. Two different negative numbers are given  $a a$. If both $a$ and $b$ are less than zero, then that will not be true as $-b < -a$. As Matti P. and Blue pointed out, you can think in terms of _absolute values_.
Answer: I would say that "b is m times as large as a" means that b= ma but that "b is m times larger than a" means that b= a+ ma= (m+1)a.
Comment: The second variant is very original.


cant reach content in block--views

Question: I am new to Drupal8.
How can i get the content ?
I call a view in page.html.twig like:

{{ page.content.views_block__serviceboxen_block_1 }}

and created a template with name:

block--views-block--serviceboxen-block-1.html.twig

How can i access to the content from my view in this template ?
I have no idea when i use
{% for row in rows %}

and
{% for item in items %}

thanks a lot.
Answer: solution: you can access the fields with 'content'
e.g. content.body or content.your_field_name.value
in a iteration it looks like:

  {% for item in content['#view'].result %}
      {% set topic = item._entity %} {# just for shorter writing #}

{{ topic.title.value }}
 {# or topic.yourFieldName.value #}

  {% endfor %}

Hope it'll help

cant reach content in block--views


PHP unzip deflate64

Question: I am currently facing an issue while trying to decompress a ZIP file that utilizes Deflate64 compression in PHP using the ZipArchive class. The extraction process seems to be working well for regular Deflate compression, but encounters difficulties when dealing with Deflate64.
Here's an example of a successful extraction using regular Deflate compression:
$zip = new ZipArchive();
$zip->open('deflate.zip');
$zip->extractTo('/tmp/test_extract');
(bool) true

However, when attempting to extract a ZIP file that uses Deflate64 compression, the process fails:
$zip = new ZipArchive();
$zip->open('deflate64.zip');
$zip->extractTo('/tmp/test_extract');
(bool) false

Furthermore, checking if Deflate64 compression is supported using ZipArchive::isCompressionMethodSupported returns false:
ZipArchive::isCompressionMethodSupported(ZipArchive::CM_DEFLATE64);
(bool) false

On the other hand, regular Deflate compression is supported:
ZipArchive::isCompressionMethodSupported(ZipArchive::CM_DEFLATE);
(bool) true

I am reaching out to the community to inquire if there is a known solution or workaround to enable the extraction of ZIP files using Deflate64 compression in PHP's ZipArchive class. Any insights or code snippets that address this issue would be greatly appreciated.
Thank you in advance for your assistance!
Answer: It looks like the libzip team just don't want to support deflate64 yet, you can use zlib to inflate each file individually.
$destination = '/tmp/test_extract';
for ($i = 0; $i < $zip->numFiles; $i++) {
    $st = $zip->statIndex($i);
    $filename = $stat['name'];
    if ($st['comp_method'] === ZipArchive::CM_DEFLATE64){
        $data = $zip->getFromIndex($i, 0, ZipArchive::FL_COMPRESSED);
        file_put_contents("$destination/$filename", gzinflate($data));
    } else {
        $zip->extractTo($destination, $filename);
    }
}

Note: You need to create subfolders by yourself.

Update: Decompress large files (PHP >= 8.2)
$inf = inflate_init(ZLIB_ENCODING_RAW);
for ...
    $src = $zip->getStreamIndex($i, ZipArchive::FL_COMPRESSED);
    $dst = fopen("$destination/$filename", 'wb');

    while(!feof($src)){
        $data = fread($src, 8192);
        $data = inflate_add($inf, $data, feof($src) ? ZLIB_FINISH : ZLIB_NO_FLUSH);
        fwrite($dst, $data);
    }

    fclose($src);
    fclose($dst);
...

Comment: It works; however, be cautious with large files as everything is stored in RAM. If anyone has a better solution, I'm open to suggestions.
Comment: With PHP>=8.2, you can use `getStreamIndex` to get a stream instead of the whole data.
Comment: I tried, but it doesn't work, at least not with deflate64.
Answer: As you have rightly checked, Deflate64 is not supported by the standard PHP ZipArchive
I would suggest using 7zip
$command = "7z x deflate64.zip -o/tmp/filename";
exec($command, $output, $returnVar);
if ($returnVar === 0) {
    // worked
} else {
    // failed
}

PHP unzip deflate64


Find image of a function $f: \mathbb{N} \to 2^\mathbb{N}$, $(0\in \mathbb{N})$; $f(n) = \{ k\in \mathbb{N} :2^k | n\}$.

Question: I have such function $f: \mathbb{N} \to 2^\mathbb{N}$, $(0\in \mathbb{N})$;  $f(n) = \{ k\in \mathbb{N} :2^k | n\}$. Find image of $f(P)$ and $f^{-1}(P)$, where $P$ is a set of prime numbers.
I actually dont understand what $2^\mathbb{N}$ is, is it a set of all subsets of $\mathbb{N}$?
Comment: Yes, and the function $f$ gives all the non-negative integers less than $K$, where $K$ is the power of $2$ in the prime factorization of $n$.
Comment: Note that $f(2) = \{0,1 \}$ and for any odd prime $p$ we have $f(p) = \{0\}.$ So $$f(P) = \bigcup\limits_{p \in P} f(p) = \{0,1\}.$$
Comment: Hint for $f(P)$: if $p\in P$, then what is $f(p)$?
Comment: In general, if $A,B$ are sets, then $A^B$ denotes the set of functions from $B\to A$.  If $A$ is a set with $2$ elements, informally written as "$A=2$", then this is the same as the set of subsets of $B$ since specifying a subset is the same as specifying a function to $\{0,1\}$ (if $S\subset B$, then $F_S(b)=1$ if and only if $b\in S$).  See [this](https://en.wikipedia.org/wiki/Currying#Set_theory) for a reference to the notation.
Comment: $f(P)$ should be a set of *subsets* of $\Bbb N.$  @AnilBagchi.
Answer: $2^\Bbb N=\mathscr P(\Bbb N)$ is the power set, or the set of all subsets of $\Bbb N .$  Intuitively,  for each natural number,  it can either be in the subset, or not. Thus a subset identifies naturally with a function from $\Bbb N$ to a two element set.
If $P$ is a set of more than one primes with $2\in P,$ then $f(P)=\{\{0\},\{0,1\}\}$, and $f^{-1}(P)=\emptyset.$
Comment: @Alex I agree with you. I mean $\{0,1\}$ if $2 \in P$; otherwise, just $\{0\}$.
Comment: Are you sure, because I thought that this function`s output should be a set of k,  in a power of which 2^k devides every number in a set of prime numbers.
Comment: I thought it was just a set of {1,0}
Comment: @amrsa Thanks) Yeah, 2 belongs to P. And the  $f^{-1} $would be just all rationals??
Answer: It seems you already concluded that
$$
f(P)=
\begin{cases}
\{0,1\} & \text{if }2 \in P,\\
\{0\} & \text{otherwise.}
\end{cases}
$$
Now,
\begin{align}
f^{-1}(P)
&= \{n \in \mathbb N : f(n) \in P\}\\
&= \left\{n \in \mathbb N : \left\{k \in \mathbb N : 2^k|n\right\} \in P\right\}.
\end{align}
Now, if $2^p|n$, then certainly $2^1=2|n$ (and, of course, $2^0=1|n$), but $0$ and $1$ are not primes.
So there is no $n \in \mathbb N$ such that $2^p|n$ but $2{\nmid}n$, i.e., for all $n \in \mathbb N$, if
$\left\{k \in \mathbb N : 2^k|n\right\}$ includes some prime $p$, it must include all naturals $m\leq p$, and so $f^{-1}(P)=\varnothing$.


How do I lock a folder with htaccess file?

Question: I am trying to lock a folder on my site with htaccess file
I created a htaccess file in the root and I created a htpasswd file inside the folder I want to lock
But the problem is that it does not work and I am banned from entering the entire site until I delete the "Require valid-user" from the .htaccess file in order to allow me to enter the site.
htaccess file
ErrorDocument 404 /404.html
#Protect Directory
AuthName "Dialog prompt"
AuthType Basic
AuthUserFile /fares/.htpasswd
Require valid-user

htpasswd file
fares:djefaflia

It does not work on the local server or on the hosting
Answer:
AuthUserFile /fares/.htpasswd

The file-path provided to AuthUserFile should be an absolute filesystem path, not a root-relative URL-path (ie. it should not be relative to the document root) which is what this looks like. (Confusingly, a relative path is resolved relative to the ServerRoot, not the root of the filesystem.)
The "absolute filesystem path" is the full file-path to the .htpasswd file on the server. For example, if the server path to your document root directory (where your HTML files are located) is /home/user/public_html and you are wanting to protect the directory /fares within your document root and you are storing the .htpasswd file inside that directory (although that is not recommended - see below) then the AuthUserFile directive should be like the following instead:
AuthUserFile /home/user/public_html/fares/.htpasswd

However, you should avoid storing the password file in the same directory you are protecting (for security reasons). Ideally, this file would be stored outside of the document root (ie. outside of the public HTML space). For example, you could mirror the file structure in a htpasswds directory above the document root in which you store all the relevant .htpasswd files on your system:
AuthUserFile /home/user/htpasswds/fares/.htpasswd

fares:djefaflia

As written, this does not "look" correct (unless you are intentionally trying to store plain text passwords - which won't work on Linux). How are you generating the password file? You should be using a tool like htpasswd.exe (that comes with Apache), or something similar that generates a hash of the password. For example, it should look more like this:
fares:$apr1$6Szn.sq3$7E6ZMJLBAZKWX.wmGRISu1

Comment: Explain to me more because I understand to you exactly what I should do now
Comment: @Fares Which bit are you struggling with? I have already covered it in reasonable detail.
Comment: here : The file-path provided to AuthUserFile should be an absolute filesystem path, not a root-relative URL-path (ie. relative to the document root) which is what this looks like.
Comment: @Fares I've updated the wording to try and make it clearer.


Find two points on $r=\theta$ such that the tangent lines to the graph at the points are parallel

Question: I was asked by my instructor to find two different points on the curve $\gamma(t)$ given by:
$$ \gamma(t) = (t\cos(t),t\sin(t)) \\ t\in(-\infty,\infty)$$
Such that the tangent lines to $\gamma(t)$ at those points are parallel. I noticed this is an Archimedean spiral ($r=\theta$), and managed to construct the following formula for the slope of a tangent line to $\gamma(t)$ at $t=t_0$:
$$m=\frac{\sin(t_0)+t_0\cos(t_0)}{\cos(t_0)-t_0\sin(t_0)}$$
I tried to substitute $\sin(t)=\cos(t)$ in order to get an explicit solution, but it won't work. If for example I try to find two points where the tangent lines are parallel to the $x$ axis, I am left with the equation $\tan(t)=-t$, which of course I cannot solve (only Taylor can help but I prefer to avoid using it, if possible).
My instructor emphasized that I have to find 2 points explicitly, and that 2 of them are enough (meaning I don't need to find all of the points with respect to some sort of a pattern).
Thanks!
Answer: The curve is bilaterally symmetric: $x(t)=-x(-t)$ and $y(t)=y(-t)$.
So if tangent line is vertical or horizontal for some t, the symmetric point -t will have parallel tangent line as well.
From the tangent all points such that $\sin(t_0) + t_0 \cos(t_0)=0$ correspond to horizontal tangents and $\cos(t_0) - t_0 \sin(t_0)=0$ correspond to vertical tangents.
Comment: Can you prove that there are infinite horizontal and vertical tangents? (I can but I think you deserve the credit for it because it was your answer that made me realize it.)
Answer: COMMENT.- You just need equality of derivatives. Since $r=\theta$ we have $\dfrac{dy}{dx}=\dfrac{\sin(\theta)+\theta\cos(\theta)}{ \cos(\theta)-\theta\sin(\theta)}$.
It follows that you need two distinct values $\theta_1$, $\theta_2$ such that
$\dfrac{\sin(\theta_1)+\theta_1\cos(\theta_1)}{ \cos(\theta_1)-\theta_1\sin(\theta_1)}=\dfrac{\sin(\theta_2)+\theta_2\cos(\theta_2)}{ \cos(\theta_2)-\theta_2\sin(\theta_2)}$
Unfortunately, you have a transcendental equation $f(x)=\dfrac{\sin(x)+x\cos(x)}{\cos(x)-x\sin(x)}=a$ where $a$ can be an arbitrary real number. You cannot find  exact solutions, just approximative ones. For example, for $a=1$ you can find $\theta_1\approx0.4026$ and $\theta_2\approx2.7097$. This way you have
$$f(\theta_1)\approx0.999895\\f(\theta_2)\approx0.999932$$


How do I deploy a static site generated by Nextjs to Vercel?

Question: I used the Nextjs static site generator to output a simple static site. I am attempting to deploy this site to Vercel but I keep getting an error while it is building. I have deployed this same site to static hosting sites in the past, but want to try Vercel now.
The nextjs docs explicitly say my nextjs app requires zero config:

We strongly recommend using Vercel even if your Next.js app is fully static. Vercel is optimized to make static Next.js apps blazingly fast. next export works with Zero Config deployments on Vercel.

This is my package.json, the deployment scripts run npm export which runs next build && next export to create the out/ directory, like the docs recommend:
{
  "name": "new-barber-shop",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next",
    "build": "next build && next export",
    "export": "next export",
    "start": "next start"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@zeit/next-css": "^1.0.1",
    "google-maps-react": "^2.0.2",
    "next": "^9.1.2",
    "react": "^16.11.0",
    "react-bootstrap": "^1.0.0-beta.14",
    "react-dom": "^16.11.0",
    "semantic-ui-react": "^0.88.1"
  }
}

Here is a portion of the Vercel deployment build logs containing the error:
22:42:26.610
Compiled successfully.
22:42:26.611
22:42:26.612
Automatically optimizing pages...
22:42:27.095
22:42:27.109
Page            Size     Files  Packages
22:42:27.109
┌ ⚡ /           98.9 kB      2        13
22:42:27.109
├   /_app       223 kB       0         2
22:42:27.109
├   /_document
22:42:27.109
└   /_error     1.96 kB      0         0
22:42:27.109
22:42:27.109
λ  (Lambda)       page was emitted as a lambda (i.e. getInitialProps)
22:42:27.109
⚡  (Static File)  page was prerendered as static HTML
22:42:27.109
22:42:27.445
Error: Cannot export when target is not server. https://err.sh/zeit/next.js/next-export-serverless
22:42:27.445
    at _default (/vercel/path0/node_modules/next/dist/export/index.js:1:2956)
22:42:27.445
    at nextExport (/vercel/path0/node_modules/next/dist/cli/next-export.js:20:325)
22:42:27.445
    at /vercel/p

As you can see it compiled successfully, but runs into an error when it tries to export I believe. Any ideas?
This is my next.config.js:
module.exports = {
  target: 'serverless',
    exportPathMap: function() {
      return {
        '/': { page: '/' }
      };
    }
  };

Error log when running npm run build in local project (identical to error output when deploying to Vercel
$ npm run build

> email@example.com build F:\Austin\web-apps\new-barber-shop
> next build && next export

Browserslist: caniuse-lite is outdated. Please run next command `npm update`
Creating an optimized production build

Compiled successfully.

Automatically optimizing pages

Page            Size     Files  Packages
┌ ⚡ /           98.9 kB      2        13
├   /_app       223 kB       0         2
├   /_document
└   /_error     1.96 kB      0         4

λ  (Lambda)       page was emitted as a lambda (i.e. getInitialProps)
⚡  (Static File)  page was prerendered as static HTML

Error: Cannot export when target is not server. https://err.sh/zeit/next.js/next-export-serverless
    at _default (F:\Austin\web-apps\new-barber-shop\node_modules\next\dist\export\index.js:1:2956)
    at nextExport (F:\Austin\web-apps\new-barber-shop\node_modules\next\dist\cli\next-export.js:20:325)
    at commands.(anonymous function).then.exec (F:\Austin\web-apps\new-barber-shop\node_modules\next\dist\bin\next:29:346)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! firstname.lastname@example.com build: `next build && next export`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the email@example.com build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Austin\AppData\Roaming\npm-cache\_logs\2021-09-01T04_17_12_371Z-debug.log

Answer: You are probably having "target": "serverless" in your next.config.js. Remove it or set it to "target": "server".

Next.js can only handle exporting when the target is set to server (this is the default value). A serverless build, for instance, has no handler for requests–this is usually implemented by a hosting provider.

EDIT: It appears that the error was due to old version of Next.js, most probably because they then understood Zeit (now Vercel) as a serverless platform and used to override the target. Updating the version will fix the problem. Also add .next, out, etc. to .gitignore. Here is the updated repo.
Comment: Thank you for your reply. I posted my `next.config.js` file above. Can you please explain where you would put the `"target": "server"` in the file? I'm a bit rusty when it comes to `next.js` development. I'm only touching up an old website.
Comment: Thank you @brc-dd, updated `next.config.js` but still got same error when deploying to Vercel. Also got the same error running `npm run build` locally.
Comment: I know, I just realized that stupid mistake a few minutes ago! I changed `target` to `server` and `npm run build` worked locally, but still gave me the same error on Vercel... It doesn't make any sense. Here is my repo -- https://github.com/austinwark/new-barber-shop
Comment: Like I said, I am a bit rusty with nextjs development (took a break to learn Android app dev)! After updating Nextjs and my npm packages, deployment to Vercel worked! Thanks a ton for your help -- I marked your answer accepted!


iOS : Google Maps API failing when applying API KEY restrictions

Question: When I use Google API key without any API key restrictions, Google Maps loads just fine in the app. As soon as I apply restrictions such as:

Application Restriction : iOS app : Accept requests from an iOS
application with one of these bundle identifiers
API Restrictions by service

The app rashes medially on maps access.
Comment: did you check enabling billing and what is your bundle identifier to call google maps API? https://developers.google.com/maps/documentation/ios-sdk/get-api-key
Comment: @tamsler Can u share piece of source that is creating crash? I guess i can help you.
Comment: Please [edit] to add meaningful code and a problem description here. Posting a [Minimal, Complete, Verifiable Example](http://stackoverflow.com/help/mcve) that demonstrates your problem would help you get better answers. Thanks!
Comment: Only system libraries are referenced in the stack trace.
Answer: I have created an working example with snapshots. I just followed the the Google Maps tutorial. It did not crashed for me with or without restrictions for ios app.
google maps working example added
Location Manager added
Location Updates handled
Network Reachability Added
Hope it helps.
Comment: @tamsler check out the Answer
Answer: SIGABRT (Signal abort) means there should be something to signal but it's aborted some how. Usually it tells you why its crashing.

So first Check the console for description:

[

If there is nothing printed, Try simulator instead of real device.
Its much more powerful than real device for debugging purposes.
Make sure you are in the debugging configuration:

[
 - You can turn on memory management options in diagnostics for better results if you doesn't find the issue: (Specially Zombie Objects)
[

Also you can try add some exception breakpoint to catch the issue before it going happen:

[
I think one of the above should lead you to something more specific about the issue and it's reason. Then you can absolutely handle it.


Are loss functions necessarily additive in observations?

Question: In all of the contexts I've seen loss functions in statistics/machine learning so far, loss functions are additive in observations. i.e.: loss $Q_D$ of dataset $D$ is an additive aggregation of losses at observations $i\in D$: $Q_D(\beta)=\sum_{i\in D}Q_i(\beta)$. e.g. in the loss that is a simple sum of squared residuals: $Q_D=\sum_i(y_i-X_i\beta)^2$.
This seems sensible, but I am wondering: Are there contexts in statistics/machine learning in which it happens (or reasons in theory why one might want) that a loss function is used that is not additive (or even separable) in observations?
Comment: It is not about additivity, but about taking average of your losses between the samples in your dataset. For the sole purpose of minimizing it, we can drop the 1/n constant, so arithmetic mean becomes a sum.
Comment: @Tim, sure but now the question becomes, do we ever want a loss function that is NOT the average of some function for each separate observation. This just reframes the question, since every additively separable function can be seen as an "average" by multiplying by 1/n, and vice versa. The question remains the same.
Comment: A related question is posted [here](https://stats.stackexchange.com/questions/432576/): *Realistic/intuitive example where a nonadditive loss function is preferred over additive ones*.
Answer: Loss functions are not always additive in observations: A loss function is function of an estimator (or predictor) and the thing it is estimating (predicting).  The loss function is often, but not always, a distance function.  Moreover, the estimator (predictor) sometimes, but not always, involves a sum of terms involving a single observation.  Generally speaking, the loss function does not always have a form that is additive with respect to the observations.  For prediction problems, deviation from this form occurs because of the form of the loss function.  For estimation problems, it occurs either because of the form of the loss function, or because of the form of the estimator appearing in the loss function.
To see the generality of the loss form for a prediction problem, consider the general case where we have an observed data $\mathbf{y} = (y_1,...,y_n)$ and we want to predict the observable vector $\mathbf{y}_* = (y_{n+1},...,y_{n+k})$ using the predictor $\hat{\mathbf{y}}_* = \mathbf{H}(\mathbf{y})$.  We can write the loss for this prediction problem as:
$$L(\hat{\mathbf{y}}_*, \mathbf{y}_*) = L(\mathbf{H}(\mathbf{y}), \mathbf{y}_*).$$
The loss function in your question is the Euclidean distance between the prediction vector and the observed data vector, which is $L(\hat{\mathbf{y}}_*, \mathbf{y}_*) = ||\hat{\mathbf{y}}_* - \mathbf{y}_*||^2 = \sum_i (\hat{y}_{*i} - y_{*i})^2$.  That particular form is composed of a sum of terms involving the observed values being predicted, and so the additivity property holds in that case.  However, there are many other examples of loss functions that give rise to a form that does not have this additivity property.
A simple example of two loss functions that are not additive in the observations are when the loss is equal to the prediction error either from the best prediction, or from the worst prediction.  In the case of "loss from best prediction" we have the loss function $L(\hat{\mathbf{y}}_*, \mathbf{y}_*) = \min_i |\hat{y}_{*i} - y_{*i}|$, and in "loss from worse prediction" we have the loss function $L(\hat{\mathbf{y}}_*, \mathbf{y}_*) = \max_i |\hat{y}_{*i} - y_{*i}|$.  In either case, the loss function is not additive for the individual terms.
Comment: Could you perhaps add an example of a loss function that is not additive in observations?
Comment: Still pretty interested in an example...
Comment: @RichardHardy: I just edited to add a couple of examples.  Hope that is useful.
Comment: Thank you! I do not see a technical problem with your examples, but I wonder about applications in which these kinds of loss functions could be relevant. Could you describe a hypothetical situation where $\min$ or $\max$ loss would be a logical choice? I guess I could imagine how they could be relevant when predicting the same observation with multiple attempts, but I cannot come up with an example where this works for predicting different observations.
Comment: @RichardHardy: Yeah, I'm not really sure of the practical value of loss functions like this.  They could arise in competition environments where there is a scoring rule like this --- e.g., you get judged solely on your best prediction, or your worst.  It would be difficult to think of a practical example where it is not directly constructed.
Comment: Which brings about the question: should the loss functions not be restricted to the class of additive in observations? I have posted [a new question](https://stats.stackexchange.com/questions/432576/) asking specifically for examples where nonadditive loss functions actually make sense in practice.
Answer: There are two most common causes for loss function being a sum/average.
First, you may simply define your loss as average of some metric. It's related to concept of risk minimization.
Second reason is that you use Maximum Likelihood or something related, like Maximum A Posteriori. Additivity comes from the fact that Maximum Likelihood solves
$$\arg\max_{\theta} P_{\theta}(Dataset) = \arg\max_{\theta} \prod_{x \in Dataset} P_{\theta}(x)$$
which is equal to $$\arg\min_{\theta} \sum_{x \in Dataset} -log(P_{\theta}(x)).$$
For example, if $P_{\theta}$ is Gaussian you'll get exactly mean squared error.
Comment: We formally *do not* need to use log-likelihoods, you can maximize the likelihood, so this is rather an example where we use product rather then a sum, isn't it?
Comment: You call it a "reason" for using sum in cost function, but it is just another representation of it, not a "reason" for taking sum.
Comment: Note that in these likelihood expressions, the sum or product is a direct consequence of the IID assumption in the data.
Comment: I don't understand your reasoning. These optimization problems are (mathematically) perfectly equivalent, so it does as much sense to say that you optimize a sum as you optimize a product. Sums are used in practice because of better numeric properties (multiplying a lot of numbers close to zero can be problematic due to loss of precision)
Comment: Ah, in this case you're right. I tried to explain where do sums come from in loss functions. Even if technically what is optimized is not necessarily a sum.


Issues with GAN and VAE models

Question: I'm reading this amazing paper on Normalizing Flows https://arxiv.org/pdf/1908.09257.pdf but one sentence kind of bothers me:

GANs and VAEs have demonstrated impressive performance results on
challenging tasks such as learning distributions of natural images.
However, several issues limit their application in practice. Neither
allows for exact evaluation of the probability density of new points.

Maybe I misinterpret it somehow... But can someone explain to me why VAE (or GAN to this matter) cannot evaluate probability density of new points? Isn't it the whole idea of estimating PDF's parameters, so we can evaluate it at any point we want, i.e. new points?
Or do you think the author was making emphasis on "exact evaluation" part?
Answer: They're some sort of generative models, learning the PDF so that they can sample from it. This is achieved by having random latent representations and mapping them to the relevant domain. So, you can easily generate new samples, but, this is not the same thing as calculating the probability of that sample. The learnt parameters belong to the neural network, not the PDF itself directly. There is no explicit calculation of the probability. To do that, you may need to resort to Monte Carlo methods.
Comment: In principle, yes, because we have a way to sample the distribution. But it may be quite expensive.
Comment: Oh, in other words latent space distribution has nothing to do with `p(x)` because in order to generate new sample `x_hat` we sample from latent distribution `Z` and map it to domain `X` using decoder of VAE, i.e. we use `p(x|z)`. And you're saying that in order to obtain `p(x)` we can use Monte Carlo methods. Right?

Issues with GAN and VAE models


Why does winforms CheckBox not meet top of container

Question: I am trying to "pleasantly" align tops of control in a left-to-right flowpanel.
I have a checkbox and several numericUpDowns. BUT the checkbox always has some sort of margin or padding at the top. So, I have to add margn at top of numericUpDown to get them to line up.
This isn't ideal. Why can't I get checkBox to start directly below top of flowpanel, just like numericUpDown does?
<code>public partial class Form1 : Form
{
    public static FlowLayoutPanel ControlPanel;
    public void CreateControls()
    {
        ControlPanel = new FlowLayoutPanel();
        ControlPanel.SuspendLayout();
        ControlPanel.FlowDirection = FlowDirection.LeftToRight;
        ControlPanel.Height = 40;
        ControlPanel.Width = this.flowLayoutPanel1.Width - 10;
        ControlPanel.WrapContents = false;
        ControlPanel.AutoScroll = true;
        ControlPanel.Anchor = AnchorStyles.None;
        ControlPanel.BorderStyle = BorderStyle.FixedSingle;

        ControlPanel.Controls.Add(LabelWithText("LB", 60));

        AddNumericUpDown("Ledge", 20, 0, 1m, -500m, 500m);
        AddCheckBox("UseExit", "UseExit", false);
        AddNumericUpDown("WrongLedge", 30, 0, 1m, -500m, 500m);

        AddNumericUpDown("Max", 100000, 0, 100000m, 0m, 1000000m);

        ControlPanel.ResumeLayout();

        this.flowLayoutPanel1.Controls.Add(ControlPanel);

    }

    public Label LabelWithText(string text, int width)
    {
        Label label = new Label();
        label.Text = text;
        label.Width = width;
        label.Top = 0;
        return label;
    }

    public void AddCheckBox(string name, string text, bool initialValue)
    {
        CheckBox checkBox = new CheckBox();
        checkBox.Name = name;
        checkBox.Text = text;
        checkBox.Checked = initialValue;
        checkBox.Top = 0;
        checkBox.Margin = new Padding(5,0,0,0);
        checkBox.TextAlign = ContentAlignment.TopLeft;
        checkBox.CheckAlign = ContentAlignment.TopLeft;
        checkBox.ImageAlign = ContentAlignment.TopLeft;
        ControlPanel.Controls.Add(checkBox);
    }

    public void AddNumericUpDown(string name, double initialValue, int decimalPlaces, decimal increment, decimal minimum, decimal maximum)
    {
        NumericUpDown numericUpDown = new NumericUpDown();
        numericUpDown.DecimalPlaces = decimalPlaces;
        numericUpDown.Increment = increment;
        numericUpDown.Minimum = minimum;
        numericUpDown.Maximum = maximum;
        numericUpDown.Value = (decimal)initialValue;
        numericUpDown.Name = name;
        numericUpDown.Visible = true;
        numericUpDown.Margin = new Padding(2);
        numericUpDown.Top = 0;
        numericUpDown.Width = 80;
        ControlPanel.Controls.Add(LabelWithText(name, 70));
        ControlPanel.Controls.Add(numericUpDown);
    }
}
</code>
Answer: It's not the tops that are supposed to align.  The baseline of the text is what's supposed to align between various controls.  This is more evident if you use a larger font.
Comment: If i use all the defaults (i.e don't set any alignments). I still get Checkbox text and tickbox sitting low...
Comment: I have to use: checkBox.Margin = new Padding(0,1,0,0);
Comment: I hear what you're saying about the difference in alignment.  It's challenging because you're trying to do it programmatically.  I wonder if there's a way to make use of [SnapLines](https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/walkthrough-arranging-controls-on-windows-forms-using-snaplines) when adding controls programmatically.


What is the square root of negative one raised to the power of square root of negative one?

Question: What is $\sqrt{-1}^\sqrt{-1}$?
Comment: Do you know about branch cuts, in particular of the complex logarithm?
Answer: $i^i=e^{i\log(i)}=e^{i(\log|1|+i\frac{\pi}{2})}=e^{-\pi/2}$
Comment: (I used the principal branch)
Comment: If we read the question carefully, the OP seems to have asked what is $\;\sqrt{i^i}\;$ ...
Comment: It actually says the square root of negative one raised to the power of square root of negative one, which could either mean $i^i$ or $\sqrt{(-1)^\sqrt{-1}}$.


Why is the Firebase iOS SDK CocoaPod over 70 MB?

Question: After running pod install for the Firebase iOS CocoaPod, I noticed that the Firebase pod is over 70MB. Why is this and is there any way to mitigate this?
Comment: By the way, you can see its size in [its CocoaPods page](https://cocoapods.org/?q=firebase).
Comment: This is an interesting question that I wanted to test. I created a brand new swift project in Xcode, walked through the steps to install Firebase via cocoapods and created a quick test app to ensure everything was installed (write to firebase, read from firebase) The entire project; headers, firebase, support files etc is 5.1Mb for 66 files.
Answer: The main Firebase pod is so big as it contains all the parts for every part of Firebase. One of the solutions I've had is to only use the parts needed, rather than just
pod Firebase

you can have
pod 'Firebase/Core'
pod 'Firebase/Storage'
pod 'Firebase/Database'
pod 'Firebase/RemoteConfig'


grouping DateTime by week of the day

Question: I suppose, it should be easy question for experienced guys. I want to group records by week' day and to have number of records at particular week-day.
Here is my DataFrame rent_week.info():
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1689 entries, 3 to 1832
Data columns (total 11 columns):
 #   Column        Non-Null Count  Dtype
---  ------        --------------  -----
 0   id            1689 non-null   int64
 1   createdAt     1689 non-null   datetime64[ns]
 2   updatedAt     1689 non-null   datetime64[ns]
 3   endAt         1689 non-null   datetime64[ns]
 4   timeoutAt     1689 non-null   datetime64[ns]
 5   powerBankId   1689 non-null   int64
 6   station_id    1689 non-null   int64
 7   endPlaceId    1686 non-null   float64
 8   endStatus     1689 non-null   object
 9   userId        1689 non-null   int64
 10  station_name  1689 non-null   object
dtypes: datetime64[ns](4), float64(1), int64(4), object(2)
memory usage: 158.3+ KB

Data in 'createdAt' columns looks like "2020-07-19T18:00:27.190010000"
I am trying to add new column:
rent_week['a_day'] = rent_week['createdAt'].strftime('%A')

and receive error back: AttributeError: 'Series' object has no attribute 'strftime'.
Meanwhile, if I write:
a_day = datetime.today()
print(a_day.strftime('%A'))

it shows expected result. In my understanding, a_day and rent_week['a_day'] have similar type datetime.
Even request through:
rent_week['a_day'] = pd.to_datetime(rent_week['createdAt']).strftime('%A')

shows me the same error: no strftime attribute.
I even didn't start grouping my data. What I am expecting in result is a DataFrame with information like:
 a_day       number_of_records
Monday       101
Tuesday      55
...

Answer: Try a_day.dt.strftime('%A') - note the additional .dt on your DataFrame column/Series object.
Background: the "similar" type assumption you make is almost correct. However, as a column could be of many types (numeric, string, datetime, geographic, ...), the methods of the underlying values are typically stored in a namespace to not clutter the already broad API (method count) of the Series type itself. That's why string functions are available only through .str, and datetime functions only available through .dt.
Comment: Thank you, @ojdo for explanation!
Answer: You can make a lambda function for conversion and apply that function to the column of "createdAt" Columns. After this step you can groupby based on your requirement. You can take help from this code:
rent_week['a_day'] = rent_week['createdAt'].apply(lambda x: x.strftime('%A'))

Comment: Thank you, @Qamar Abbas Looks like my problem was in wrong index
Answer: Thank you Quamar and Ojdo for your contribution. I found the problem: it is in index
<ipython-input-41-a42a82727cdd>:8: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  rent_week['a_day'] = rent_week['createdAt'].dt.strftime('%A')

as soon as I reset index
rent_week.reset_index()

both variants are working as expected!

grouping DateTime by week of the day


Namespace in DataContract WCF

Question: I'm working on a WCF service in VB. I was asked my DTOs are in différentas namespaces. Here's an example with two classes:
First class:
Namespace DTO
  Namespace SaveContext

      <DataContract(Namespace:="MyProject/DTO", Name:="Reply")> _
      Public Class Reply

         'Members and methods of my first class

      End Class

  End Namespace
End Namespace

Second Class:
Namespace DTO
  Namespace ClearContext

      <DataContract(Namespace:="MyProject/DTO", Name:="Reply")> _
      Public Class Reply

         'Members and methods of my second class

      End Class

  End Namespace
End Namespace

When I come to create an object, everything is fine. Here's an example:
Dim saveReply As New DTO.SaveContext.Reply
Dim clearReply As New DTO.ClearContext.Reply

But when I come to do a test project to test my service, no namespace does not appear, and put my two classes are the same. The Intellisence going to my first class with the name Reply, and the second class with the name Reply1, while I wanted the same hierarchy with my classes. So I wonder if it is possible to do? I look forward to your responses. Thank you in advance for your attention.
Answer: WCF is resolving a class "naming collision" for you automatically. You are defining two separate C# classes into the same XML namespace so the WCF WSDL generator is correctly marking them as separate XML schemas. The behavior you are seeing is as Microsoft likes to say "by design". Maybe what you actually need to do is use inheritance and KnownTypes for your scenario.

Namespace in DataContract WCF


Adding a table with items and prices to a drupal site

Question: I am not sure how to ask this question, but I hope I will be making myself clear.
We are building a CMS-like site for the most part, but the customer also wants the capability of adding a prices table for goods that can be consumed by a user on a daily basis.
So far, there is a custom content type 'user daily report' whose purpose is to store info of the likes of:
user1 - 2015/05/01 - 1 breakfast - 1 lunch - 3 drinks
At the end of the month, I have to be able to provide a report which summarizes how much the user has to be charged for his/her accumulated consumption.
I'm not sure how to exactly phrase my question here, since I'm fairly new to Drupal. Therefor I'll try to describe my requirement / question using some language I'm more familiar with:

Have Drupal create a products table, a prices table (foreign key-ed to the products table), and add a couple fields to the daily report content type (product_id, amount).
In order to create the monthly report, I think I would just use a grouping SQL query (with group by and sum).

The above is not very 'drupalish'. But at the same time, I fail to see how the products and prices tables could be implemented using content types.
To make the question more precise, it is actually a 2 parts question, being:
1) I am not sure that putting the products and prices info inside of Drupal is best achieved by using custom content types. What is the best way to go for you people when faced to this type of functionality?
2) What is the best way of extracting/summarizing the info at the end of the month? I have struggled my way using the views module, but being myself much of an 'old school programmer' I am not necessarily confident that all I need can be achieved by using 'views'.
With all that in mind, my question is: what's the best approach to achieve this goal in a way that integrates well with 'the Drupal way'?
Any hint on the topic is most welcome!
Thanks In Advance!
PS. I've tried the entity-references + views_calc way with a wee prototype.
In general, I feel satisfied with the tests I've carried out.
What we need to be able to implement is several tables of products/prices available to different sets of users. All of it based on organic groups (we are using an openatrium distribution).
Using an entity-reference as a field in the users content type, and then adding the necessary relationship when using the views module, I can get what I need. Plus with the Views Calc module I get the summarized stuff.
I still have to try it all in our fully fledged openatrium dev install and see what happens when associating products/prices to groups. But so far, seems promising.
I've learned that my original version of the question didn't fit the questions policy because it was too loose and prone to answers based in personal opinion vs facts (and sorry about that). Maybe the edited version will prevent it from getting closed?
I'll choose Pierre's answer as right, as it has certainly been helpful.
Comment: _but being myself much of an 'old school programmer' I am not necessarily confident that all I need can be achieved by using 'views'._ I used to think the same thing, shunned Views for years. It was a stupid decision, you get _so_ much just done for you. If you're using Drupal entities (nodes, users, taxonomy, etc), you should almost certainly be using Views to gather your data. Might mean you need to read up on how it work internally so you can make whatever small manipulations you need to, but broad-strokes, you're likely re-inventing the wheel if you don't use Views
Comment: Thanks a lot, Clive; that's exactly what I feel: if a go and create a module that takes care of the non-entities new tables, I'll be somehow missing the point of using drupal altogether... I've fought my way with views, but still nowhere near comfortable with them, I'm afraid.... Thanks kiamlaluno; I know. I didn't even know how to start the question. I'll try to create a small functioning prototype following Pierre's directions and tell you all how it goes
Comment: This question is too broad and subjective: We cannot tell you the _best_ way to do something.
Answer: Your question consists of 2 questions ... I'll use the same numbers to answer them.
1. Alternatives to using Custom Content types
a) Use Drupal Entities (Option 1)
Use the Entity Construction Kit (ECK) module to create 'entities' (= fieldable things ...) like Products and Prices. For each of those entities use "fields" for each of the columns you mentioned. Should you run into fields such as dates, you would have to add modules such as date also.
For the "foreign keys" use the Entity reference module (possibly some related modules of it also, extending its functionality, as mentioned on the ECK project page) and/or the References module (cfr. 'node_reference' and 'user_reference' as contained in CCK for D6).
Maybe modules like Display Suite or Panels could help to enhance the look and feel of it all also?
b) Use custom tables and/or an external database (Option 2)
Custom tables are tables you create yourself, in the same Drupal database. External Databases are databases that are different from the Drupal database, which are typically in formats such as Oracle, PostGress, MS Sql, MySQL, SQLite, some PDO compliant DBMS.
Using this alternative, you can use the Forena module for reporting about the data from within a Drupal site (as further explaining within "reporting" below also). To perform updates (delets, inserts, etc), you'd use your own tools that you'd prefer for the DBMS of your choice. Same for creating the tables, etc.
2. Reporting
Consider using modules such as (either one, or both, depending on your requirements):

Views, combined with Views Calc also probably. Have a look at How to calculate the sum for each option of all webform results in a Drupal webform grid? to get an idea of using Views Calc.

Maybe you want to consider the Forena module as a supplement / alternative. E.g. if you'd need to also create charts or so, or if you have a need to access data in some external database such as MS SQL, Oracle, etc. Here is a quote about it:

... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Disclosure: I'm a (co-)maintainer of some of the modules mentioned,
I hope this does not violate the site's policy on self-promotion.
Comment: I have been using the views module, I don't know the Forena module. I guess that the problem lies less in the view that extracts the info, but rather in how to set the products/prices info inside of the Drupal app. I somehow don't feel that the best approach would be to create 2 news custom content types; and am not sure how to stablish relationships between the 'daily report' and 'products' tables.
Comment: Merci Pierre for your help so far, I'll be taking a look at all of it. We are already using panels, views, entity reference and panels. I had already been pointed to views_calc. I guess that all boils down to how to store the products and prices 'tables' inside of Drupal.
Comment: Pierre, as explained in my last edit to the question, I'll try in deep the modules you pointed me to. Thanks!
Comment: Thanks for the edit, but know that there is no reason to include that "edit" itself (just create a revised version of your question) ... Add another comment whenever you're finished looking at these things, eg if you've other comments, etc.
Comment: Based on your last comment, I further refined my answer related to "how to store those tables". note: consider also including that comment in your further edited question ...