text:
Q: Clean Code: Functions with few parameters I read the first chapters of Clean Code by Robert C. Martin, and it seems to me it's pretty good, but I have a doubt, in one part it is mentioned that it is good (cognitively) that the functions should have as few parameters as possible, it even suggests that 3 or more parameters is too much for a function (which I find very exaggerated and idealistic), so I started to wonder...
Both the practices of using global variables and passing many arguments on the functions would be bad programming practices, but the use of global variables can greatly reduce the number of parameters in the functions...
So I wanted to hear what you think about it, is it worth using global variables to reduce the number of parameters of the functions or not? In what cases would it be?
What I think is that it depends on several factors:

*

*Source code size.

*Number of parameters in average of the functions.

*Number of functions.

*Frequency in which the same variables are used.

In my opinion if the source code size is relatively small (like less than 600 lines of code), there are many functions, the same variables are passed as parameters and the functions have many parameters, then using global variables would be worth, but I would like to know...

*

*Do you share my opinion?

*What do you think of other cases where the source code is bigger, etc.?

P.S. I saw this post, the titles are very similar, but he doesn't ask what I want to know.

A:
is it worth using global variables to reduce the number of parameters of the functions or not?

Not

I read the first chapters of this book

Did you read the rest of the book?
A global is just a hidden parameter. They cause a different pain. But it's still pain. Stop thinking of ways to get around this rule. Think about how to follow it.
What is a parameter?
It's stuff. In a nicely labeled box. Why does it matter how many boxes you have when you can put whatever stuff in it?
It's the cost of shipping and handling.
Move(1, 2, 3, 4)

Tell me you can read that.  Go on, try.
Move(PointA, PointB)

That's why.
That trick is called introduce parameter object.
And yes it's just a trick if all you're doing is counting parameters. What you should be counting is IDEAS! Abstractions! How much are you making me think about at once? Keep it simple.
Now this is the same count:
Move(xyx, y)

OW! That's horrible! What went wrong here?
It's not enough to limit the number of ideas. They must be clear ideas. What the heck is a xyx?
Now this is still weak. What's a more powerful way to think about this?

Functions should be small. No smaller than that.
Uncle Bob

Move(PointB)

Why make the function do any more than it really needs to do? The single responsibility principle isn't only for classes. Seriously, it's worth changing an entire architecture just to stop one function from turning into an overloaded nightmare with 10 sometimes related parameters some of which can't be used with others.
I've seen code where the most common number of lines in a function was 1.  Seriously. I'm not saying you have to write that way but sheesh, don't tell me a global is the ONLY way you can comply with this rule.  Stop trying to get out of refactoring that function properly. You know you can. It might break down into a few functions. It might actually turn into a few objects. Hell you might even break part of it out into an entirely different application.
The book isn't telling you to count your parameters.  It's telling you to pay attention to the pain you're causing. Anything that fixes the pain fixes the problem.  Just be aware when you're simply trading one pain for another.

A: You should avoid global variables like the plague.
I wouldn't put a hard limit to number of arguments (like 3 or 4), but you do want to keep them to a minimum, if possible.
Use structs (or objects in C++) to group together variables into a single entity and pass that (by reference) to functions.  Usually a function gets a structure or object (with a few different things in it) passed to it along with a couple of other parameters that tell the function to do something to the struct.
For good-smelling, clean, modular code, try to stick to the single responsibility principle. Do that with your structs (or objects), the functions, and the source files. If you do that, the natural number of parameters passed to a function will be obvious.

A: We're talking about cognitive load, not syntax. So the question is... What is a parameter in this context?
A parameter is a value which affects the behaviour of the function. The more parameters, the more possible combinations of values you get, the harder reasoning about the function gets.
In that sense, global variables that the function uses are parameters. They're parameters that don't appear in its signature, that have order-of-construction, access control and remanence issues.
Unless said parameter is what is called a cross-cutting concern, that is some program-wide state which everything uses but nothing alters (e.g. a logging object), you should not replace function parameters with global variables. They'd still be parameters, but nastier.

A: I would never use global variables to reduce parameters. The reason is that global variables can be altered by any function/command, therefore making the function input unreliable and prone to values that are out of scope of what the function can handle. What if the variable was changed during the execution of the function and half the function had different values than the other half?
Passing parameters on the other hand, restricts the variable's scope to only its own function such that only the function can modify a parameter once its called.
If you need to pass global variables instead of a parameter, its preferable to redesign the code.
Just my two cents.

A: Having many parameters is considered undesirable, but turning them into fields or global variables is a lot worse because it doesn't solve the actual problem but introduce new problems.
Having many parameters is not in itself the problem, but it is an symptom that you might have a problem. Consider this method:
Graphics.PaintRectangle(left, top, length, height, red, green, blue, transparency);

Having 7 parameters is a definite warning sign. The underling problem is these parameters are not independent but belongs in groups. left and top belong together as a Position-structure, length and height as a Size structure, and red, blue and green as a Color structure. And maybe Color and transparency belongs in a Brush structure? Perhaps Position and Size belongs together in a Rectangle structure, in which case we may even consider turning it into a Paint method on the Rectangle object instead? So we may end up with:
Rectangle.Paint(brush);

Mission accomplished! But the important thing is we actually have improved the overall design, and the reduction in number of parameters is a consequence of this. If we just reduce the number of parameter without tackling the underlying issues, we might do something like this:
Graphics.left = something;
Graphics.top = something;
Graphics.length = something;
...etc
Graphics.PaintRectangle();

Here we have achieved the same reduction in number of parameter, but we have actually made the design worse.
Bottom line: For any programming advice and rules-of-thumb it is really important to understand the underlying reasoning.

A: IMHO your question is based on a misunderstanding. In "Clean Code", Bob Martin does not suggest to replace repeated function parameters by globals, that would  be a really awful advice. He suggest to replace them by by private member variables of the class of the function. And he also proposes small, cohesive classes (typically smaller than the 600 lines of code you mentioned), so these member variables are definitely no globals.
So when you have the opinion in a context with less than 600 lines "using global variables would be worth it", then you perfectly share the opinion of Uncle Bob. Of course, it is debatable if "3 parameters at maximum" is the ideal number, and if this rule sometimes leads to too many member variables even in small classes. IMHO this is a trade-off, there is no hard-and-fast rule where to draw the line.

A: I'm with Uncle Bob on this and agree that more than 3 params is something to be avoided (I very rarely use more than 3 params in a function).  Having lots of params on a single function creates a bigger maintenance problem and is probably a smell that your function is doing too much/has too many responsibilities.
If you are using more than 3 in a method in a OO language then you should consider are the params not related to each other in some way and therefore you should really be passing in an object instead?
Also, if you create more (smaller) functions you'll also notice that functions tend to more often have 3 params or less.  Extract function/method is your friend :-).
Do not use global variables as a way to get round having more params!  That is swapping one bad practice for an even worse one!

A: I don't share your opinion. In my opinion using global variables is a worse practice than more parameters irrespective of the qualities you described. My reasoning is that more parameters may make a method more difficult to understand, but global variables can cause many problems for the code including poor testability, concurrency bugs, and tight coupling. No matter how many parameters a function has, it won't inherently have the same problems as global variables.

...the same variables are passed as parameters

It may be a design smell. If you have the same parameters being passed to most functions in your system, there may be a cross-cutting concern that should be handled by introducing a new component. I don't think passing the same variable to many functions to be sound reasoning to introduce global variables.
In one edit of your question you indicated that introducing global variables might improve the readability of code. I disagree. Usage of global variables is hidden in the implementation code whereas function parameters are declared in the signature. Functions should ideally be pure. They should only operate on their parameters and should not have any side-effects. If you have a pure function, you can reason about the function by looking just at one function. If your function is not pure, you must consider the state of other components, and it becomes much more difficult to reason about.

A: Using global variables always seems an easy way to code (especially in a small program), but it will make your code difficult to extend.
Yes, you can reduce the number of parameters in a function by using an array to bind the parameters in one entity.
function <functionname>(var1,var2,var3,var4.....var(n)){}

The above function will be edited and changed to [using associative array]-
data=array(var1->var1,
           var2->var2
           var3->var3..
           .....
           ); // data is an associative array

function <functionname>(data)

I agree with robert bristow-johnson's answer: you can even use a struct to bind data in a single entity.

A: A valid alternative to many function parameters is to introduce a parameter object. This is useful if you have a composed method which passes (almost) all of its parameters to a bunch of other methods.
In simple cases this is a simple DTO having nothing but the old parameters as properties.

A: Taking an example from PHP 4, look at the function signature for mktime():

*

*int mktime ([ int $hour = date("H") [, int $minute = date("i") [, int $second = date("s") [, int $month = date("n") [, int $day = date("j") [, int $year = date("Y") [, int $is_dst = -1 ]]]]]]] )
Don't you find that confusing? The function is called "make time" but it takes day, month and year parameters as well as three time parameters. How easy is it to remember which order they go in? What if you see mktime(1, 2, 3, 4, 5, 2246);? Can you understand that without having to refer to anything else? Is 2246 interpreted as a 24-hour time "22:46"? What do the other parameters mean?
It would be better as an object.
Moving to PHP 5, there now is a DateTime object. Amongst its methods are two called setDate() and setTime(). Their signatures are as follows:

*

*public DateTime setDate ( int $year , int $month , int $day )

*public DateTime setTime ( int $hour , int $minute [, int $second = 0 ] )
You still have to remember that the order of the parameters goes from greatest to smallest, but it's a big improvement. Note that there isn't a single method that allows you to set all six parameters at once. You have to make two separate calls to do this.
What Uncle Bob is talking about is avoiding having a flat structure. Related parameters should be grouped together into an object, and if you have more than three parameters, it's very likely you've got a pseudo object there, which gives you the opportunity of creating an appropriate object for greater separation. Although PHP doesn't have a separate Date and Time class, you  could consider that DateTime really contains a Date object and a Time object.
You could possibly have the following structure:
<?php
$my_date = new Date;
$my_date->setDay(5);
$my_date->setMonth(4);
$my_date->setYear(2246);

$my_time = new Time;
$my_time->setHour(1);
$my_time->setMinute(2);
$my_time->setSecond(3);

$my_date_time = new DateTime;
$my_date_time->setTime($my_time);
$my_date_time->setDate($my_date);
?>

Is it mandatory to set two or three parameters each time? If you want to change just the hour or just the day, it's now easy to do so. Yes, the object needs to be validated to make sure each parameter works with the others, but that was the case before anyway.
The most important thing is, is it easier to understand, and therefore maintain? The code block at the bottom is bigger than a single mktime() function, but I'd argue that's much easier to understand; even a non-programmer wouldn't have much trouble working out what it does. The goal is not always shorter code or cleverer code, but more maintainable code.
Oh, and don't use globals!

A: Lots of good answers here yet most are not addressing the point. Why these rules of thumb? It is about scope, it is about dependencies and it is about proper modelling.
Globals for arguments is worse because it only looks like you made it simpler but in fact you only hid the complexity. You don't see it anymore in the prototype but you still have to be aware of it (which is hard since it is not there for you to see anymore) and getting your head around the function's logic won't help you because there may be other hidden logic interfering behind your back. Your scope went all over the place and you introduced a dependency on whatever because whatever can now mess with your variable. Not good.
The main thing to maintain for a function is that you can understand what it does by looking at the prototype and call. So the name should be clear and unambiguous. But also, the more arguments there are the harder it will be to grasp what it does. It widens the scope in your head, too many things going on, this is why you want to limit the number. It matters what kind of arguments you are dealing with though, some are worse than others. An extra optional boolean that allows for case insensitive processing does not nake the function any harder to understand so you would not want to make a big deal about it. As a side note, enums make better arguments than booleans because an enum's meaning is obvious in the call.
The typical trouble is not that you write a new function with an enormous amount of arguments, you will start with only a few when you do not realize yet how complex the problem you are solving really is. As your program evolves, argument lists gradually tend to get longer. Once a model has set in your mind you want to keep it because it is a safe reference that you know. But in retrospect the model may not be that great. You missed a step or too in the logic and you failed to recognize an entity or two. "OK... I could start over and spend a day or two refactoring my code or... I could add this argument so I can make it do the right thing after all and be done with it. For now. For this scenario. To get this bug off my plate so I can move the sticky note to done."
The more often you go with the second solution the more expensive further maintenance is going to be and the harder and unattractive a refactor will become.
There is no boiler plate solution for reducing the number of arguments in an existing function. Just grouping them into compounds is not really making things easier, it is just another way of wiping complexity under the carpet. Doing it right involves looking at the entire call stack again and recognizing what is missing or has been done wrong.

A: Several times I have found that grouping a lot of parameters that were sent together improved things.

*

*It forces you to give a good name to this agrupation of
concepts that are used together. If you use those parameters together it could be that they have a relationship (or that you should not use together at all).

*Once with the object I usually find that some funtionality can be moved that this apparently stuypid object. It is usually easy to test and with great cohesion and low coupling making thing even better.

*The next time I need to add a new parameter I have a nice place to include it without changing the signature of a lot of methods.
So it may not work 100% of the times but ask yourself if this list of parameter should be grouped in an object. And please. Do not use untyped classes like Tuple to avoid creating the object. You are using object-oriented programming, do not mind to create more objects if you need them.

A: With all due respect, I'm pretty sure you've completely missed the point of having a small number of parameters in a function.
The idea is that the brain can only hold so much "active information" at one time, and if you have n parameters in a function, you have n more pieces of "active information" that needs to be in your brain to easily and accurately comprehend what the piece of code is doing (Steve McConnell, in Code Complete (a much better book, IMO), says something similar about 7 variables in a method's body: rarely do we reach that, but any more and you're losing the ability keep everything straight in your head).
The point of a low number of variables is to be able to keep the cognitive requirements of working with this code small, so you can work at it (or read it) more effectively.  A side cause of this is that well factored code will tend to have less and less parameters (e.g., poorly factored code tends to group a bunch of stuff into a mess).
By passing objects instead of values, perhaps you gain a level of abstraction for your brain because now it needs to realize yes, I've got a SearchContext to work with here instead of thinking about the 15 properties that might be within that search context.
By attempting to use Global variables, you've completely gone in the entire wrong direction.  Now not only have you not solved the problems of having too many parameters for a function, you've taken that problem and thrown it in a much, much better problem that you now have to carry around in your mind!
Now instead of working just at the function level, you need to be considering the global scope of your project as well (gawd, how terrible! I shudder...).  You don't even have all your information in front of you in the function (crap, what's that global variable name?) (I hope this hasn't been changed by something else since I called this function).
Globally scoped variables are one of the very worst things to see in a project (large or small).  They denote a disability for proper scope management, which is a highly fundamental skill for programming.  They. Are. Evil.
By moving parameters out of your function and putting them into globals, you've shot yourself in the foor (or the leg, or face).  And God forbid you ever decide that hey, I can re-use this global for something else... my mind trembles at the thought.
The whole ideal is to keep things easy to manage, and global variables are NOT going to do that.  I'd go so far as to say they're one of the worst things you can do to go in the opposite direction.

A: I've found a highly effective approach (in JavaScript) to minimize friction between interfaces:
Use a uniform interface for all modules, specifically: single param functions.
When you need multiple parameters: Use a single Object/Hash or Array.
Bear with me, I promise I'm not trolling...
Before you say "what good is a single param func?" or "Is there a difference between 1 Array and multi arg funcs?"
Well, yes. It's perhaps visually subtle, but the difference is manyfold – I explore the many benefits here
Apparently some ppl think 3 is the right # of arguments. Some think it's 2. Well, that still begs the question, "which param goes in arg[0]?" Instead of picking the option which constrains the interface with a more rigid declaration.
I guess I argue for a more radical position: don't rely on positional arguments. I just feel it's fragile and leads to arguments about the position of the damn arguments.
Skip it and move right along to the inevitable fighting about the names of functions and variables.
Seriously though, after naming settles, hopefully you end up with code like follows, which is somewhat self documenting, not position-sensitive, and allows future param changes to be handled inside to the function:
function sendMessage({toUser, fromUser, subject, body}) { }

// And call the method like so:
sendMessage({toUser: this.parentUser, fromUser: this.currentUser, subject: 'Example Alert'})


text:
Q: Lots of pointer casts in QGraphicsView framework and performance Since most of the convenience functions of QGraphicsScene and QGraphicsItem (such as items(), collidingItems(), childItems() etc.) return a QList you're forced to do lots of qgraphicsitem_cast or static_cast and QGraphicsItem::Type() checks to get hold of the actual items when you have lots of different type of items in the scene. I thought doing lots of subclass casts were not a desirable coding style, but I guess in this case there are no other viable way, or is there?
QList<QGraphicsItem *> itemsHit = someItem->collidingItems(Qt::IntersectsItemShape);
foreach (QGraphicsItem *item, itemsHit) {
    if (item->type() == QGraphicsEllipseItem::type()) {
        QGraphicsEllipseItem *ellipse = qgraphicsitem_cast<QGraphicsEllipseItem *>(item);
        // do something
    }
    else if (item->type() == MyItemSubclass::type()) {
        MyItemSubClass *myItem = qgraphicsitem_cast<MyItemSubClass *>(item);
        // do something
    }
    // etc
}

The above qgraphicsitem_cast could be replaced by static_cast since correct type is already verified. When doing lots of these all the time (very dynamic scene), will the numerous casting affect performance beyond the normal if-else evaluation?

A: The performance overhead is mostly prepaid; it's the result of the overhead of having the .type() member. It might be efficient to retrieve the item->type() once. You know it doesn't change, but chances are the compiler doesn't.
[edit]
Also, if you really have a lot of types, it could be worthwhile to introduce some intermediate types. eg. if (dynamic_cast<MyGraphicsInterMediateType*>(item)) {/* check those types */} else {/* other types */}

redpajama_set_name: RedPajamaStackExchange


text:
Q: jersey testframework with gradle - MessageBodyProviderNotFound I have a bit a difficult situation. I am using jersey to provide REST services.
In my runtime I do this with version: 1.16.0:
restClasspath(
'org.codehaus.jackson:jackson-core-asl:1.9.2',
'org.codehaus.jackson:jackson-mapper-asl:1.9.2',
'com.sun.jersey:jersey-core:1.16.0',
'com.sun.jersey:jersey-server:1.16.0',
)

This is my resource class:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import ....model.DecisionTree;
import ...model.TestDataProvider;

@Path("new_rest")
public class NewPublicAPIRestResource {

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @Path("ppp/{param}")
  public Response getHello(@PathParam("param") String treeName) {
      DecisionTree tree = TestDataProvider.createDecisionTree();
      return Response.ok(tree).build();
  }
}

This works and I get a json response as expected.
Now I found about jersey-testframework which provides an in memory server for integration tests.
Unfortunately this only seems to work with jersey 2.x, so I added an extra gradle setting for my tests:
testClasspath(
'org.glassfish.jersey.core:jersey-common:2.7',
'org.glassfish.jersey.core:jersey-server:2.7',
'org.glassfish.jersey.core:jersey-client:2.7',
'org.glassfish.hk2:hk2:2.2.0',
'org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-inmemory:2.7',
 )

And this is my test class:
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import ...resource.NewPublicAPIRestResource;

public class ConditionNodeTest extends JerseyTest{

    @Override
    protected Application configure() {
        return new ResourceConfig(NewPublicAPIRestResource.class);
    }

    @Test
    public void test() {
        System.out.println(target("new_rest/ppp/param").request().get(String.class));
    }
}

This setup does work, as long as my resource returns String. However, as soon as I return a Response, as shown in my code here, I get this error:
javax.ws.rs.ProcessingException: Server-side request processing failed with an error.
    ...
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:424)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:667)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:396)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:296)
    at ....model.ConditionNodeTest.test(ConditionNodeTest.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    ...
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    ...
Caused by: org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json, type=class ....model.DecisionTree, genericType=class ....model.DecisionTree.
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:247)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
    at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:103)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
    at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:88)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
    at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1154)
    at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:571)
    at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:378)
    at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:368)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:262)
    ... 44 more

From what I can tell I am missing some provider that parses my classes into json, but I just cannot figure out which one. I tried adding a few libs to my classpath like:
'org.glassfish.jersey.media:jersey-media-jaxb:2.16'
'org.glassfish.jersey.media:jersey-media-json-jackson:2.7

and several others I cannot remember, but did not get it working.
Any ideas what I am missing here?
Thanks,
Sven

A: This is correct
'org.glassfish.jersey.media:jersey-media-json-jackson:2.7'

But up until Jersey 2.9, we still need to register the JacksonFeature with the application (as mentioned here). So just do
@Override
protected Application configure() {
    return new ResourceConfig(NewPublicAPIRestResource.class)
            .register(JacksonFeature.class);
}

Oh and BTW, Jersey 1.x also has the Jersey Test Framework. It's just the API is a little different, but it still functions the same. See example here and here, and here is in-memory provider. But anyway, I recommend sticking with Jersey 2.x.


text:
Q: Apply Array.map with Dictionary How would I write the following code correctly in Swift 4.2:
let navStack = ["root", "page1", "page3"]
let route = ["root", "page1", "page2", "page3"]
let routeTags =
[
    "root": ["root"],
    "page1": ["page1", "page2"],
    "page3": ["page3"]
]
let r = navStack.map({ routeTags[$0] }).joined(separator: "/")

The current code doesn't compile (ambiguous reference to member 'subscript'). The code should produce a string with the dictionary values mapped according to the keys in navStack.

A: Two issues:

*

*The result of routeTags[$0] is an optional and must be unwrapped (safely with compactMap).

*The joined expression must be moved into the closure because the second item is an array.

let navStack = ["root", "page1", "page3"]
let route = ["root", "page1", "page2", "page3"]
let routeTags =
    [
        "root": ["root"],
        "page1": ["page1", "page2"],
        "page3": ["page3"]
]
let r = navStack.compactMap{ routeTags[$0]?.joined(separator: "/") }

Or you have to use joined twice if you want one single string:
let r = navStack.compactMap{ routeTags[$0]?.joined(separator: "/") }.joined(separator: "/")


text:
Q: A strange HTML display issue when mix use Arabian character (right to left) with normal English character Here's JsFiddle I created to demonstrate the problem.
The output of following code seems to be wrong

        Exchange Rate : 1 AED(د.إ) = 1.0 EUR(€)

while display can be correct if I change it to 2 lines.

        Exchange Rate : 1 AED(د.إ)

         = 1.0 EUR(€)

Hope some nice guy can figure out this strange problem. Even appreciate more if there are some background knowledge you can share to us.

A: well it is problem with rtl languages and rtl languages

    Exchange Rate : 1 USD($)
     = 1.0 EUR(€)

Exchange Rate : 1 AED
(د.إ)
  = 1.0 EUR(€)

try to fix by putting another language in separate element give it direction:rtl; and in this case i gave display:inline-block;


text:
Q: Should I flag a low quality answer for deletion when reviewing? As I stated on this other question, I don't like the way the "Recommend Deletion" works on the new review system, essentially because it doesn't let me know the final outcome of my recommendation.
However, I frequently see answers such as this one on the review queue, and they're very similar to what I see on the 10k flag queue. Is it okay to also flag those posts instead of just recommending deletion, or would I be overloading the moderators for no reason?

A: For answers like that one you should use the available option from the "Recommend Deletion" popup:


text:
Q: How to get useNavigate to push only if the new URI is different from the current? There is a button on my App that calls useNavigate to change the URI location. I notice that it pushes the URI when pressed repeatedly.
How to get it to only push if the new URI is different from the current URI?
const navigate = useNavigate();
<div onClick={() => navigate("/home")}>
  Button
</div>

The problem with the code above is that each time the div is clicked, /home is pushed to the URI history stack even if the current location is /home. So that if the user press the back button it would seem to have no effect.

A: Check the target path against the current location.pathname and only issue the imperative navigation if not already on the same path.
Example:
import { useLocation, useNavigate } from "react-router-dom";

...

const { pathname } = useLocation();
const navigate = useNavigate();

<button
  onClick={() => {
    if (pathname !== "/home") {
      navigate("/home");
    } else {
      console.log("Already Home");
    }
  }}
>
  Go Home
</button>


text:
Q: How to fix an au.com.bytecode.opencsv.CSVReader I have as an import the au.com.bytecode.opencsv.CSVReader. Eclipse says that

the import cannot be resolved

at: CSVReader reader = new CSVReader

CSVReader cannot be resolved to a type

How to correct it? It is the only red marker of my code.


text:
Q: nginx to always serve the root index.html in every path I have currently the code below. I am wondering if it's possible to still service this root even though I go to other pages like http://localhost/dog. The problem with my command below is it will return 404
server {
    listen 80;
    server_name         localhost;

    location / {
        root /usr/src/app/angularjs/dist;
    }
}

A: It is possible. Add the try_files directive to your location block, this will tell nginx to load all requests that cannot be matched to a filesystem path with your index.html:
try_files $uri /index.html;


text:
Q: GCP Dataproc - configure YARN fair scheduler I was trying to set up a dataproc cluster that would compute only one job (or specified max jobs) at a time and the rest would be in queue.
I have found this solution, How to configure monopolistic FIFO application queue in YARN? , but as I'm always creating a new cluster, I needed to automatize this. I have added this to cluster creation:
"softwareConfig": {
    "properties": {
        "yarn:yarn.resourcemanager.scheduler.class":"org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler",
        "yarn:yarn.scheduler.fair.user-as-default-queue":"false",
        "yarn:yarn.scheduler.fair.allocation.file":"$HADOOP_CONF_DIR/fair-scheduler.xml",
     }
}

with another line in init action script:
sudo echo "<allocations><queueMaxAppsDefault>1</queueMaxAppsDefault></allocations>" > /etc/hadoop/conf/fair-scheduler.xml

and the cluster tells me this when I fetch its config:
'softwareConfig': {
  'imageVersion': '1.2.27',
  'properties': {
    'capacity-scheduler:yarn.scheduler.capacity.root.default.ordering-policy': 'fair',
    'core:fs.gs.block.size': '134217728',
    'core:fs.gs.metadata.cache.enable': 'false',
    'distcp:mapreduce.map.java.opts': '-Xmx4096m',
    'distcp:mapreduce.map.memory.mb': '5120',
    'distcp:mapreduce.reduce.java.opts': '-Xmx4096m',
    'distcp:mapreduce.reduce.memory.mb': '5120',
    'hdfs:dfs.datanode.address': '0.0.0.0:9866',
    'hdfs:dfs.datanode.http.address': '0.0.0.0:9864',
    'hdfs:dfs.datanode.https.address': '0.0.0.0:9865',
    'hdfs:dfs.datanode.ipc.address': '0.0.0.0:9867',
    'hdfs:dfs.namenode.http-address': '0.0.0.0:9870',
    'hdfs:dfs.namenode.https-address': '0.0.0.0:9871',
    'hdfs:dfs.namenode.secondary.http-address': '0.0.0.0:9868',
    'hdfs:dfs.namenode.secondary.https-address': '0.0.0.0:9869',
    'mapred-env:HADOOP_JOB_HISTORYSERVER_HEAPSIZE': '3840',
    'mapred:mapreduce.job.maps': '189',
    'mapred:mapreduce.job.reduce.slowstart.completedmaps': '0.95',
    'mapred:mapreduce.job.reduces': '63',
    'mapred:mapreduce.map.cpu.vcores': '1',
    'mapred:mapreduce.map.java.opts': '-Xmx4096m',
    'mapred:mapreduce.map.memory.mb': '5120',
    'mapred:mapreduce.reduce.cpu.vcores': '1',
    'mapred:mapreduce.reduce.java.opts': '-Xmx4096m',
    'mapred:mapreduce.reduce.memory.mb': '5120',
    'mapred:mapreduce.task.io.sort.mb': '256',
    'mapred:yarn.app.mapreduce.am.command-opts': '-Xmx4096m',
    'mapred:yarn.app.mapreduce.am.resource.cpu-vcores': '1',
    'mapred:yarn.app.mapreduce.am.resource.mb': '5120',
    'spark-env:SPARK_DAEMON_MEMORY': '3840m',
    'spark:spark.driver.maxResultSize': '1920m',
    'spark:spark.driver.memory': '3840m',
    'spark:spark.executor.cores': '8',
    'spark:spark.executor.memory': '37237m',
    'spark:spark.yarn.am.memory': '640m',
    'yarn:yarn.nodemanager.resource.memory-mb': '81920',
    'yarn:yarn.resourcemanager.scheduler.class': 'org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler',
    'yarn:yarn.scheduler.fair.allocation.file': '$HADOOP_CONF_DIR/fair-scheduler.xml',
    'yarn:yarn.scheduler.fair.user-as-default-queue': 'false',
    'yarn:yarn.scheduler.maximum-allocation-mb': '81920',
    'yarn:yarn.scheduler.minimum-allocation-mb': '1024'
  }
},

The file fair-scheduler.xml also contains the specified code (everything is in one line, but I don't think this could be the problem)
After all this, the cluster still acts like if the capacity scheduler was in charge. No idea why. Any recommendation would help.
Thanks.

A: as init actions script is running after the cluster is created, the yarn service is already running in the time when the script modify the yarn-site.xml.
So after modifying the xml config file and creating the other xml file, the yarn service needs to be restarted.
It can be done using this command:
sudo systemctl restart hadoop-yarn-resourcemanager.service

Also, since the $HADOOP_CONF_DIR was not set (I thought it should be), its needed to input the whole path to the file. But, after that, the initial YARN service won't start, because it can't find the file that is created later in init actions script. So, what I did is to add the last few lines to yarn-site.xml in the init actions script as well.
The code for init actions script is the following:
ROLE=$(/usr/share/google/get_metadata_value attributes/dataproc-role)
if [[ "${ROLE}" == 'Master' ]]; then
    echo "<allocations>" > /etc/hadoop/conf/fair-scheduler.xml
    echo "  <queueMaxAppsDefault>1</queueMaxAppsDefault>" >> /etc/hadoop/conf/fair-scheduler.xml
    echo "</allocations>" >> /etc/hadoop/conf/fair-scheduler.xml

    sed -i '$ d' /etc/hadoop/conf/yarn-site.xml

    echo "  <property>" >> /etc/hadoop/conf/yarn-site.xml
    echo "    <name>yarn.scheduler.fair.allocation.file</name>" >> /etc/hadoop/conf/yarn-site.xml
    echo "    <value>/etc/hadoop/conf/fair-scheduler.xml</value>" >> /etc/hadoop/conf/yarn-site.xml
    echo "  </property>" >> /etc/hadoop/conf/yarn-site.xml
    echo "</configuration>" >> /etc/hadoop/conf/yarn-site.xml
    systemctl restart hadoop-yarn-resourcemanager.service
fi


text:
Q: JavaFX FXML Scalable UI Is it in any way possible to achive the same behaviour with JavaFx and Fxml, that I would get when using a ViewBox in WPF?
In WPFyou could design your UI in an, for example, 800x600 sized container. If you put this in a Viewbox, you can resize the Windows as you like, and the elements within will scale accordingly.
Seems to me like there is no such thing as a Viewbox in Fxml. Is there any other way?


text:
Q: Robots.txt - What is the proper format for a Crawl Delay for multiple user agents? Below is a sample robots.txt file to Allow multiple user agents with multiple crawl delays for each user agent. The Crawl-delay values are for illustration purposes and will be different in a real robots.txt file.
I have searched all over the web for proper answers but could not find one. There are too many mixed suggestions and I do not know which is the correct / proper method.
Questions:
(1) Can each user agent have it's own crawl-delay? (I assume yes)
(2) Where do you put the crawl-delay line for each user agent, before or after the Allow / Dissallow line?
(3) Does there have to be a blank like between each user agent group.
References:
http://www.seopt.com/2013/01/robots-text-file/
http://help.yandex.com/webmaster/?id=1113851#1113858
Essentially, I am looking to find out how the final robots.txt file should look using the values in the sample below.
Thanks in advance.
# Allow only major search spiders
User-agent: Mediapartners-Google
Disallow:
Crawl-delay: 11

User-agent: Googlebot
Disallow:
Crawl-delay: 12

User-agent: Adsbot-Google
Disallow:
Crawl-delay: 13

User-agent: Googlebot-Image
Disallow:
Crawl-delay: 14

User-agent: Googlebot-Mobile
Disallow:
Crawl-delay: 15

User-agent: MSNBot
Disallow:
Crawl-delay: 16

User-agent: bingbot
Disallow:
Crawl-delay: 17

User-agent: Slurp
Disallow:
Crawl-delay: 18

User-agent: Yahoo! Slurp
Disallow:
Crawl-delay: 19

# Block all other spiders
User-agent: *
Disallow: /

# Block Directories for all spiders
User-agent: *
Disallow: /ads/
Disallow: /cgi-bin/
Disallow: /scripts/

(4) If I want to set all of the user agents to have crawl delay of 10 seconds, would the following be correct?
# Allow only major search spiders
User-agent: *
Crawl-delay: 10

User-agent: Mediapartners-Google
Disallow:

User-agent: Googlebot
Disallow:

User-agent: Adsbot-Google
Disallow:

User-agent: Googlebot-Image
Disallow:

User-agent: Googlebot-Mobile
Disallow:

User-agent: MSNBot
Disallow:

User-agent: bingbot
Disallow:

User-agent: Slurp
Disallow:

User-agent: Yahoo! Slurp
Disallow:

# Block all other spiders
User-agent: *
Disallow: /

# Block Directories for all spiders
User-agent: *
Disallow: /ads/
Disallow: /cgi-bin/
Disallow: /scripts/

A:
(1) Can each user agent have it's own crawl-delay?

Yes. Each record, started by one or more User-agent lines, can have a Crawl-delay line. Note that Crawl-delay is not part of the original robots.txt specification. But it's no problem to include them for those parsers that understand it, as the spec defines:

Unrecognised headers are ignored.

So older robots.txt parsers will simply ignore your Crawl-delay lines.

(2) Where do you put the crawl-delay line for each user agent, before or after the Allow / Dissallow line?

Doesn't matter.

(3) Does there have to be a blank like between each user agent group.

Yes. Records have to be separated by one or more new lines. See the original spec:

The file consists of one or more records separated by one or more blank lines (terminated by CR,CR/NL, or NL).

(4) If I want to set all of the user agents to have crawl delay of 10 seconds, would the following be correct?

No. Bots look for records that match their user-agent. Only if they don't find a record, they will use the User-agent: * record. So in your example all the listed bots (like Googlebot, MSNBot, Yahoo! Slurp etc.) will have no Crawl-delay.

Also note that you can't have several records with User-agent: *:

If the value is '*', the record describes the default access policy for any robot that has not matched any of the other records. It is not allowed to have multiple such records in the "/robots.txt" file.

So parsers might look (if no other record matched) for the first record with User-agent: * and ignore the following ones. For your first example that would mean that URLs beginning with /ads/, /cgi-bin/ and /scripts/ are not blocked.
And even if you have only one record with User-agent: *, those Disallow lines are only for bots that have no other record match! As your comment # Block Directories for all spiders suggest, you want these URL paths to be blocked for all spiders, so you'd have to repeat the Disallow lines for every record.


text:
Q: Does every locally compact subset of $\mathbb {R}^n$ have a one-point compactification on $\mathbb{S}^{n}$? In my general topology course, we've briefly touched the subject of one-point compactifications (Alexandroff); we've stated that every topological space $X$ has a one-point compactification $(X^+,\varphi)$, where $X^+=X\cup\{\infty\}$ has the topology that consists of complements of closed compact sets in $X$ (in addition to open sets in $X$) and $\varphi$ is an embedding of $X$ into $X^+$. We've also stated that when $X$ is a locally compact Hausdorff space and $Y$ is a compact Hausdorff space, it's sufficient to check that $\exists b\in Y$ such that $Y\setminus\{b\}\cong X$, to see that $Y\cong X^+$.
The question may be naïve, but I'm interested in whether or not it holds that we can always embed any locally compact $A\subset\mathbb R^n$ into $\mathbb S^{n}$ in such a way that the north pole of $\mathbb S^{n}=\{(x,t)\in\mathbb R^n\times\mathbb R;\ \Vert x\rVert^2+t^2=1\}$, i.e. $N=(0, 1)$, takes the role of the compactification point $\infty$. I've considered some cases where it is possible to one-point compactify the space ($\mathbb Z$ with $\mathbb S^1$, $\mathbb Z\times(-1, 1)$, $\mathbb Z\times(-1, 1]$ with $\mathbb S^2$, tested how stereographic projections work with these, also proved any closed non-compact subset $Z\subset\mathbb R^n$ can be compactified in this way).
Then I began to consider spaces that aren't simply-connected, such as $\mathbb R^2\setminus\{(0,0)\}$, and certain non-connected spaces, such as $\mathbb R^2\setminus(\{0\}\times(-\infty,\infty))$ and quickly got stuck on how to compactify them in such a manner. I'm guessing it's because you can't, but missing what's the condition to be able to do so.

A: No. Your example of $\mathbb{R}^2 \backslash \{0\}$ is one of such cases. Its one-point compactification is homotopically equivalent to $S^2 \vee S^1$ (see here* before going on). So it suffices to argue why no space $A$ homotopically equivalent to $S^2 \vee S^1$ can be embedded in $S^2$.
One way to see this is via Alexander duality. We would need to have
$$0 \simeq\widetilde{H}_{-1}(S^n-A;\mathbb{Z}) \simeq H^{2}(A;\mathbb{Z}) \simeq \mathbb{Z},$$
a contradiction (here we are using the fact that $S^n-A$ can't be empty. Note that $\widetilde{H}_{-1}(\emptyset) \simeq \mathbb{Z},$ allowing the only case $A=S^n$  of a CW-complex with non-trivial second cohomology to be embedded in $S^n$).
*One problem with the one-point compatification is that it is rarely a manifold ($S^2 \vee S^1$ for example is not a manifold).  If you take an arbitrary open connected set of Euclidean space and one-point-compactify it, it will usually not be a manifold. If it were, we could try to attack the problem in a way simpler than what is done above in the following way: the only compact manifold of dimension $n$ which embeds in $S^n$ is $S^n$ itself; this is due to the invariance of domain theorem, which tells us that the embedding must be an open map (and the image is closed since it is the image of a compact set under a continuous map with Hausdorff codomain), hence the image must be the whole $S^n$. So it would suffice to pick an open subset of Euclidean space such that its one-point compactification is a manifold which is not $S^n$. As of now, I don't know if it is possible. I've asked this question here.


text:
Q: Unbold frontmatter chapter names in table of contents According to the thesis guidelines set out by my university, the Chapter names in the table of contents must be bold. But all sections in the prefatory sections must be normal font (unbold) in the table of contents.
How can I unbold the table of contents entries in just the frontmatter?
\documentclass{book}
\begin{document}
\frontmatter
\chapter{Abstract}
The ``Abstract'' entry (and entries for other frontmatter chapters) in the table of contents should be unbolded.
\tableofcontents
\mainmatter
\chapter{Chapter name}
But the mainmatter chapters should still be bold in TOC.
\end{document}

A: I'm not sure this is wise....
Caveat emptor....
\documentclass{book}
\begin{document}
\frontmatter
\let\bforigdefault\bfdefault
\addtocontents{toc}{\let\string\bfdefault\string\mddefault}
\chapter{Abstract}
The ``Abstract'' entry (and entries for other frontmatter chapters) in the table of contents should be unbolded.
\tableofcontents
\mainmatter
\addtocontents{toc}{\let\string\bfdefault\string\bforigdefault}
\chapter{Chapter name}
But the mainmatter chapters should still be bold in TOC.
\end{document}


text:
Q: Migrating from Travis to GitLab CI with Docker I'm migrating from Travis to GitLab CI and I'm struggling to get Docker working:
.gitlab-ci.yml file:
image: docker:latest

services:
  - docker-dind

stages:
  - build
  - test

before_script:
  - apk add python3 python3-dev python3-pip
  - pip3 install --upgrade pip
  - pip3 install --no-cache-dir docker-compose
  - export REACT_APP_USERS_SERVICE_URL=http://127.0.0.1

compile:
  stage: build
  script:
    - docker-compose up --build -d

test:
  stage: test
  script:
    - docker-compose exec users python manage.py test

after_script:
  - docker-compose down

The build error throws:
ERROR: Job failed: Error response from daemon: pull access denied for docker-dind, repository does not exist or may require 'docker login' (executor_docker.go:188:0s)

How do I troubleshoot this ? I haven't needed docker login until now.
Edit:
After researching on GitLab docs and from similar SO topics I got to this:
image: docker:stable

services:
  - docker:dind

stages:
  - build
  - test

before_script:
  - apk add python python-dev python-pip
  - pip install --no-cache-dir docker-compose
  - export REACT_APP_USERS_SERVICE_URL=http://127.0.0.1

compile:
  stage: build
  script:
    - docker-compose up --build -d

test:
  stage: test
  script:
    - docker-compose exec users python manage.py test

after_script:
  - docker-compose down

Error output reads:
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/community/x86_64/APKINDEX.tar.gz
ERROR: unsatisfiable constraints:
  pip (missing):
    required by: world[pip]

A: This is the .gitlab-ci.yml file that got it running:
image: docker:stable

services:
  - docker:dind

stages:
  - build
  - test

before_script:
  - apk add --no-cache py-pip python-dev libffi-dev openssl-dev gcc libc-dev make
  - pip install --no-cache-dir docker-compose
  - export REACT_APP_USERS_SERVICE_URL=http://127.0.0.1

compile:
  stage: build
  script:
    - docker-compose up --build -d

test:
  stage: test
  script:
    - docker-compose exec users python manage.py test

after_script:
  - docker-compose down

A: It's docker:dind, not docker-dind.
services:
  - docker:dind


text:
Q: Spark with replicated Cassandra nodes I found article where author advices to use next Spark-Cassandra architecture schema(Spark Slave for each Cassandra node):

I have N Cassandra nodes. All nodes are complete replicas of each other. Is some sense to run Spark slave for each Cassandra node in my case?

A: Yes it does. The Spark-Cassandra connector is data locality aware, i.e. each Spark node co-located with a Cassandra node will make sure to only process the local Cassandra data, which avoids shuffling lots of data across the network. You can find out how this works by watching a talk by Russell Spitzer on this topic here.


text:
Q: List search results in a combobox I want to change our search as it is a bit hacky now.
Currently it works like this:

*

*User enter a text in a textbox, for example Volvo and start searching.

*This search with SQL all posts containing Volvo.

*The result is a list with 2 columns, BoldID and DisplayValue.

*BoldID is just an unique number to identify the object in database.

*DisplayValue is what the user see in the list of results.

*Each row in the resultset is identified with a row number in users list. The first with 1, the second with 2 and so on.

*There is also a limitation to only show max 99 hits by intention by looping the query in code. It is not good to have a query that returns many hits as it no meaning to have more in the users hit list. The search should be more specific in that case.

The result list is displayed in a separate global window called rightpane. The hacky part is that if searching from a modal dialog then rightpane must be undocked from the main window to be able to pick a value with the mouse. We suspect this could be a reason that the application sometimes lock itself with the modal dialog behind the main window.
After change it should work like this:
The user enter text in a Combobox and start searching with SQL on demand like before. But the resultset is displayed in the combobox. So I only want to change the display if possible as there are a lot of old SQL queries that is in use and works fine now.
We use Delphi 2007, Interbase 2009 and components from DevExpress. Yesterday I tried to connect a customdatasource to a combobox, but I realize this was not implemented yet. See How to use a TcxCustomDataSource in a TcxExtLookupComboBox. I want to use a custom datasource to implement row number and max number of hits. Se 6 and 7 in the list above.
So now I see 2 options:

*

*Use a DB-aware combobox

*Use a textbox and attach a grid to it to display the resultset.

The combobox is simpler because it is a whole component, but I don't know how to implement feature 6 and 7 from the list above.
The textbox + grid give more freedom but require more work.
I prefer the first option. The current problems is:

*

*I think Interbase SQL cannot restrict the amount of hits in the resultset. It must be done with code. How is this done with a DB-aware combobox ?

*How can I display row numbers in the resultset ?

Update 1:
Requirement 7 is solved thanks to Marjan, thanks.
As for 6 I think it is harder. Ideally I want it in SQL so I could extract an own column like Adding row no. But Interbase don't support that.

A: Requirement 6:
Assuming that the db's id value is an integer, you can use the tag of a control or the Object of the strings in a combobox/listbox to store the id value.
[pseudo code]
while not eof do
  ComboBox.Items.AddObject(<DisplayText From Db>, TObject(<IntegerID from Db>));

and use it like so
id := Integer(ComboBox.Items.Objects[ComboBox.ItemIndex]);

Requirement 7:
Using a db aware combobox/listbox looping through the query til eof or 99 rows is out. So you would need to rely on SQL. Even if you do not want to change any of the current SQL statements, you could use SQL's "TOP" feature to limit the number of rows. For example
SELECT TOP 99 FROM (<your original SQL>)

In Interbase SQL you can use the phrase:
ROWS 1 TO 99

just after the order clause (see example at http://blogs.teamb.com/craigstuntz/dtpostname/ibsqlintro/ - almost the bottom of the page)

A: Interbase has a ROWS clause, apparently used for what you want.


text:
Q: Most efficient way to set up MySQL Tables? I have a table called 'users' that contains fields such as
username
DOB
gender
etc

Each user can save their plants on a table called 'plants' that has the following fields
username
plant

So user 'johndoe' would show on table 'plants' as follows:
johndoe -> lilly
johndoe -> orchid1
johndoe -> orchid2
johndoe -> fern1
johndoe -> fern2

Questions:
Is this a bad way of setting up my tables? I ask because when the number of users grows, then there will be hundreds of rows, several of which with repeated usernames because each user will likely have more than one plant. Would this slow down queries?
If I make one plant table per user, I think that would increase dramatically the number of DB requests and create an enormous amount of tables in the DB.
Another option would be to have separate tables for lilly, orchid, fern, etc with fields such as
username

but then I would still have several rows with repeated usernames.
Any suggestions?

A: Normalize your tables. Add id field to users and store that id in plants instead of the username.
Further, read more about normalization principles and try to apply them in practice.

A: In stead of using the username I would use an INT id. Like so:
userid
username
DOB
gender
etc

and for your plants:
plantid
userid_fk
plantname

And then join on users.userid = plants.userid_fk to find the matches :)

A: That's a perfectly reasonable way (your initial proposal) to set things up; that's what relational databases are for.
You're doing a classic many-to-many relationship in your plants table.  Each user can have several plants, and each plant may have several users.
For better efficiency, you could use an id to refer to your users instead of a user name.  In most relational databases, an id is a row number, and is a very efficient (and compact) reference.

A: Here's how I'd go about this, with an example database script and query:
Create/Load Users Table - Using a surrogate primary key instead of the username since queries will be faster against INTs and they can conceivably change.
CREATE TABLE users  (
    id          int(11) AUTO_INCREMENT NOT NULL,
    username    varchar(255) NOT NULL,
    gender      char(1) NULL,
    PRIMARY KEY(id)
) ENGINE = MyISAM AUTO_INCREMENT = 3

Load Users
INSERT INTO users(id, username, gender)
  VALUES(1, 'john', NULL)
GO
INSERT INTO users(id, username, gender)
  VALUES(2, 'jane', NULL)
GO

Create Plants
CREATE TABLE plants  (
    id      int(11) AUTO_INCREMENT NOT NULL,
    name    varchar(200) NOT NULL,
    PRIMARY KEY(id)
) ENGINE = MyISAM AUTO_INCREMENT = 6

Load Plants
INSERT INTO plants(id, name)
  VALUES(1, 'fern1')
GO
INSERT INTO plants(id, name)
  VALUES(2, 'fern2')
GO
INSERT INTO plants(id, name)
  VALUES(3, 'orchid1')
GO
INSERT INTO plants(id, name)
  VALUES(4, 'orchid2')
GO
INSERT INTO plants(id, name)
  VALUES(5, 'lilly1')

Create Join Table I use a surrogate primary key here since so many web platforms won't properly update a join table with a 2 column primary. Also, I've ended up adding meta data / details to these types of joins quite often, and it gets messy without it. Note I don't restrict the combination of the same user adding the same plant type, but you can easily.
CREATE TABLE plants_users  (
    id          int(11) AUTO_INCREMENT NOT NULL,
    plant_id    int(11) NOT NULL,
    user_id     int(11) NOT NULL,
    PRIMARY KEY(id)
)
ENGINE = MyISAM
AUTO_INCREMENT = 8
GO
CREATE INDEX fk_plant_id USING BTREE
    ON plants_users(plant_id)
GO
CREATE INDEX fk_user_id USING BTREE
    ON plants_users(user_id)

Load Join Table
INSERT INTO plants_users(id, plant_id, user_id)
  VALUES(1, 1, 1)
GO
INSERT INTO plants_users(id, plant_id, user_id)
  VALUES(2, 2, 1)
GO
INSERT INTO plants_users(id, plant_id, user_id)
  VALUES(3, 3, 1)
GO
INSERT INTO plants_users(id, plant_id, user_id)
  VALUES(4, 4, 1)
GO
INSERT INTO plants_users(id, plant_id, user_id)
  VALUES(5, 2, 2)
GO
INSERT INTO plants_users(id, plant_id, user_id)
  VALUES(6, 3, 2)
GO
INSERT INTO plants_users(id, plant_id, user_id)
  VALUES(7, 5, 2)

Final Query:
select
    users.username,
    plants.name
from
    users,plants,plants_users
where
    users.id = plants_users.user_id and
    plants.id = plants_users.plant_id

Result:
    user    name
    john    fern1
    john    fern2
    john    orchid1
    john    orchid2
    jane    fern2
    jane    orchid1
    jane    lilly1


text:
Q: Socket.io examples with Swift and Node.js on the backend I am trying to find a working example of a Socket.io implementation on iOS with Swift, but have been unlucky so far. I did get a few examples from Github, but each have some issues and I cannot tell why they don't work.
Does anyone know where I can get an out of the box working example, so that I can go through the code and understand the implementation?

A: Based on socket.io's examples:
Server (index.js, see socket.io website for setup):
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
    socket.on('chat message', function(msg){
        io.emit('chat message', msg);
    });
});

http.listen(8080, function(){
   console.log('listening on *:8080');
});

Client (ViewController.swift):
import UIKit
import Socket_IO_Client_Swift

class ViewController: UIViewController {

@IBOutlet weak var chatView:UITextView!
@IBOutlet weak var sendButton:UIButton!
@IBOutlet weak var sendField:UITextField!

let socket = SocketIOClient(socketURL: "10.0.0.1:8080", opts: ["log": true])

override func viewDidLoad() {
    super.viewDidLoad()

    addHandlers()
    self.socket.connect()
}

@IBAction func send() {
    self.socket.emit("chat message", withItems: [self.sendField.text!])
    self.sendField.text = ""
}

func addHandlers() {
    self.socket.on("connect") {data, ack in
        print("socket connected")
    }

    self.socket.on("chat message") {[weak self] data, ack in
        if let value = data.first as? String {
            self?.chatView.text?.appendContentsOf(value + "\n")
        }
    }
}
}

Web client (index.html, useful for testing):
<!doctype html>

    <title>Socket.IO chat</title>

    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>

A: Since I asked the question there have been changes and we now have socket.io for iOS. Here's the original blog post on it: http://socket.io/blog/socket-io-on-ios/


text:
Q: TIMESTAMPDIFF returns the wrong number of months in mysql If we add the 1 month to the DATE_ADD
SELECT DATE_ADD('2023-01-31 07:26:35', INTERVAL 1 MONTH)

Which returns the date 2023-02-28 07:26:35
While if we calculate with TIMESTAMPDIFF it return the 0 as number of month which i guess needs to be 1?
SELECT TIMESTAMPDIFF(MONTH,'2023-01-31 07:26:35', '2023-02-28 07:26:35')

Please let me know where the issue is.

A: The function works in such a way that it checks how many literal months are completed from the start date to the end date. It doesn't matter how off the number in the month segment of the start date from that of the end date.
A full month needs to be completed from date to date.
The following question will answer your question: "can it be considered that a full month has been passed from 02/15 to 03/10 ?"
Check the following result out
SELECT TIMESTAMPDIFF(MONTH,'2023-01-31', '2023-02-03') // 0
SELECT TIMESTAMPDIFF(MONTH,'2003-01-31','2003-02-28'); //0
SELECT TIMESTAMPDIFF(MONTH,'2003-01-31','2003-02-28'); //Null (not a leap year)

SELECT TIMESTAMPDIFF(MONTH,'2003-01-31','2003-03-01'); //1

The function calculates the difference the way it would be done by a human.


text:
Q: How does the ng_copy work actually in AngularJS? How does the ng-copy work actually?
I came across the below code and unable to connect the working of ng-copy
<input ng-copy="count = count + 1" ng-init="count=0" value="Copy this text" />

The text has been copied {{count}} times.

A: Your code works for me in Chrome 70 on a Mac. Here's a stackblitz showing it working.

Are you using a browser that supports the copy event? Note that it's not universally supported.


text:
Q: Gantt Chart in jfreeChart? I have a .csv file containing TaskId and TaskStartTimerValue. I want to make a Gantt Graph displaying TaskId on the x axis and TaskStartTimervalue at the y axis. I am using a demo from this link this link at sanjaal.com.
The demo uses a SimpleTimePeriod method to get the timing range.
Is there any other method available that I can use to pass my timer values?

A: As an alternative to TimePeriod, you can use the Task constructor that accepts two Date instances:
public Task(java.lang.String description,
    java.util.Date start,
    java.util.Date end)

Use an instance of Calendar to create your dates. In this example, there are two main tasks:
Task t1 = new Task("Design", date(1, MAY), date(31, MAY));
Task t2 = new Task("Proposal", date(1, JUNE), date(31, JUNE));

This simple auxiliary method, analogous to the example's makeDate(), generates dates for a fixed year:
private static Date date(final int day, final int month) {
    final Calendar calendar = Calendar.getInstance();
    calendar.set(2012, month, day);
    final Date result = calendar.getTime();
    return result;
}


text:
Q: Change color of the view using RGB value or hex value of color in swift I got the following code on internet and I used this piece of code in my project to change the color of the background.
// Creates a UIColor from a Hex string.

func colorWithHexString (hex:String) -> UIColor {
    var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString

    if (cString.hasPrefix("#")) {
        cString = (cString as NSString).substringFromIndex(1)
    }

    if (countElements(cString) != 6) {
        return UIColor.grayColor()
    }

    var rString = (cString as NSString).substringToIndex(2)
    var gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
    var bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)

    var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
    NSScanner(string: rString).scanHexInt(&r)
    NSScanner(string: gString).scanHexInt(&g)
    NSScanner(string: bString).scanHexInt(&b)

    return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}

When I called the above function as follows to change the color of background:
lbl91.backgroundColor = colorWithHexString(hex: 0x209624);

it gives me following error:
cannot convert the expression's type '()' to type integerliteralconvertible

A: The function expects its parameter like this:
colorWithHexString("#ff00dd")

or without the hashtag
colorWithHexString("ff00dd")


text:
Q: Getting error MySQLNonTransientConnectionException while using batch update in SQL Following cod:
String url;
ConnectionURL cURL= new ConnectionURL();
url=cURL.getCloudConnection();
try (Connection conn = DriverManager.getConnection(url))
{
    Statement statement = conn.createStatement();
    conn.setAutoCommit(false);

    for(int i=9;i<updateCformValues.size()-1;i++){
         List<Object> row=updateCformValues.get(i);
         String JDECode =(String)row.get(0);

        String CValue =(String)row.get(3);
        String updatedata = "update CRdataTable set OutstandingCFormValue='"+CValue+"'  where JDECode ='"+JDECode+"' ";
        log("String"+i);
        statement.addBatch(updatedata);
     }

    statement.executeBatch();

      conn.commit();
}

}
    catch (Exception e) {
            // TODO: handle exception
        out.print(e);
                e.printStackTrace();
        }

Throws an excpetion
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after statement closed

Please help me, thanks.


text:
Q: list with a tuple of dicts instead of list of dicts I have list of dicts
[{'id': 14786,
  'sku': '0663370-ZWA',
  'sizes': ['38', '40', '42', '44', '46'],
  'color': 'zwart'},
 {'id': 14787,
  'sku': '0663371-ZWA',
  'sizes': ['38', '40', '42', '44', '46'],
  'color': 'zwart'}]

want to place it in a datastructure for update attributes with woocommerce api
list_of_update_items = []

for index in lst_of_dcts:
    lst_of_attributes_items=[]
    attributes = {'id': 1, 'name': 'kleur', 'position': 0,'options': index['color'], 'variations': 'false','visible': 'true'},{'id': 6, 'options': index['sizes'], 'variations': 'true','visible': 'true'}
    # make a list of attributes_items to use as value in the parent dict
    lst_of_attributes_items.append(attributes)
    #make a dict with id as key and atribute_list as key
    update = {'id': index['id'], 'attributes': lst_of_attributes_items}
    list_of_update_items.append(update)
    #clear the list of attributes_items for the next iteration
    lst_of_attributes_items=[]
    #wrap in the top_dict
    data = {'update': list_of_update_items}

data results in
    {'update': [{'id': 14786,
   'attributes': [({'id': 1,
      'name': 'kleur',
      'position': 0,
      'options': 'zwart',
      'variations': 'false',
      'visible': 'true'},
     {'id': 6,
      'options': ['38', '40', '42', '44', '46'],
      'variations': 'true',
      'visible': 'true'})]},
  {'id': 14787,
   'attributes': [({'id': 1,
      'name': 'kleur',
      'position': 0,
      'options': 'zwart',
      'variations': 'false',
      'visible': 'true'},
     {'id': 6,
      'options': ['38', '40', '42', '44', '46'],
      'variations': 'true',
      'visible': 'true'})]}]}

makes a tuple of dicts in the list of 'attributes'_values. what I need is a list of dicts. What causes the tupple?

A: You use an intermediate:
lst_of_attributes_items=[]

Which you append a tuple of dicst to:
attributes = {'id': 1, 'name': 'kleur', 'position': 0,'options': index['color'], 'variations': 'false','visible': 'true'},{'id': 6, 'options': index['sizes'], 'variations': 'true','visible': 'true'}
list_of_update_items.append(update)

Notice,
attributes = {...}, {...}

Creates a tuple.
And then that list, with a single item (which is a tuple with two dicts) is set to the "attribute" key of your update dict:
update = {'id': index['id'], 'attributes': lst_of_attributes_items}

This doesn't make any sense, just make attributes a list instead of a tuple (since you dont want tuples... dont use tuples) then just put that directlyin the update dict. The whole thing can be simplified to:
lst_of_dcts = [{'id': 14786,
  'sku': '0663370-ZWA',
  'sizes': ['38', '40', '42', '44', '46'],
  'color': 'zwart'},
 {'id': 14787,
  'sku': '0663371-ZWA',
  'sizes': ['38', '40', '42', '44', '46'],
  'color': 'zwart'}]

list_of_update_items = []

for index in lst_of_dcts:
    attributes = [
        {'id': 1, 'name': 'kleur', 'position': 0,'options': index['color'], 'variations': 'false','visible': 'true'},
        {'id': 6, 'options': index['sizes'], 'variations': 'true','visible': 'true'}
    ]
    list_of_update_items.append({'id': index['id'], 'attributes': attributes})

data = {'update': list_of_update_items}

Indeed, you could do the whole thing with a list comprehension (although, I probably wouldn't, since it isn't as readable to me):
update_items = [
    {
        "id": index["id"],
        "attributes": [
            {
                "id": 1,
                "name": "kleur",
                "position": 0,
                "options": index["color"],
                "variations": "false",
                "visible": "true",
            },
            {
                "id": 6,
                "options": index["sizes"],
                "variations": "true",
                "visible": "true",
            },
        ],
    }
    for index in lst_of_dcts
]

Although, using a helper function makes it pretty nice:
def update_from_index(index):
    return {
        "id": index["id"],
        "attributes": [
            {
                "id": 1,
                "name": "kleur",
                "position": 0,
                "options": index["color"],
                "variations": "false",
                "visible": "true",
            },
            {
                "id": 6,
                "options": index["sizes"],
                "variations": "true",
                "visible": "true",
            },
        ],
    }

update_items = [update_from_index(index) for index in lst_of_dcts]


text:
Q: 2NF with a transitive dependency? Tomorrow I have my final exam of Database Design but I have a doubt about the Second Normal Form (2NF).
The definition says a relation is in 2NF if no non-prime attribute is partially dependent on a key.
My doubt is about if a relation could be in 2NF is if has attributes that are fully dependent on a key but transitively.
For example:
R (A,B,C,D) with AB key and FD ( AB->C,C->D)
In this case the non-prime attribute C is fully dependent on the key so it meets the condition but in the case of the attribute D I don´t know if it meets the rule.
 D is dependent on C and due to C is fully dependent on the key,does it mean that D is fully dependent on the key being this relation in 2NF?

A: Yes, D is transitively fully dependent on the key and this is valid in 2NF.  Transitive dependencies are addressed in 3NF.


text:
Q: How to automatically find the correct schema to store data inside a PostgreSQL database? I have a C# WinForms application that imports sales contained in a fixed width file and stores it into some tables. The tables have the exact same structure but are located in different schemas inside the database.
Currently I run two queries in my application to store each sale's data, one to fetch the correct schema to store the data and another to actually insert it into the table.
To better exemplify, let's say I have a Clients table in a Main schema and several schemas (one for each region of my country) with a Sales table each. I use each sale's Client Id to find the correct schema to store it.
I need to optimize this proccess, make it faster. I profiled the application and this two queries are the most time consuming steps. I think running a single command inside my application and leaving the work of finding the correct schema to the database will help.
I want to achieve something like this:
INSERT INTO
    (SELECT clients.schema_name FROM main.clients WHERE client_id = @client_id).sales
    (client_id, qty, value)
VALUES
    (@client_id, @qty, @value)

Clearly it doesn't works. I don't know much about SQL, just the basics, but I think that's not possible to do with in a single command, I guess I need a Stored Procedure for that.
I would love to hear some directions or even better solutions for this (as long it does not involves changing the database structure).

A: Your database is broken, and avoiding the problem is quite probably not going to be worth it long term. If you are interested, it's not difficult to point out the maintainability problems with using schemas like that.
That said, you probably cache client_id -> schema_name in your C# code and avoid most queries to get that information.
You could also write a SP to do that, but it would probably have to resort to constructing dynamic SQL queries or a similar hack which might be pretty slow by itself.


text:
Q: consulta webbrowser c# tengo una duda si esto se puede plantear así porque me está leyendo la misma url envés de las que figuran en la lista, no se si tengo que destruir el objeto "navegador" o como seria?? soy nuevo usando esto
  for (int i=0;i<listView1.Items.Count;i++)
        {

           string nombrepj= listView1.Items[i].SubItems[0].Text;
           string url_Completa = url_base + nombrepj;

            navegador.Navigate(url_Completa);
            navegador.ScriptErrorsSuppressed = true; //oculta los errores de script
            navegador.DocumentCompleted += datos_cargados;

        }


text:
Q: parse String variable from database (type datetime) to LocalDateTime variable using Resultset I'm trying to convert a String value (initially a LocalDateTime variable) that was stored in a database (as datetime) and parse it into a LocalDateTime variable. I've tried it with a formatter:
String dTP;
dTP=(rs.getString("arrivedate"));
            DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
            LocalDateTime dateTimeParked = LocalDateTime.parse(dTP,formatter);

And without a formatter:
String dTP;
dTP=(rs.getString("arrivedate"));
LocalDateTime dateTimeParked = LocalDateTime.parse(dTP);

But I get the same error each time:
Exception in thread "AWT-EventQueue-0" java.time.format.DateTimeParseException: Text '2016-07-09 01:30:00.0' could not be parsed at index 10

My thinking is that index 10 is the space between date and time.
Could anyone help me with this? I've been at it for hours :(

A: There is a error in the format of the that causes the issue. Please refer https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html.The ISO date time is of the format  '2011-12-03T10:15:30' .  The following will give you the idea
public static void main(String[] args) throws Exception {

    String isoDate = "2016-07-09T01:30:00.0";
    //  ISO Local Date and Time '2011-12-03T10:15:30'
    DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
    LocalDateTime dateTimeParked = LocalDateTime.parse(isoDate, formatter);
    System.out.println(dateTimeParked);

    String date = "2016-07-09 01:30:00.0";
    DateTimeFormatter formatterNew = DateTimeFormatter.ofPattern("yyyy-LL-dd HH:mm:ss.S");
    LocalDateTime dateTimeParkedNew = LocalDateTime.parse(date, formatterNew);
    System.out.println(dateTimeParkedNew);

}

This prints :
2016-07-09T01:30
2016-07-09T01:30

A: The other answers are correct, your string is in SQL format which differs from the canonical version of ISO 8601 format by using a space character in the middle rather than a T.   So either replace the space with a T or define a formatting pattern for parsing.
Use smart objects, not dumb strings
But the bigger problem is that you are retrieving the date-time value from your database as a string. You should be retrieving date-time types of data as date-times types in Java.
For drivers compliant with JDBC 4.2 and later, you should be able to use setObject and getObject with java.time objects.
For SQL type of TIMESTAMP WITHOUT TIME ZONE use LocalDateTime. For TIMESTAMP WITH TIME ZONE, use Instant or perhaps ZonedDateTime depending on the database.
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class );

Store in database.
myPreparedStatement.setObject( … , ldt ) ;

A: try this formatter:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");

I'm not sure about the millisecond part though (In case it is more than 1 character long).


text:
Q: The file does not exist I was working on my project last night, I saved it as usual and closed down eclipse. I woke up today to continue with it as it's in for next week and this happens :

I have no idea what to do. Is there any possibility I can get my classes back?
thanks =/

A: *

*Make sure the project is inside the eclipse workspace folder

*Delete the project from eclipse (DON'T SELECT "DELETE PROJECT CONTENTS ON DISK")

*Restart eclipse

*Import the project

A: Restarted Eclipse ? Seems like it crashed. Maybe you copy the folder of the project and import it as a new project.


text:
Q: Parse error: syntax error, unexpected ')', expecting '(' in C:\xampp\htdocs\res\connection.php on line 12 I need some help here. I have some code below, and my question is, I'm not getting where the error is, which is showing by the error message.
try
{
    $db = new PDO('mysql:host=localhost; db_name=softdemo','root', '');
}
catch(PDOException $e)
{
    echo $e->getMessage();
}

try{
    foreach ( $db->query("SELECT * FROM users") as row )
    {
        echo $row['username'].$row['password']."<br/>";
    }
    $db = null;
}
catch(Exception $e)
{
    echo $e->getMessage();
}

A: Error comes from this line you missed $ before $row variable
  foreach ( $db->query("SELECT * FROM users") as row )

Change this to
$res = $db->query("SELECT * FROM users");
if(!empty($res))
{
  foreach( $res as $row )
  { //code here..
  }
}

A: You've missed $ sign, this is required as $row is a variable.
So, Change
foreach ( $db->query("SELECT * FROM users") as row )

To
$res = $db->query("SELECT * FROM users");
if(!empty($res))
{
  foreach( $res as $row )
  { //code here..
  }
}

A: You've missed out a $, this is required as $row is a variable.
foreach ( $db->query("SELECT * FROM users") as $row )


text:
Q: What's the difference between error and fail? I've been looking for answer for this question and found this blog post. It says that fail has advantages over error because it isn't constrained to the IO monad.
Should i use fail instead of error all over my code? Does fail raise Control.Exception.catchable exceptions in IO?
EDIT: I've found an update for the link above.

A: Here's my advice:

*

*If you're in IO code already, use proper exceptions via throwIO from Control.Exception.

*If your code uses a monad stack already, add errors to your monad stack if it doesn't support it already, and use those.

*If you are in non-monadic code, write total functions. I.e., avoid error and incomplete patterns if you can. Using fail here would only force your code to be unnecessarily monadic. If you need exceptional results, use a proper data type (such as Maybe or Either or a custom datatype).


text:
Q: Docker deployment update shared volume Kind of new with Docker in production I have a design question.
What is the best approach to deploy with Docker a PHP app that contains data and info used by other containers in the main application directory that will have to be updated over the builds ?
Example (simplify Symfony kind of app):
- application
    - app
    - src
    - vendor
    - conf
    - conf/vhost.conf
    - web/assets/*

And let's simplify with only 2 services
- php-fpm
- nginx

1/ The first try was to build 2 images

*

*php-fpm: with

ADD . /var/www/html/project/
VOLUME /var/www/html/project/
vendors(composer) install in the Dockerfile

That way I was able to reach /var/www/html/project/ on nginx

volumes_from php-fpm

=> And then the configuration and the assets etc.
But if I am not wrong that is not the good way to do it because in the next build my image won't update the VOLUME /var/www/html/project/ (because it is a volume)
=> then my code will never be updated.
2/ Then I ended up doing that:
- providing the last code base in the image: COPY . /data/image/app
- creating a named volume: docroot
- mount docroot on php-fpm
- adding a rsync on the entrypoint to sync /data/image/app to docroot:/var/www/html/project ( with the good excludes that I needed)
- doing the vendors(composer) install in the entrypoint

=> still using volumes_from:php-fpm on nginx.
Which is important because I want:
- the conf/vhost.conf
- the assets
- maybe other stuff

I may need to add a SolR that will use some configuration files and/or resources etc.
3/ I suppose there is another approach that would consist to specifically ADD what I need on each image.
I think it adds complexity to the build process
but it makes also a lot of sense.
So, what do you think, have I missed something? approach 2/ or 3/, 4?
Thank you very much!

A: Your question is really about static file assets. Some frameworks and projects treat these very much like their own component. In the php world, the php-fpm application server doesn't normally handle static files. It leaves that up to a webserver component like nginx. This, on its own, is not a problem. In fact it is good practice.
The only reason it's coming up is you are introducing an isolation layer between php-fpm and nginx.
If we consider another, non-docker, situation where an isolation is introduced between php-fpm and nginx, we get the same problem. In this example, I'll have my nginx server running in the DMZ of my datacenter, and php-fpm will act as the application server behind the firewall in my datacenter. How will that nginx serve up that php project's static files?
I mentioned that static assets could almost be considered their own component. In this two-node example, a separate step during the deploy could be utilized to populate the static files on the nginx server in the DMZ. This is not unlike your solution #2 where you run an rsync to populate a volume that both the php-fpm and nginx containers have access to.
Yet another solution would be to make php-fpm handle serving up these static assets. This, of course, is not considered a best practice since php-fpm is not built to serve static files. It can be done, but it's poorly optimized. This performance hit can be mitigated by using nginx file caching.
Your #3 solution is also quite viable. You could also have your project build two images instead of one. The first one would be your normal php image that has all your php code ADDed. The second would be based on the nginx base image, and ADD only the static files that the project needs.
Although it isn't considered best practice, it may be appropriate on some projects to run both nginx and php-fpm in the same container. If your nginx configuration is literally only serving up static files and reverse proxying to php-fpm, then you can treat that pair of processes as one logical service. You would need to run supervisord, runit, or a similar process manager.


text:
Q: Email HTML table renders correctly in Gmail but fails in Outlook I'm trying to convert a simple Web HTML into an Email HTML file. I was able to convert it into table structure which renders properly in Gmail but fails in Outlook.
The height and width of all the corresponding rows and columns are correct. I'm not able to figure out the reason why it breaks in Outlook.
Below is a screenshot of the working case from Gmail:

Below is a screenshot of the failing case from Outlook :

Fiddle for the HTML code : HTML file

 -

 -

 Lorem ipsum dolor sit consectetur

 Vivamus tincidunt:

 Vestibulum

Lorem Ipsum

 Nulla convallis:

 Aliquam amet

Phasellus

 Donec eget velit:

 Nunc metus

 Duis rhoncus enim:

 Vivamus

 Praesent laoreet:

 Pellentesque

 -

Can you please let me know how to make it correct and consistent across both Gmail and Outlook?
Thanks in advance.

A: Check all your  elements have the background color.
Alternatively, you can just wrap the entire table in another table that has the background-color, like so:

    ...

If you don't want the top rows to have a color, put a wrapping table in for them with a white bgcolor - or remove them entirely (why are they even there...).


text:
Q: How to implement a StringFormat in a property grid?
SCENARIO

I've sub-classed a control and I would like to add an StringFormat expandable group in the control's property grid to set its values at design time.

PROBLEM

I'm unable to properly add the StringFormat properties into the property grid, this is what I get:

QUESTION

Which is the simplest way to implement an StringFormat into a PropertyGrid?

CODE

I've tried the suggestion of @Plutonix answer here: Create an expandable group in a property grid? (sure I'm doing something wrong)
I preffer to avoid a TypeConverter usage in case of this could be done in a simpler way, because I'm not sure whether this implementation needs this kind of headache.
Public Class MyControl: Inherits ListBox

    Public Property MyProperty As MyStringFormat = New MyStringFormat

End Class

<TypeConverter(GetType(StringFormatConverter))>
Public Class MyStringFormat

    <Browsable(True)>
    <NotifyParentProperty(True)>
    <EditorBrowsable(EditorBrowsableState.Always)>
    Public Property myStringFormat As StringFormat

    Public Sub New()
        ' default values, if any
        myStringFormat = New StringFormat
    End Sub

End Class

Public Class StringFormatConverter : Inherits ExpandableObjectConverter

    Public Overrides Function ConvertTo(context As ITypeDescriptorContext,
                                        culture As Globalization.CultureInfo,
                                        value As Object,
                                        destinationType As Type) As Object

        Return MyBase.ConvertTo(context, culture, value, destinationType)

    End Function

End Class

A: Following on with your earlier adventure, this is all you need:
' property on the control

<Browsable(True), EditorBrowsable(EditorBrowsableState.Always),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
DefaultValue(-1)>
Public Property TextFormating As TextFormat

' be sure to instance it!
' TextFormating = New TextFormat

Using the Component approach:
Public Class TextFormat
    Inherits Component

    <Browsable(True), NotifyParentProperty(True),
    DesignerSerializationVisibility(DesignerSerializationVisibility.Visible),
    EditorBrowsable(EditorBrowsableState.Always), DefaultValue(-1)>
    Public Property Alignment As StringAlignment

    <Browsable(True), NotifyParentProperty(True),
    DesignerSerializationVisibility(DesignerSerializationVisibility.Visible),
    EditorBrowsable(EditorBrowsableState.Always), DefaultValue(-1)>
    Public Property LineAlignent As StringAlignment

    <Browsable(True), NotifyParentProperty(True),
    DesignerSerializationVisibility(DesignerSerializationVisibility.Visible),
    EditorBrowsable(EditorBrowsableState.Always), DefaultValue(-1)>
    Public Property Trimming As StringTrimming

    <Browsable(True), NotifyParentProperty(True),
    Editor(GetType(UIEnumEditor), GetType(UITypeEditor)),
    DesignerSerializationVisibility(DesignerSerializationVisibility.Visible),
    EditorBrowsable(EditorBrowsableState.Always), DefaultValue(-1)>
    Public Property FormatFlags As StringFormatFlags

End Class

Add whatever other properties you want.  You can inherit because it is a sealed class, also it doesnt have all the attributes you require.  You wont like the default behavior of the StringFormatFlags property; and if you think a TypeConverter is a headache, you are in for a treat!

Since StringFormatFlags is a Flag Enum, you will likely want to pick and combine several at a time.  The default UITypeEditor though is a DropDown, but we want a DropDownCheckList.  For this, we need a custom UITypeEditor.  These are not as scary as they sounds, but there is also no need to recreate the wheel:
The Enhanced CollectionEditor Framework article on CodeProject is a collection editor framework which also includes a EnumTypeEditor (scroll to the end of the article where it is mentioned in passing).  In about the middle of the article is a brief primer on TypeConverters as well.
To use it:
- download the file and include the DLL in your project
- then (re)decorate your TextFormat.TextFormatFlags property:
<Editor(GetType(UIEnumEditor), GetType(UITypeEditor)),
Browsable(True), NotifyParentProperty(True),
DesignerSerializationVisibility(DesignerSerializationVisibility.Visible),
EditorBrowsable(EditorBrowsableState.Always), DefaultValue(0)>
Public Property TextFormatFlags As StringFormatFlags

(Note the added UIEnumEditor attribute).
The article and demo shows how to inherit the base editor to customize a few things.  One thing it will do is use Descriptions rather than the Enum Name in the list, if they exist and if you want.  That's it, 2 steps and you can check off which flags to combine:

You dont need a TypeConverter for this one because combining 4 properties into one string doesnt make much sense.  As before, it will still have the empty/extra drop down when your Type inherits Component.


text:
Q: Prime numbers in an dynamic array I've a program which inserts all prime numbers up to a specific number in an array.
The calculation is correct. My problems are the function parameters and the transfer of my dynamic array to the function. My function doesn't modify my array.
Please take a look at the code:
#include <iostream>

using namespace std;

int primeinlesen(int *i);
int primarrayspeicherung (int *primarray,int *bis);

int main()
{
    int reload=1;
    while(reload==1)
    {
        int bis=0,*primarray,valcounter;
        primeinlesen(&bis);
        valcounter=primarrayspeicherung(primarray,&bis);
        for(int i=0;i<valcounter;i++)
        {
            cout<<i<<". Primzahl: "<<primarray[i]<<"\n";
        }
        delete [] primarray;
        cout<<"Anzahl Primzahlen: "<<valcounter<<endl;
        cout<<"Erneute Berechnung?(Ja(1) oder Nein(0))";
        cin>>reload;
    }
    return 0;
}

int primeinlesen(int *i)
{
    cout<<"Bis zu welchem Wert moechten SiePrimzahlen ausgegeben,haben(max.500)";
    cin>>*i;
    if(*i>500)
    {
        cout<<"Wert zu hoch...";

    }
    return 0;
}
int primarrayspeicherung (int *primarray,int *bis)
{
    int x,y,counter,e,valcounter=0,xcounter=0,xvalcounter=0,xx,xy,xe;
    for(x=2;x<*bis;x++)
    {
        counter=0;
        for(y=2;y<x;y++)
        {
            e=x%y;
            if(e==0)
            {
                counter++;
            }
        }
        if(counter==0)
        {
            valcounter++;
        }
    }
    //ZWEITER DURCHGANG
    primarray=new int[valcounter];
    for(xx=2;xx<*bis;xx++)
    {
        xcounter=0;
        for(xy=2;xy<xx;xy++)
        {
            xe=xx%xy;
            if(xe==0)
            {
                xcounter++;
            }
        }
        if(xcounter==0)
        {
            primarray[xvalcounter]=xx;
            xvalcounter++;
        }

    }
    return valcounter;
}

Best regards

A: In this function:
int primarrayspeicherung (int *primarray,int *bis)

primarray is a local variable. Everything you're doing to it (e.g. allocating, assigning) only affects the local primarray, not the one you pass in. If you want to modify both, you need to pass in a reference:
int primarrayspeicherung (int*& primarray,int *bis)


text:
Q: Problema al llamar otra ventana en Python Tengo un botón el cual debe llamar otra ventana en python pero la interfaz aparece todo en blanco y el cmd me muestra esto

*Donde está el botón *
from tkinter import *
from creditos import *

 raiz = Tk()
 raiz.title("Test escolar");
 raiz.resizable(0, 0)
 raiz.configure(bg = '#CAA942')
 raiz.geometry("900x500")

 imagen = PhotoImage(file = "fondo.png")
 fondo = Label(raiz, image = imagen, bg = '#CAA942').place(x = 0, y = 0)

 imagen2 = PhotoImage(file = "user.png")
 fondo2 = Label(raiz, image = imagen2, bg = '#CAA942').place(x = 730, y = 160)

 lblmen = Label(text = "Test vocacional", font = ("Times New Roman", 25), bg =
 '#CAA942').place(x = 250, y = 0)
 lbldescripcion = Label(text = "Su interfaz dinámica hará que el aspirante no
 desvíe su atención,debido a que hace" + '\n'
      "más interesante el proyecto y menos tedioso realizar este tipo de
 examinaciones," + '\n'
      "esto ocasionará que responda con sinceridad.Tendrá un personaje en 2D que
 esta interactuando" + '\n'
      "con el usuario y el texto se representará en cuadro de diálogos," + '\n'
      " donde el usuario selecciona su respuesta según su consideración..", font = ("Agency Fb", 13), width = 85, height = 6, justify = LEFT, bg = '#CAA942').place(x = 185, y = 150)

lblpalabra = Label(text = "Iniciar", font = ("Times New Roman", 25), bg = '#CAA942').place(x = 45, y = 140)
boton = Button(raiz, text = "Pinchame", width = 15, relief = 'raised', command = (lambda: Ejemplo()))
boton.grid(row = 1, column = 2, padx = 5, pady = 5)

nxt = PhotoImage(file = "next.png")
a = Button(raiz, image = nxt, bg = '#CAA942').place(x = 60, y = 200)

raiz.mainloop()

La ventana a llamar
from tkinter import *
 def Ejemplo():

    raiz1=Tk()
    raiz1.title("Créditos");
    raiz1.resizable(0,0)
    raiz1.geometry("880x600")

    imagenfondo = PhotoImage(file="pizza.png")
    fondoimg = Label(raiz1,image=imagenfondo).place(x=0,y=0)
    lbltit = Label(text="Créditos",font=("Agency Fb",30),bg="#5B8C34",width=12,height=1,anchor=N,fg="white").place(x=70,y=270)
    lbltxt1 = Label(text="Equipo de diseño:" ,font=("Agency Fb",20),bg='#5B8C34',width=15,height=1,fg="black").place(x=345,y=100)
    lblname1 = Label(text="Freddy Uriostegui Cruz" +'\n' "Jose Roman Aviles",font=("Helvetica",15),bg='#5B8C34',anchor=S,fg="white").place(x=320,y=150)

    lbltxt1 = Label(text="Equipo de programación:" ,font=("Agency Fb",20),bg='#5B8C34',width=20,height=1,fg="black").place(x=315,y=230)
    lblname2 = Label(text="Leonardo Colli" +'\n' "Jose Roman Aviles" + '\n' "Emmanuel Cahuich Ramos" + '\n' "Freddy Uriostegui Cruz",font=("Helvetica",15),bg='#5B8C34',anchor=S,fg="white").place(x=300,y=280)

    lbltxt1 = Label(text="Equipo de sonido:" ,font=("Agency Fb",20),bg='#5B8C34',width=15,height=1,fg="black").place(x=330,y=400)
    lblname2 = Label(text="Leonardo Colli" +'\n' "Jose Roman Aviles",font=("Helvetica",15),bg='#5B8C34',anchor=S,fg="white").place(x=330,y=450)

    lbltxt1 = Label(text="Equipo de documentación:" ,font=("Agency Fb",20),bg='#5B8C34',width=25,height=1,fg="black").place(x=570,y=100)
    lblname2 = Label(text="Leonardo Colli" +'\n' "Emmanuel Cahuich Ramos",font=("Helvetica",15),bg='#5B8C34',anchor=S,fg="white").place(x=570,y=150)

    lbltxt1 = Label(text="Equipo creativo:" ,font=("Agency Fb",20),bg='#5B8C34',width=15,height=1,fg="black").place(x=600,y=250)
    lblname2 = Label(text="Leonardo Colli" +'\n' "Freddy Uriostegui",font=("Helvetica",15),bg='#5B8C34',fg="white").place(x=600,y=300)

    raiz1.mainloop()

Además de que el cmd me muestra esto:

A: Revisa que tengas pizza.png en el directorio
Prueba comentando :
imagenfondo = PhotoImage(file="pizza.png")
fondoimg = Label(raiz1,image=imagenfondo).place(x=0,y=0)


text:
Q: .net Core Controller action, return static html page I intend to return a static html page from my controller action. The html page is part of my project / bundle. I have the following code which works when run locally (localhost), but when on Azure, it fails. I don't have access to the Azure instance at the moment so I can not debug it or turn on Development mode for detailed errors etc. Please excuse the naiveness, what is the issue with the following code:
    public IActionResult PrivacyPolicy()
    {
        //_hostingEnvironment is an instance of IHostEnvironment
        var staticPage = PhysicalFile(System.IO.Path.Combine(_hostingEnvironment.ContentRootPath, "Views/Home/PrivacyPolicy.html"), "text/html");
        return staticPage;
    }

A: If you have access problems you can simply read the file and then just return its content:
return Content(File.ReadAllText("somefile.html"));

Darin Dimitrov also answered a question about this, that uses a different approach. please also have a look at that:
How do you request static .html files under the ~/Views folder in ASP.NET MVC?
Also as Darin says, you may want to put your static file in a different directory than Views

A: Depending on what sort of host OS you run your application you might want to check whether your "Views/Home/PrivacyPolicy.html" is spelled with correct case letters. Reason being, some filesystems (like ext4 on Ubuntu) are case sensitive.


text:
Q: Typescript: interfaces properties to string literal types? So this is a question to all Typescript wizards.
If I have an interface, e.g
interface A {
  value: string
  child : {
     nestedValue: number
  }
}

is it possible to derive a type that contains all properties of that interface A as string literal types? Like this:
type WhatIWant = 'value' | 'child.nestedValue'
Thanks!