Correct use of the implication symbol

Question: A lecturer mentioned that a common mistake people make in assignments is the incorrect use of the implication notation,  $\Rightarrow  $. I would like to clarify the correct use of the symbol as I am responsible for marking some first year assignments this term, and have been advised to deduct marks if students make this 'mistake'.
The symbol should be used, I am told, only when making a logical statement $A\Rightarrow B $, i.e. when the truth value is unknown. In other situations where we know $A $ is true, we should use the therefore symbol $\therefore $. So, for example, a mark would need to be deducted for the following answer:

Q: If $(a_n),(b_n) $ are positive, bounded real sequences, then $(a_nb_n) $ is also bounded.
A: $(a_n),(b_n) $ bounded $\Rightarrow  $ $a_n <A$ for some $A$ for all $n $, $b_n <B$ for some $B $ for all $n $ $\Rightarrow  $ $a_nb_n  <AB $ for all $n $ $\Rightarrow  $ $(a_nb_n)$ is bounded.

A mark would be deducted since $(a_n),(b_n) $ bounded was a hypothesis of the question. However, I see this as pedantic, since if I add the following line to the proof then it will be correct:

And since $(a_n),(b_n) $ bounded is assumed, it follows that $(a_nb_n) $ is bounded.

Am I right to say that this makes the argument 100% correct? I will add that the line need not be added in the first place, because given the context (an assignment answer), it is clear that this is what the author intended.
Comment: There was a similar longer proof in the handbook, with the note 'The implication sign is their only attempt at connecting statements and it is
used incorrectly: "P ⇒ Q" means "if P then Q", but we know the predicates are true. So we should use "thus",
"hence", "therefore" etc.'
Comment: @Szmagpie Some people use $\implies$ instead of "then", "therefore", etc. This is wrong. This isn't being done in the example you've given though.
Comment: I'd recommend speaking to the lecturer so that you are on the right page. You are effectively an employee of the lecturer and clarification of a task from your boss is normal in any workplace.
Comment: Are you sure you picked a good example? I'm as pedantic as they come and I see nothing wrong with a proof that looks like $A\implies B\implies C\implies D$.
Comment: @GitGud I guess the motivation of my question is to compare the answers '$A\therefore B $' and '$A\implies B $, and $A$ is assumed, $\therefore B$'; then if they are equivalent, I argue that the latter half is redundant given the context, and as a result, $A\implies B $ is acceptable
Comment: IMO all those possibilities are fine. But, if it's any help, "If $A\implies B$" is wrong.
Comment: The OP's said lecturer is against [the abuse of the implication symbol](https://math.stackexchange.com/a/3891518/21813), as described by @GitGud.
Answer: There's two ways to use $\Rightarrow$:

As notation for the relevant function $\{0,1\}^2 \rightarrow \{0,1\}$.
As a syntactic ingredient in proofs.

Your lecturer is saying she doesn't like (2), which is fair enough. I wouldn't go as far as to call it "wrong"; that's too strong of a word in this context.
Answer: I would not deduct any marks for the first answer.
What is an implication? It simply says "If A is true, then B is true". This is symbolically written as $A \implies B$.
When the implication is false, there is some object having property $B$ that does not have property $A$.
In the implication in question, it is clear that the author knows the context he is working in, and does not need another redundant statement to clarify to a well-read instructor that he is aware of the context. Therefore, there is nothing wrong with the logic of the question, I would detest a deduction of marks.

Correct use of the implication symbol


Eu quero o resultado de uma consulta e em SQL é simples...em PHP é confuso

Question: Quero apenas o resultado de um SELECT em php e eu não sei como pegar o resultado:
$descricao = mysqli_query($this->conexao, "Select descricao from tabela where codigo = 1");

var_dump ("$descricao");

Retorna um array e como eu consigo recuperar o campo = descricao?
Answer: $resultado = mysqli_query($this->conexao, "Select descricao from tabela where codigo = 1");
$linha = mysqli_fetch_assoc($resultado);
echo $linha['descricao'];

Comment: Preciso agora que você me ensine a dar medalhas...você mereceu todas as medalhas agora...viu?


correlation of single values

Question: This is anovice question, but I have been trying to understand it the whole day.
I have got three text types and three scores representing readability indices for each text type. How can I compute a correlation to check whether there is a significant difference between the scores depending on the text?
I have tried to do but didn't succeed, I got messages of this sort: one variable is constant (I cannot replicate it here anymore).
Answer: In order to attain a significant difference you need variability. In this example, if i am correct, you just have one instance of the index for each text type. I would interpret that as simply one is more readable than the other based on the single observations for each. You can't say much more.
Comment: Thank you. I thought I was missing something.

correlation of single values


Monic Legendre Polynomials

Question:
Write the polynomial as linear combinations of monic Legendre
  polynomials by using orthogonality to compute the coefficients.
$$t^4+t^2$$

My attempt:
Since I know that $q_4(t) = t^4-\frac{6t^2}{7}+\frac{3}{35}$ and $q_2(t)= t^2 -\frac{1}{3}$ then I must have a situation where the linear combinations looks like $$\alpha q_4(t) +\beta q_2(t) +\gamma q_0(t)$$where $\alpha , \beta, \gamma$ are constant coefficients. My question is how do I find those coefficients so that  $$\alpha q_4(t) +\beta q_2(t) +\gamma q_0(t)= t^4 +t^2$$
Comment: "My question is how do I find those coefficients": The question tells you how to find the coefficients.
Answer: You should actually write it out and gather like terms. $$\alpha q_4(t)+\beta q_2(t)+\gamma q_0(t)=\alpha t^4+\left(\beta-\frac67\alpha\right)t^2+\left(\frac3{35}\alpha-\frac13\beta+\gamma\right),$$ so we need $$\alpha=1,\quad\beta-\frac67\alpha=1,\quad\frac3{35}\alpha-\frac13\beta+\gamma=0.$$ Solve the system for $\alpha,\beta,\gamma.$
Comment: ah of course, thank you very much Cameron !!!

Monic Legendre Polynomials


Using ui-tinymce Directive in Another Directive

Question: I'm trying to use the ui-tinymce directive inside of another directive:
angular.module("risevision.widget.common.font-setting", ["ui.tinymce"])
  .directive("fontSetting", ["$templateCache", function ($templateCache) {
    return {
      restrict: "AE",
      template: $templateCache.get("_angular/font-setting/font-setting.html"),
      transclude: false,
      link: function ($scope, element, attrs) {
        $scope.tinymceOptions = {
          menubar: false,
          statusbar: false
        };
      }
    };
  }]);

And _angular/font-setting/font-setting.html:

    <textarea ui-tinymce="tinymceOptions" ng-model="tinymceModel"></textarea>

The TinyMCE editor shows up, but it's ignoring the configuration options I've set in $scope.tinymceOptions. That is, the menu bar and status bar still show.
Any thoughts as to why it's not working?
Thx.
Answer: I know I'm late to the party but I'm going to answer you in case someone has the same issue and can't find the answer.
TinyMce needs to be loaded only when the tinymceOptions variable has data so you need to wrap it in an ng-if:

    <textarea ui-tinymce="$parent.tinymceOptions" ng-model="$parent.tinymceModel"></textarea>

You can avoid using $parent (elements inside ng-if have their own scope) using controller as inside the directive if you are using Angular >1.4:
app.directive('someDirective', function () {
  return {
    scope: {},
    bindToController: {
      someObject: '=',
      ...
    },
    controllerAs: 'ctrl',
    controller: function () {
      var ctrl = this;
      ctrl.message = 'Object loaded.';
    },
    template: '
{{ctrl.message}}
'
  };
});


In swimming, is there a competitive advantage to being in one lane or another?

Question: Upon observing swimming competitions in the Olympics, it is not clear to me whether one of the eight lanes is more advantageous versus another. I've seen vague claims but nothing backed up with science.
In competitive swimming, is there an advantage to being in one lane or another? Furthermore, does the stroke (ie: breast, fly, freestyle, etc.) affect this effect?
Comment: Hard to answer objectively since there's the bias that faster swimmers in prelims are generally placed in center lanes for finals. From experience, swimming in center lanes is better than lanes against the wall because you can see other swimmers better (makes racing easier) and you don't get tossed around in the waves that bounce off the side wall.
Answer: The reason the fastest swimmer is placed in the center lanes is because it's believed to be the "coveted" lane.  This is due to the fact that from lanes 4-5, you have the greatest visibility of swimmers in the other lanes.  This is an advantage because in competitive races, athletes are known to perform better when they realize a competitor is close.
Also, if a swimmer breathes to the right or left, he will always be able to see half of the field, whereas swimmers in the edge lanes don't have this advantage.
Answer:
In competitive swimming, is there an advantage to being in one lane or another?

No. Lane 4 has always been believed to be the "fastest" lane, but there is no scientific evidence of such.

Michael Phelps on being in lane 8 for the 400m individual medley final in the 2012 Olympics:

"The only thing that matters is just getting a spot in. You
  can't win the gold medal from the morning."

If any given lane had a "competitive advantage," Phelps would most likely have had a different response.

World records, championships, and gold medals have been won from all lanes, especially lane 1 and lane 8.
German female swimmer Franziska van Almsick, swimming in lane 8, set a world record by winning the 200m freestyle with a time of 1:56.78 at the 1994 FINA World Championships. Her world record stood for eight years.
Australian male swimmer Kieren Perkins. swimming in lane 8, won gold in the 1500m freestyle with a time of 14:56.40 at the 1996 Olympics.
Chinese female swimmer Luo Xuejuan, swimming in lane 1, set an Olympic record by winning gold in the 100m breaststroke with a time of 1:06.64 at the 2004 Olympics. This was the third fastest time in history, 0.27 seconds off the world record.

Historically, world records, championships, and gold medals are won in middle lanes. This is because swimmers win their prelims, heats, etc.
The swimmers are placed in their respective lane based on their time. The fastest time will get lane 4 next round and the eighth-fastest time will get lane 8. Lane placement from fastest to eighth-fastest time: 4,5,3,6,2,7,1,8.
Comment: Fastest swimmers of preliminaries start in the middle lane, so any research will be highly biased.
Comment: Using a Michael Phelps quote and anecdotal race results is hardly an answer. The other answers explain *why* being in the center might be better.
Comment: I thing the point @HartleyBrody was trying to make is that the top athlete in any sport is almost always likely to state that they don't need any sort of advantage and will therefore denounce the existence of such.  Better anecdotal evidence would come from someone who consistently races against Michael and loses.  Not being at the pinnacle, s/he would be more likely to admit whether such an advantage exists.

Regardless, this was still a good answer with good references.
Comment: @HartleyBrody See [previous comment](http://sports.stackexchange.com/questions/1326/in-swimming-is-there-a-competitive-advantage-to-being-in-one-lane-or-another/1327?noredirect=1#comment1518_1327)..."anecdotal race results" and a quote from an experienced swimmer at the highest level reinforce said comment. Other comments and answers state environmental advantages (better vision, reflected waves, the fact the fastest swim in the middle) nicely, but doesn't explain these "anecdotal race results" in which these environmental advantages were overcome.
Comment: @Devin The Michael Phelps quote supplements, albeit marginally, the answer. The point made does not refute statistics, which include races outside of any Phelps was in.
Answer: It used to be that lanes 1 and 8 were considered slower due to reflected waves off the side, but modern pools have wave reduction systems so this is no longer the case.
Answer: Apart from the physical differences, swimmers may gain psychological advantages, and the lane in which this happens depends on the swimmer.
I have met professional swimmers who like to swim in lanes that are near the side, stating reasons which include being able to monitor all 7 other swimmers during 1 breath, as opposed to 2 breaths if the swimmer was near the middle lane.
However, that swimmer specialised in freestyle, and the opposite may be true for breaststrokers and butterflyers, who may see other swimmers more clearly in the middle lanes.
In the end, it all depends on the swimmer.
Comment: Welcome to SE.Sport. Can you please add any official references to your answer?
Comment: @Ale I forgot the exact quote, but I was training under Ashley Callus who stated it.


Tree search based Game AI: How to avoid AI 'wandering'/'procrastination' with sparse rewards?

Question: My game AI makes use of an algorithm that searches all possible future states based on the moves I can make (minimax / monte carlo esque). It evaluates these states using a scoring system, picks the highest scored final state and follows it.
This works well in most situations, but awfully when rewards are sparse. For example: there's a desirable collectable object that's 3 tiles to the right of me. The natural solution would be to go right->right->right.
But, my algorithm searches 6 turns deep. And it will will find many paths that eventually collect the object, including ones that take longer than 3 turns. It might for example find a path that's:   up->right->down->right->right->down, collecting the object on turn 5 instead.
Since in both cases, the final leaf nodes detect the object as collected, it doesn't naturally prefer one or the other. So, instead of going right on turn 1, it might go up, or down, or left. This behavior will be repeated exactly on the next turn, so that it basically ends up dancing randomly in front of the collectable object, only luck will make it step on it.
That's clearly suboptimal and I want to fix it, but have run out of ideas how to handle this appropriately. Are there any solutions for this issue or is there any theoretical work that deals with handling this issue?
Solutions I've tried:

Make it value object collection more on earlier turns. While this works, to beat evaluator 'noise', the difference between turns must be quite high. Turn 1 must be rated higher than 2, turn 2 rated higher than 3, etc. The difference between turn 1 and 6 needs to be so high that it ends up making the behavior extremely greedy, which is not desirable in most situations. In an environment with multiple objects, it might end up choosing the path that grabs an object on turn 1, instead of the much better path that can grab objects on turn 5 and 6.
Assign the object as a target and value distance to it. If not done on a turn to turn basis, the original problem persists. If done on a turn to turn basis, the difference in importance required per turn once again makes it too greedy. This method also decreases flexibility and causes other issues. Target selection is not trivial and kind of ruins the point of a minimax style algorithm
Going much deeper in my searches so that it can always find a second object. This would cost so much computing power that I'd have to make concessions, like pruning paths much more aggressively. If I do so, I'll be back at the same problem since I won't know how to get it to prefer pruning the 5 turn version over the 3 turn version.
Give extra value to the plans laid out last turn. If it can at least follow the suboptimal path, there wouldn't be as much of an issue. Unfortunately, this once again has to be a pretty strong effect for it to work reliably, making it follow sub-optimal paths in all scenarios, hurting overall performance.
Answer: When weighting the outcome of the last step of your move, are you calculating in the number of moves needed to pick up an object?
I presume, you are quantifying each step of your move actions, giving a +1 if the step results in the picking up of an object. This means that in 3 steps, I can pick up the object with your above example, and get a +1 state of the play field, but I can also do this with 4-5-6-x steps, getting the same +1 state. If only a single object is reachable in the depth you are searching, your algorithm will likely select one of the random +1 states, giving you the above behaviour.
This could be solved, by quantifying with a negative score, each of the moves the AI must make. Thus, getting the object in 3 moves, will result in a -2, but getting the object in 6 moves, will result in -5. This way, the AI will clearly know, that it is preferable to get the object in the least amount of moves, ie, 3.


Windows Server 2012 R2 Task Scheduler access denied (0x80070005), but command works manually in shell

Question: I have the following problem. On our Windows Server 2012 R2 is a scheduled task which calls a batch file, which in return calls vb scripts.
Those scripts just download 5 pictures and stores them into a folder under a specified name. If I call the bat directly via command line, it works like a charm but with the scheduler I get following information.
It saves the files in the same partition where the script is located. Just in another folder where the user also has access, because he is added to the admin group.
Event Information: Event-ID: 201  ResultCode 2147943645 successfully completed

The ResultCode seems to match the following access denied message.
Result of the last execution: Access denied 0x80070005

My researches lead me to try some config changes.

Run the task in the Schedule with highes rivileges -> same error
Change the security for %windir%/system32/cmd.exe -> user already in
the admin group
Remove " from start in -> there is nothing, also    adding the
folder, where the script is located doesn't change    anything

Thank you in advance for any hint, question, information to this problem.
Comment: Check this similar thread: https://stackoverflow.com/questions/10187292/issue-with-task-scheduler-launching-a-task
Answer: I think that should check Task Security Context of your schedulled task.
Do you have store user's password in the task?
The error can be caused by lack of network access.
Comment: I don't know what you mean, I'm new at the company and they just copied the files from a 2003 Server onto a 2012r2 Server and added the task like in the old Server. Also I worked with Linux in the past and the persons knew this. Therefore I'm really dumb when i comes to Windows Securtiy Stuff. We think it coul dbe a problem with the UAC of the Server
Answer: You most likely need to grant the "Log on as batch job" system privilege to the service account that you are using to run the scheduled task.
(You are not running the scheduled task with your own personal credentials, right?)
From TechNet's description:

Allows a user to be logged on by means of a batch-queue facility. For
  example, when a user submits a job by means of the task scheduler, the
  task scheduler logs that user on as a batch user rather than as an
  interactive user.
By default, only the LocalSystem account has the privilege to be
  logged on as a batch job.

This can be set in a domain GPO or in a local GPO, both in the following location:
Computer Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment

To confirm the source of the "Access denied" failure, you should check the Windows Security log in Event Viewer. Filter the log to only show Audit Failures, and then search for the last time that you attempted to run your scheduled task.
Comment: The Adminstration-Group is added there and the User, I'm working with, is in the Administation-Group


Prove that the radius of $(ABC)$ is smaller than the radius of $Max[(ADC),(ABD),(CBD)]$.

Question:
Given $3$ points $A,B,C$ and a third point $D$ lying outside the circumcircle $(ABC)$. Say $ABCD$ is a convex quadrilateral. Prove that $(BDC)$ is larger than $(ABC)$.

Moreover, here is another problem.

Given $3$ points $A,B,C$ and a third point $D$ lying insider the circumcircle $(ABC)$ such that $ABDC$ is a convex quadrilateral. Prove that $(DBC)$ is larger than $(ABC)$.
Comment: It's very easy by the extended law of sines.
Answer: Hint: Apply the extended law of sines on $\triangle ABC$ and $\triangle BCD$ with side $BC$ in both triangles. Then note that if $D$ is inside $(ABC)$, $\angle D+\angle A>180$ and it's converse.
Comment: thankyou, I got it.


Calculating rollsum and Delt with offsets

Question: I have df a which has two columns viz; PC and Price as given below
dput(a)

structure(list(PC = c(0, -0.009, 0, -0.008, 0.003, 0.008, -0.017,
0.032, 0.062, -0.02), Price = c(111.449554, 110.495506, 110.476242,
109.560745, 109.859482, 110.68824, 108.780159, 112.239769, 119.216805,
116.826897)), class = "data.frame", row.names = c(NA, -10L))

I have lookbackPeriod = 2 which means I have to calculate rollsum of a$PC column for every nth lookbackPeriod and
this I could calculate by
 b <- data.frame(MScore = rollsum(a$PC,k=lookbackPeriod ))

I also have holdPeriod = 2 which means I have to calculate percentage in price for every nth holdPeriod but nth holdPeriod period starts where the nth lookbackPeriod ends
example if this was a then for the rollsum it will consider values in Yellow but to calculate percentage change it will consider value in orange and green.

So final output in B would look line this for the given input
The output will have nrow(a) - lookbackPeriod + 1 - holdPeriod observations

This kind of gives me the results but it is coercing LHS to list at the last line and first two records of Delt function result have NA
b <- data.frame(MScore = rollsum(a$PC,k=lookbackPeriod ))
b <- b[1:(nrow(b)-holdPeriod+1),]
a <- a[lookbackPeriod:nrow(a),]
b$PChg <- as.data.frame( Delt(a$Price,k=holdPeriod))

Answer: Use rollapply with a width equal to the sum of the periods left aligning the results using the appropriate functions:
library(zoo)

k1 <- lookbackPeriod
k <- k1 + holdPeriod
roll <- function(...) rollapply(..., fill = NA, align = "left")
transform(a, MScore = roll(PC, k, function(x) sum(x[1:k1])),
             PChg = roll(Price, k, function(x) x[k]/x[k1]-1))

giving:
       PC    Price MScore         PChg
1   0.000 111.4496 -0.009 -0.008459720
2  -0.009 110.4955 -0.009 -0.005582739
3   0.000 110.4762 -0.008  0.010291049
4  -0.008 109.5607 -0.005 -0.009824578
5   0.003 109.8595  0.011  0.014017108
6   0.008 110.6882 -0.009  0.095942551
7  -0.017 108.7802  0.015  0.040869008
8   0.032 112.2398     NA           NA
9   0.062 119.2168     NA           NA
10 -0.020 116.8269     NA           NA

This variation would also work:
f <- function(x) c(MScore = sum(x[1:k1, 1]), PChg = x[k, 2]/x[k1, 2] - 1)
cbind(a, rollapply(a, k, f, fill = NA, align = "left", by.column = FALSE))


Why does form ID get displayed to drupal_set_message?

Question: I'm upgrading from 6 to 7 (thankless task!) and Ive noticed that in the admin section the name of any form that is on the page seems to get output to drupal_set_message (it appears in the green box) I thought this to be unusual but possibly deliberate on the part of the module author. However, in my custom module I have a form and when ever I go to the page the name of the form appears in the green status box.
Can anyone shed any light onto why this may be happening?
Comment: "Screen or it didn't happen" ;) But no, really, it never happened to me and I'd love to see how it looks. Maybe it would help us guess why. Also, can you `grep` your code?
Answer: You may be having hook_form_alter(&$form,&$form_state,$form_id) in your code
possible code in your custom code will be
<code>function hook_form_alter(&$form,&$form_state,$form_id) {
//just remove the below line to disable the message
drupal_set_message($form_id);

}
</code>
Comment: I cant believe I didnt spot this! you are indeed correct. I put it in my hook_form_alter when I was debugging something else and then completely forgot about it! good call.


Is a translation a orthogonal transformation?

Question: I'm trying to prove a translation preserves inner products.
I know intuitively that a translation preserves inner products since they should preserve distances. However I couldn't prove it formally:
If $A:\mathbb R^3\to \mathbb R^3$ defined by $A(w)=w+v$ is a translation by a vector $v$. I couldn't prove that $\langle A(w_1),A(w_2)\rangle=\langle w_1,w_2\rangle$.
Comment: A translation indeed preserves the distance (= the norm of the difference of two vectors), but not the norm of a vector itself.
Comment: @G.Sassatelli yeah, I got it. Thank you
Answer: That's because it's wrong: $\langle A(0), A(0)\rangle = \langle v, v\rangle = \| v\|^2 \neq 0 = \langle 0, 0\rangle$. You can find many other counterexamples.
Observe that it's still an isometry (but not a linear one!) with respect to the norm:
$ \| A(w_1) - A(w_2)\| = \| w_1 + v - (w_2 + v)\| = \| w_1 - w_2\|$
Comment: Thank you. That's weird! Translation is supposed to be an isometry.
Comment: @user42912 It's an isometry in the sense of metric spaces, but not in the sense of inner-product spaces.
Comment: The problem is that it's not linear.
Comment: Thank you again. I think I got it.


AngularJS variable to html  attribute

Question: I want to set part of an url of an html <object> tag with an angular variable, but I get a lot of error messages in the console, because the presented string looks like
http://...../%7B%7Bvarname%7B%7B/....

I had the same problem with the  tag, but there I could use the ng-src directive. I guess I need to write my own directive, but what are the things I need to look out for?
<object type="application/x-shockwave-flash" height="378" width="620" id="live_embed_player_flash" data="http://...?chan={{varname}}" bgcolor="#000000">
    ...
    <param name="flashvars" value="hostname=...&chan={{varname}}" />
</object>

Answer: Try this:
<object ... data="{{address}}">

Controller:
$scope.varname = "something";
$scope.address = "http://...?chan=" + $scope.varname;

Fiddle
Comment: Thanks, but should this work? Because for me it does exactly what I expected, nothings gets "interpreted". The final html output includes {{'http://...?chan='+varname}} and of course the error message stays the same.
Comment: @KenavR `varname` should be a scope model. Take a look at my update.
Comment: @KenavR Try storing the entire address in a scope variable and then using that inside the HTML.
Comment: It always was a $scope variable and I can correctly output it with {{varname}}, but as an attribute value it doesn't work. It does get correctly "interpreted" eventually, but the browser is faster fetching the markup, than angular is with replacing the {{variables}}. (http://docs.angularjs.org/api/ng.directive:ngSrc) I guess I need to dig more into ngSrc and go on with my search.
Comment: Did you try with my latest update? By having the entire address in a scope variable instead of concatenating in the HTML?
Comment: Yes I did, the error message changed, but it didn't work either.
Comment: @KenavR I have added a fiddle which works regardless of the approach used! :D
Comment: Thanks, I changed your fiddle example with my resources to show you that it doesn't work, but ... it does work, I am very surprised. I thought the reason was that I use Angular 1.1.5 and you 1.2.2, but regardless it works. I need to take a deeper look into the rest of my code, I may be back later.

AngularJS variable to html  attribute


I am trying to delete data from table by using forign key in laravel

Question: I am trying to delete data by using a foreign key but unfortunately not deleting from FreeDownloadFiles tables how can I delete data from this table please help me thanks.
Note: data is  successfully deleting from  freedownload table but not deleting from FreeDownloadFiles tables
free_download table

id  |  name | images

free_download_files table

 id | free_download_id | images

Controller
    public function destroy(Request $request)
    {
        $freedownload = FreeDownload::findOrFail($request->deleteId);
        $freedownloadfiles = FreeDownloadFiles::where('free_download_id', $request->deleteId)->get();

        foreach ($freedownloadfiles as $key => $value) {

            $delete = $value->delete();
        }

        // apply your conditional check here
        if (false) {
            $response['error'] = 'This FreeDownload has something assigned to it.';
            return response()->json($response, 409);
        } else {
            Storage::disk('yourstitchart')->delete($freedownload->icon);
            $response = $freedownload->delete();
            return response()->json($response, 200);
        }
    }

Comment: No need the loop, do that with one line code `FreeDownloadFiles::where('free_download_id', $request->deleteId)->delete();`
Comment: Do you have a relation between the 2 models?
Comment: yes I have a model relationship
Comment: data is successfully deleting from db but can you please tell me how can i  delete images from the storage?
Comment: @zubairmalik you can do that like this way `Storage::delete('file.jpg');` https://laravel.com/docs/8.x/filesystem#deleting-files
Answer: You can automate the deleting of the images/files associated with the FreeDownloadFiles records by hooking into the model deleting event in the FreeDownloadFiles model definition.

class FreeDownloadFile extends Model
{
     protected static function booted()
     {
        static::deleting(function ($record) {

            /**
             * if images field contains string with comma separated paths to image files
             * convert to array explode(',', $record->images)
             * replace comma with whatever separator is used eg ;
             */
            foreach(explode(',', $record->images) as $image) {
                Storage::delete($image);
            }
        });
     }
}

Similarly to automate deleting of FreeDownloadFiles associated with a FreeDownload we can hook into the deleting event for FreeDownload

class FreeDownload extends Model
{
   protected static function booted()
     {
        static::deleting(function ($record) {

            //can also use higher order magic
            //$record->freeDownloadFiles->each->delete();

            foreach($record->freeDownloadFiles as $file) {
                $file->delete();
            }
        });
     }
}

Then the controller method can become simple as
public function destroy(Request $request)
    {
        $freedownload = FreeDownload::findOrFail($request->deleteId);

        // apply your conditional check here
        if (false) {
            $response['error'] = 'This FreeDownload has something assigned to it.';
            return response()->json($response, 409);
        } else {
            Storage::disk('yourstitchart')->delete($freedownload->icon);
            $response = $freedownload->delete();
            return response()->json($response, 200);
        }
    }

Comment: Donkarnash thanks for helping but unfortunately I am getting an error on the FreeDownloadFile model please check the error in this link thanks. https://imageupload.io/GdlGt6PZXa.i
Comment: What is stored in the `images` column for `FreeDownloadFiles` record? What's the column type?
Comment: multi images storing in images column for FreeDownloadFiles record and column type is text
Comment: Is it comma separated paths to image files as text? Can you please post the result of `dd($freeDownloadFile->images)`;
Comment: If the `$freeDownloadFiles->images` contain comma separated string like 'path/to/image1, path/to/image2, path/to/image3' then it needs to be converted to array before being fed to foreach loop
Comment: @zubairmalik Have updated the answer to convert comma separated list of multiple paths to images for consumption in foreach loop using `explode(',', $record->images)`. Have a look and let me know. Also pls post output of `dd($freeDownloadFile->images)` if it doesn't work.


npm-install command not working in an angular 7 project

Question: I downloaded a project from git, which is written in angular 7. I just need to run command npm install to run it. But its showing the following error.
npm ERR! code E404
npm ERR! 404 Not Found: firstname.lastname@example.com

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/abhiz/.npm/_logs/2019-04-24T07_30_14_888Z-debug.log

The following is a small part of the detailed error report from the log file(/home/abhiz/.npm/_logs/2019-04-24T07_30_14_888Z-debug.log).
    ... ... ...
    ... ... ...
    23 silly saveTree | `-- firstname.lastname@example.com
    23 silly saveTree |   `-- firstname.lastname@example.com
    23 silly saveTree `-- firstname.lastname@example.com
    24 verbose stack Error: 404 Not Found: firstname.lastname@example.com
    24 verbose stack     at fetch.then.res (/home/abhiz/.nvm/versions/node/v10.0.0/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/fetch.js:42:19)
    24 verbose stack     at tryCatcher (/home/abhiz/.nvm/versions/node/v10.0.0/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
    24 verbose stack     at Promise._settlePromiseFromHandler (/home/abhiz/.nvm/versions/node/v10.0.0/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:512:31)
    24 verbose stack     at Promise._settlePromise (/home/abhiz/.nvm/versions/node/v10.0.0/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:569:18)
    24 verbose stack     at Promise._settlePromise0 (/home/abhiz/.nvm/versions/node/v10.0.0/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:614:10)
    24 verbose stack     at Promise._settlePromises (/home/abhiz/.nvm/versions/node/v10.0.0/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:693:18)
    24 verbose stack     at Async._drainQueue (/home/abhiz/.nvm/versions/node/v10.0.0/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:133:16)
    24 verbose stack     at Async._drainQueues (/home/abhiz/.nvm/versions/node/v10.0.0/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:143:10)
    24 verbose stack     at Immediate.Async.drainQueues [as _onImmediate] (/home/abhiz/.nvm/versions/node/v10.0.0/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:17:14)
    24 verbose stack     at runCallback (timers.js:696:18)
    24 verbose stack     at tryOnImmediate (timers.js:667:5)
    24 verbose stack     at processImmediate (timers.js:649:5)
    25 verbose cwd /home/abhiz/WorkSpace/TreadFormAnalysis
    26 verbose Linux 4.15.0-47-generic
    27 verbose argv "/home/abhiz/.nvm/versions/node/v10.0.0/bin/node" "/home/abhiz/.nvm/versions/node/v10.0.0/bin/npm" "install"
    28 verbose node v10.0.0
    29 verbose npm  v6.4.1
    30 error code E404
    31 error 404 Not Found: email@example.com
    32 verbose exit [ 1, true ]

Only for this project npm install is not working. I have tried running this command in another angular 7 project and it run successfully.
 What is " email@example.com " and how to resolve this error?
These informations may be needed.
My system's npm -version is 6.4.1 and node version is 10.0.In this project web socket is used.
Package.json file
        {
      "name": "app-demo",
      "version": "0.0.0",
      "scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build",
        "test": "ng test",
        "lint": "ng lint",
        "e2e": "ng e2e"
      },
      "private": true,
      "dependencies": {
        "@angular/animations": "^6.1.3",
        "@angular/cdk": "^6.4.6",
        "@angular/common": "^6.0.0",
        "@angular/compiler": "^6.0.0",
        "@angular/core": "^6.0.0",
        "@angular/forms": "^6.0.0",
        "@angular/http": "^6.0.0",
        "@angular/material": "^6.4.6",
        "@angular/platform-browser": "^6.0.0",
        "@angular/platform-browser-dynamic": "^6.0.0",
        "@angular/router": "^6.0.0",
        "@ng-bootstrap/ng-bootstrap": "^3.2.0",
        "@ngx-loading-bar/core": "^4.1.1",
        "@ngx-loading-bar/http-client": "^4.0.0",
        "angular-svg-round-progressbar": "^2.0.0",
        "angular2-cookie": "^1.2.6",
        "angular2-toaster": "^6.1.0",
        "bootstrap": "^3.3.7",
        "core-js": "^2.5.4",
        "file-saver": "^2.0.0",
        "jquery": "^3.3.1",
        "jwt-decode": "^2.2.0",
        "lodash": "^4.17.11",
        "net": "1.0.2",
        "ng-connection-service": "^1.0.4",
        "ngx-bootstrap": "^3.1.4",
        "ngx-cookie-service": "^1.0.10",
        "ngx-spinner": "^6.1.2",
        "ngx-toggle-switch": "^2.0.5",
        "rxjs": "^6.2.2",
        "sockjs-client": "^1.3.0",
        "stompjs": "^2.3.3",
        "xlsx": "^0.14.1",
        "zone.js": "^0.8.26"
      },
      "devDependencies": {
        "@angular-devkit/build-angular": "^0.6.8",
        "@angular/cli": "~6.0.0",
        "@angular/compiler-cli": "^6.0.0",
        "@angular/language-service": "^6.0.0",
        "@types/jasmine": "~2.8.6",
        "@types/jasminewd2": "~2.0.3",
        "@types/node": "~8.9.4",
        "codelyzer": "~4.2.1",
        "jasmine-core": "~2.99.1",
        "jasmine-spec-reporter": "~4.2.1",
        "karma": "^3.0.0",
        "karma-chrome-launcher": "~2.2.0",
        "karma-coverage-istanbul-reporter": "~1.4.2",
        "karma-jasmine": "~1.1.1",
        "karma-jasmine-html-reporter": "^0.2.2",
        "protractor": "^5.4.1",
        "ts-node": "~5.0.1",
        "tslint": "~5.9.1",
        "typescript": "~2.7.2",
        "net": "1.0.2",
        "angular-svg-round-progressbar": "2.0.0",
        "ng-connection-monitor": "0.0.0"
      }
    }

Comment: @Abhiz well npm install is installing your dependencies defined in the package.json file. Different projects have different dependencies. Here 1 of your dependencies are failing. Can you show your package.json file? - it is rather impossible to debug without. It tries to install version 0.0.0 of ng-connection-monitior - this seems pretty odd.
Comment: Are you behind proxy?
Comment: no. And this command is working in other angular projects
Comment: yes ,  sure. I ll edit my question
Answer: This is because the project you downloaded requires the ng-connection-monitor library as a build dependency and npm was unable to find this library when you did an npm install. Looking on npmjs for ng-connection-monitor returns no results so this would explain your 404 error:

404 Not Found: email@example.com

This leads me to believe that this module is either a private package or has since been deleted off of npmjs... so you will be unable to download this required build dependency as listed within your package.json file. Alternatively, there is however a ng-connection-service module listed on npmjs.
Perhaps you could proceed as follows:
Try removing this dependency from your package.json file and see if your project still builds and works appropriately. Alternatively, maybe try to get in contact with the author of the GIT repo you've cloned and see what the deal is with this module? As previously mentioned, this module may now be deprecated and has been replaced with another module so it was removed off of npmjs or it's a private module which isn't made publicly available on npmjs.
Hopefully that helps!
Comment: Thanks for such a brief answer. It helped.
Comment: Glad it helped, please consider accepting my answer


What is the exact coefficient of $x^{12}$ in $(2+x^3+x^6)^{10}$?

Question: What is the coefficient of $x^{12}$ in $(2+x^3+x^6)^{10}$?
I figure you need to pick $x^3$ 4 times so $C(10,4)$...but what happens with the other numbers/variables???
Can someone explain to me how this is done properly?
Thanks.
EDIT:
$(x + y)^n = C(n,k) \cdot x^{n-k} \cdot y^k$
EX: Find the term for $x^5$ in $(5-2x)^8$
Answer: $C(8,5) \cdot (-2)^5 \cdot 5^3$
How can I use this info to solve a polynomial based question such as the featured?
 Answer:
To sum up all information provided by everyone (Thanks!!!):
$(C(10,4) * 2^6) + (C(10,2) * 2^8) + (C(10,1) * C(9,2) + 2^7) = 71040 $
Comment: Are you familiar with multinomial expansion?
Comment: You could also pick $x^6$ twice and then 2 eight times.
Comment: $2^{8} * x^6 * x^6 = 2^{8} x^{12}$
Comment: @SpamIAm Doesn't that add up to 12? n = 10
Comment: My mistake, I meant pick 2 eight times.
Comment: How about in combinational terms? If i wrote that as my answer it would be marked incorrect.  I'm looking for an answer such as $C(10,4) * x^6 * 2^4$ but I'm pretty sure this is incorrect...
Comment: See my edit example
Answer: Hint 1: $x^{12} = x^6 x^6 = x^3 x^3  x^3 x^3 = x^3 x^3 x^6$
How many ways to pick $x^6 x^6$? Everything that's not an $x$ term is a multiplier of $2$. This would be $2^8 {10 \choose 2}$ for a total of $10$ elements.
For four $x^3$ there would be $10 \choose 4$ ways to pick.
Hint 2: For $x^3 x^3 x^6$ there are $10$ ways to choose the $x^6$, $10-1 \choose 2$ ways to pick  $x^3$.
Hopefully you can figure out the final sum of the three cases from here.
Comment: Would this be identical to $C(10,4) * 2^6$?
Comment: @user134788 no.
Comment: Why not? I'm picking 4 of x^3 and 6 of 2... Would that not result in the same answer?
Comment: @user134788 There are multiple ways of adding up to 12. See the first line.
Comment: Right, so when picking four $x^3$, I would then pick 2 how many times? 6? That also adds up to 10.
Comment: @user134788 yes, for a total of 10 elements.
Comment: Ah okay, makes sense now.  Above you said no when I asked if it would result in the same answer lol. Thanks!
Answer: You can reach $x^{12}$ in the product from $x^6x^6\cdot2\cdot2\cdot2\cdot2\cdot2\cdot2\cdot2\cdot2$, which can be done in $\binom{10}{2}$ ways with a coefficient of $2^8$.
Or you can reach it with $x^6x^3x^3\cdot2\cdot2\cdot2\cdot2\cdot2\cdot2\cdot2$, which can be done in $\binom{10}{1}\binom{9}{2}$ ways with a coefficient of $2^7$.
Or you can reach it with $x^3x^3x^3x^3\cdot2\cdot2\cdot2\cdot2\cdot2\cdot2$, which can be done in $\binom{10}{4}$ ways with a coefficient of $2^6$.
$$\begin{align}2^8\binom{10}{2}+2^7\binom{10}{1}\binom{9}{2}+2^6\binom{10}{4}&=64(4\cdot45+2\cdot10\cdot36+210)\\
&=64(1110)\\
&=71040
\end{align}$$
Answer: Hint 1 Let $y=x^3$.
Hint 2  The coefficient for $y^4$ in $P(y)$ can be calculated by derivating $P(y)$ four times.
Comment: @user134788: No, that's not what N.S. said at all. Take the fourth derivative of $P(y) = (y^2 + y + 2)^{10}$. The constant term is 24 times the coefficient of $y^4$ (which is the coefficient of $x^{12}$ in the original.)
Comment: What is P(y)?...the power set?
Comment: @user134788 any polynomial in $y$ ;)
Comment: Set $P(x) = (2 + x^3 + x^6)^{10}$. Using the suggested substitution, we have $P(y) = (y^2 + y + 2)^{10}$.
Comment: It seems like you're just telling me how to expand the original equation manually and look at the coefficient.  I'm trying to skip all those steps and use the binomial theorum.  See my edit.
Comment: @Kundor fourth derivative as in calculus?
Comment: @user134788: Yes, fourth derivative as in calculus. Recall that $P(y) = P(0) + P'(0) y + P''(0) y^2/2! + P^{(3)}(0) y^3/3! + P^{(4)}(0)y^4/4! + \dots$, so the coefficient of $y^4$ is $4! P^{(4)}(0)$, i.e. $24$ times the fourth deriviative of $P(y)$, evaluated at $0$. This is not necessarily a convenient thing to calculate, however, so I personally wouldn't recommend this approach.
Answer: In combinatorial terms, you're looking for the number of partitions of $12$ that use only $0, 3$, and $6$ and have $10$ parts.  You then weight these partitions by multinomial coefficients.  There are $3$ such partitions:
\begin{align*}
12 &= 6 + 6 + 0 + \cdots + 0\\
&= 6 + 3 + 3 + 0 + \cdots + 0\\
&= 3 + 3 + 3 + 3 + 0 + \cdots + 0 \, .
\end{align*}
These partitions correspond to the terms
\begin{align*}
x^6 * x^6 * 2^8 &= 2^8 x^{12}\\
x^6 * x^3 * x^3 * 2^7 &= 2^7 x^{12}\\
x^3 * x^3 * x^3 * x^3 * 2^6 &= 2^6 x^{12} \, .
\end{align*}
Now we observe that the number of ways each of these can be chosen is $\binom{10}{8,2}$, $\binom{10}{7,2,1}$, $\binom{10}{6,4}$ ways.  So it looks to me that the coefficient of $x^{12}$ is
$$
\binom{10}{8,2} 2^8 + \binom{10}{7,2,1} 2^7 + \binom{10}{6,4} 2^6 \, .
$$
Answer: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left( #1 \right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}
 \newcommand{\wt}[1]{\widetilde{#1}}$
\begin{align}
\pars{2 + x^{3} + x^{6}}^{10}&=
\sum_{n_{1},n_{2},n_{3} = 0 \atop {\vphantom{\Large A}n_{1} + n_{2} + n_{3} = 10}}
{10! \over n_{1}!\,n_{2}!\,n_{3}!}\,2^{n_{1}}\pars{x^{3}}^{n_{2}}\pars{x^{6}}^{n_{3}}
\\[3mm]&=
\sum_{n_{1},n_{2},n_{3} = 0 \atop {\vphantom{\Large A}n_{1} + n_{2} + n_{3} = 10}}
{10! \over n_{1}!\,n_{2}!\,n_{3}!}\,2^{n_{1}}x^{3n_{2} + 6n_{3}}
\end{align}

$$
x^{12}\mbox{- Coeff.}=\left.%
\sum_{n_{1},n_{2},n_{3} = 0 \atop {\vphantom{\Large A}n_{1} + n_{2} + n_{3} = 10}}
{10! \over n_{1}!\,n_{2}!\,n_{3}!}\,2^{n_{1}}\right\vert_{3n_{2} + 6n_{3} = 12}
$$

Since $n_{1} + n_{2} + n_{3} = 10$ and $3n_{2} + 6n_{3} = 12$ we'll have:
$$
\pars{~n_{2} = -2n_{1} + 16 \geq 0\quad\imp\quad n_{1} \leq 8~}
\ \mbox{and}\
\pars{~n_{3} = n_{1} - 6 \geq 0\quad\imp\quad n_{1} \geq 6~}
$$

\begin{align}
\color{#00f}{\large x^{12}\mbox{- Coeff.}}&=\sum_{n_{1} = 6}^{8}
{10! \over n_{1}!\,\pars{16 - 2n_{1}}!\,\pars{n_{1} - 6}!}\,2^{n_{1}}
\\[3mm]&={10! \over 6!\,4!\,0!}\,2^{6}+
{10! \over 7!\,2!\,1!}\,2^{7}+
{10! \over 8!\,0!\,2!}\,2^{8}
\\[3mm]&=2^{6}\pars{10\times 3\times 7 + 10\times 9\times 4\times 2 + 45\times 4}
=2^{6}\pars{210 + 720 + 180}
\\[3mm]&= 64\times 1110 = \color{#00f}{\large 71040}
\end{align}


Why is Views Nivo Slideshow block only displaying to logged in users?

Question: I'm using the Views Nivo Slider module to create a slideshow for a couple of different sites I'm creating. The slideshow works perfectly if a user is logged in, but the block doesn't display at all when not logged in (the HTML for the block isn't even there). I thought it might be a permissions issue, so I tried giving anonymous users every permission possible, and still no luck. Any idea what might be causing this? Could it be something in my view?
Comment: Did you check the permissions for your view (on the view itself)?  If you set the permissions to a role on the view, even giving anonymous users permissions would not allow them to access the view unless they had the role.
Comment: I checked, but the access is set to Unrestricted.
Comment: Have you tried first clearing cache data and then giving permission ?
Comment: Is anonym able to view content or entities from your view?
Answer: I have some problems with blocks before and I always check the following, it has solved my problems so far.

Check your block permission.
Verify the block is assigned to a valid region setting in your template.
Rebuild the node permissions in admin/reports/status. Before doing this, backup your database and clear the cache.
Verify the access permission used from the view is view published content.

When I am working with views, I make sure the theme developer module is not enabled. I disable it, and then I clear the cache.
Answer: Check the advanced settings, and try to disable views sql rewriting.


Songs Memorization

Question: How do I improve my song memory? I've realized that I'm poor in cramming songs. I only sing one or two lines in most of the songs and it hinders making fun as I play.
Comment: Is it the tune, or the words that evade you?
Comment: I'm poor majorly in words.
Answer: Memorizing music is achieved through repetition: by listening to a recorded version of the piece and by playing and/or singing that piece over and over again.
Answer: You say it's the lyrics that hang you up.  Option 1: learn to scat, and then the words won't matter.  Option 2: memorize the lyrics by writing them down.  Each time you write them down, you'll have fewer gaps.  Also, try to picture a visual story to help you with the memorization.

Songs Memorization


Problema em quebrar uma String

Question: Tenho uma string que é concatenada dentro de um loop, queria que para cada loop fosse criado uma nova linha com os valores concatenados.
Segue o código que estou usando:
mensagem ="";

for (int i = 0; i < titulosReceber.Rows.Count; i++)
    mensagem += "Titulos: " + (titulosReceber[i].TitId).ToString() +
    "FormaPagto: " + (titulosReceber[i].NomeMeioPagamento).ToString() +
    "Valor: " + (titulosReceber[i].Valor).ToString() + " Dt. Venc: " +
    (titulosReceber[i].dVenc)+"\n" ;

SalvarHistorico("Ação Faturar da Saida, gerado(s) o(s)"+ mensagem,
Historico.enumHistoricoTipo.SAI_Faturar, this.Saida[0].Id, IdOperador );

A string é concatenada, mas não quebra a linha.
Comment: Onde isto está sendo usado? A quebra de linha está presente sim, não tem como não estar. Mas dependendo de onde for usado, ela não aparecerá, porque `\n` não funciona em todos contextos, como o HTML, por exemplo. Quebra de linha em HTML é ``.
Comment: Vc quer que o `SalvarHistorico` seja chamado a cada iteração?
Comment: Andre, se poder só quebra a string já me ajuda bastante.
Comment: O que @bigown falou está correto, `\n` não funciona em páginas web, vc deverá dá um replace `\n` por ``, deve ter alguns métodos/mecanismo para executar esse *replace*
Comment: Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: A quebra de linha está ocorrendo normalmente através do \n não tem como não ter segundo este código.
Seu problema está em outro lugar. Quando você vai apresentar esta string gerada, você não está vendo o texto quebrar pela forma como o mecanismo que fará a apresentação manipula isto. Ou seja, quando você imprime, o \n não fica visível como uma quebra de linha. Como você indica usar o ASP.NET, deve estar tentando mostrar isto em uma página HTML, cuja quebra de linha é representada por
. Então ou você muda neste código para usar este texto como quebra ou então quando for montar a página converte o \n para
.
Coloquei no GitHub para referência futura.
Answer: StringBuilder mensagem = new StringBuilder();

for (int i = 0; i < titulosReceber.Rows.Count; i++)
    mensagem.Append(string.Format("
Titulos: {0} Forma Pagto: :{1} Valor :{2} Dt. Venc :{3}", titulosReceber[i].TitId, titulosReceber[i].NomeMeioPagamento, titulosReceber[i].Valor, titulosReceber[i].dVenc.ToString("dd/MM/yyyy")).ToString());

    SalvarHistorico("Ação Faturar da Saida, gerado(s) o(s)"+ mensagem, Historico.enumHistoricoTipo.SAI_Faturar, this.Saida[0].Id, IdOperador );

Answer: Onde você está exibindo esta mensagem gerada? Se for em um contexto HTML, você pode utilizar mensagem.Replace(Environment.NewLine, "
") antes de exibir que deve funcionar. Outra opção seria ao invés de colocar o \n colocar direto o
.
Comment: Ola Richard dias, obrigado pela ajuda, já conseguir resolver a questão segue o código.
Comment: Marque uma resposta como correta então

Problema em quebrar uma String


Difference between Thomanns "Alto/Baritone horn", "tenor horn", "baritone" and euphonium?

Question: Apparently BAritones and Alto/Baritone horns are sold as different things.
Also, I thought alto horns were called so in america and tenor horns in UK (or viceversa, cant remember), but it turns out that alto and tenor horns are 2 different things (at least sold in Thomann) and Baritones and Baritone horns as well seem to be 2 different instrumnts.
I know however the difference between a euphonium and a baritone (horn(?)).
I am researching different brass instruments and when seeing them in Thomann I get a mess in my head.
So, can anybody help me clarify the difference between all thse instruments. I guess its a range things but I thought french horns had the "same" range as a tenor trobbone but then I see there are tenor horns as well and maybe they have the same range as tenor trombones?
Comment: A lot of what you need to know is covered here: https://music.stackexchange.com/questions/33715/is-a-bb-baritone-and-a-baritone-horn-the-same-instrument/80047#80047 and here: https://music.stackexchange.com/questions/10370/difference-between-baritone-and-euphonium/14045#14045
Answer: The Euphonium has a fuller, rounder tone and a fuller volume than the Baritone. They are both tuned in Bb.
The tenor horn in UK is actually an Alto instrument and tuned in Eb. Its sound is "similar" to the Flugelhorn.
The Bariton part is often higher than the Euphonium. The latter is also called the "violoncello" of the brass band because of its counterpart (counterpoint function) to the cornets. The Euphonium part is usually more virtuos than the Baritone.
Answer: Thomann lists two groups of instruments: Baritones and Alto/Baritone horns.
The Alto/Baritone horns list contains conventional British Brass Band standard baritone horns, which have these features:

upward pointing bell
piston valves
fourth valve can be played with left hand

Some of these instruments also feature compensated tubing for better tuning.
The Baritones list meanwhile contains instruments with the same length of tubing, but configured differently - instruments that don't belong in the Alto/Baritone horns list:

Bell upward facing sometimes
some instruments designed to be played marching, so bell is forward facing
angled bell
rotary valves rather than piston valves (although I did see one that used piston valves)
curvier shapes

I'm sure that as a blindfolded listener you'd be very hard-pressed to tell the difference between instruments from these two groups. The deciding factor to determine which instrument to use is the musical context - American marching band or UK Brass band.


Drupal 7 - Entitiy Reference - Reference field to a conent as a link

Question: I created content - lets call it X - which has a field with the type of entitiy reference (done with Entitiy reference). This field refers to a content that can be selected via select list. When X is shown the reference field appears but not as a link so that I can directly forward to that content. Do I need any additional module for that?
Answer: On the Manage Display page (Structure->Content Types->Your content), first be sure the display format is set to Label. Then, click on the gear on the right. You will see a checkbox with "Link label to the referenced entity". Check that and click Update, then save our display. The label will now link to the entity.


Como retornar valores de duas tabelas distintas php

Question: Sou iniciante e queria criar uma função que me retornasse a partir do nome o cpf, usuario e senha da pessoa no sistema. Onde os campos nome e cpf pertencem a tabela usuarios e os campos usuario e senha pertencem a users.
Forma que tentei e não obtive sucesso

Minha function.php
     function retorna($nome, $conn){
            $result = "SELECT CPF, USUARIO, SENHA FROM USUARIOS A INNER JOIN USUAR B ON B.NOME = A.NOME WHERE nome = '$nome' LIMIT 1";
            $resultado = mysqli_query($conn, $result);
            if($resultado->num_rows){
                    $row = mysqli_fetch_assoc($resultado);
                    $valores['cpf'] = $row['cpf'];
                    $valores['usuario'] = $row['usuario'];
                    $valores['senha'] = $row['senha'];

            }else{
                    $valores['cpf'] = '';
                    $valores['usuario'] = '';
                    $valores['senha'] = '';

            }

            return json_encode($valores);

    }

    if(isset($_GET['nome'])){
            echo retorna($_GET['nome'], $conn);
    }

Answer: As duas tabelas são relacionadas? Se sim tenta fazer essa busca por número, como cod_usuario.
Creio eu que não é possível fazer um select com inner setando 2 tipos diferentes de valores para um mesmo campo.
Nesse caso eu recomendaria que criasse uma view no banco e desse um select por ela. Exemplo :
create view vw_user as
  select a.cpf, b.usuario, b.senha
  from usuario a, user b
  where a.cod_usuario = b.cod_usuario
;

Onde dentro do código em php você coloca a consulta
select * from vw_user where nome = $nome

Claro, alegando que o nome do usuario da tabela pessoa é o mesmo que o nome da tabela users. Caso contrario, sugiro que esse login seja feito pelo numero do cpf, ou que ele utilize outra chave para encontrar o usuário.
EDIT 1: criei um banco fictício para ilustrar o meu pensamento (sem a adição da view, para ficar mais simples)
create database logincliente;
use logincliente;

create table pessoa(
cod_pessoa int not null auto_increment primary key,
nome_pessoa varchar(50)
);

create table login(
cod_login int not null auto_increment primary key,
cod_pessoa int not null,
login varchar(50),
senha varchar(50)
);

alter table login add constraint fk_loginPessoa foreign key (cod_pessoa) references pessoa (cod_pessoa);

insert into pessoa(nome_pessoa) values
('Flávio'),
('Castro'),
('Reginaldo'),
('Péricles');

insert into login (cod_pessoa,login,senha) values
(1,'flaviko','12345'),
(2,'kastr','stqvb'),
(3,'reginaldo','reginaldo'),
(4,'pokkter','033line');

select p.nome_pessoa, l.login, l.senha from pessoa p, login l where nome_pessoa = 'péricles' and p.cod_pessoa = l.cod_pessoa;

Tenta testar esse ultimo select, e veja se é esse o resultado que deseja :)
Comment: Tentei deixar o mesmo script e só alterar meu select depois de criar a view e persiste o erro .
Comment: eu criei um script SQL que ilustrou basicamente o que eu tentei explicar (não usei view, pois não é tão necessário na ocasião)
Comment: seria preciso um javascript como o que eu citei para fazer o preenchimento dos próximos campos
Comment: esse insert que eu fiz você pode adaptar ao seu código
Comment: esse select que eu fiz, é só colocar uma variavel php no meio
Comment: no caso utilizando esse código dentro da minha function.php não dá, acho que preciso buscar um novo script para preencher todos dados a partir de um campo


Distinguishing between linear and non-linear differential equations

Question: I am working on a few problems from Dennis Zill's book on Differential equations and in te exercise below I am asked to say if the differential equation is linear or non-linear and its order:

My answers:
1 - 2nd order, linear
2 - 3rd order, ?
3 - 4th order, linear
4 - 2nd order, non-linear
5 - 2nd order, non-linear
6 - 2nd order, non-linear
7 - 3rd order, linear
8 - 2nd order, ?
Can someone confirm that? I am really confused about a differential equation being linear or nonlinear.
Comment: $2.$ and $8.$ are nonlinear.
Answer: An ordinary differential equation is linear if it can be written in the form
$$
L(y(x))=\left[A_n(x)\frac{d^n}{dx^n}+A_{n-1}(x)\frac{d^{n-1}}{dx^{n-1}}+ \cdots +A_1(x)\frac{d}{dx}+A_0(x)\right]y(x)=f(x)
$$
(this guarantees that if $h(x)$ and $k(x)$ are solutions , also $\alpha h(x)+\beta k(x)$ is a solution)
so, in your case , the equations 2,4,5,6,8 are not linear.
Comment: I am having a bit of confusion understanding your text. Is $$
\left[A_n(x)\frac{d^ny}{dx^n}+A_{n-1}(x)\frac{d^{n-1}y}{dx^{n-1}}+ \cdots +A_1(x)\frac{dy}{dx}+A_0(x)\right]y=f(x)
$$ what you mean? Is there any restriction on the undifferentiated y term?
Comment: https://math.stackexchange.com/a/4527089/804033 this equation looks a bit different too, i am guessing it could be a formatting error?


Cauchy problem using Duhamel's Principle

Question: Consider the Cauchy problem
$$\left\{
\begin{array}{l l}
u_{tt} - u_{xx} = e^{-t}\sin x & \quad \mbox{$x \in \mathbb{R}, t>0$,} \\
\quad u(x,0) = 0, \\
\quad u_t(x,0) = 0.
\end{array}
\right. $$
(a) Find the solution $u(x,t)$ using Duhamel's principle.
(b) Compute the limit $\lim_{t\rightarrow\infty}{u(x,t)}$
I think the general solution to this looks like this:
$$\int_{0}^{t}u(x,t) = U(x,t-s,s)ds$$
but I am not sure of how to get there.
Or I am also aware that the solution might take the form of this:
$$v(x,t) = \frac{1}{2}[\phi(x+ct)+\phi(x-ct)] +\frac{1}{2c} \int_{x-ct}^{x+ct} \psi(s) ds$$
In this case, it this were the general solution, the the entire left side of the addition would disappear because of the zero from the initial conditions?
Also, I am not sure of where to even begin with computing the limit since I am already lost here...
Thank you for your help.
Answer: The general solution that you gave is for the homogeneous problem (right-hand-side equal to zero), however, it is still important to know this to derive a formula for the inhomogeneous problem. The essence behind Duhamel's principle is to consider the homogenous problem with $f$ as part of your initial condition at some given time slice, viz.,
$$u_{tt} - u_{xx} = 0, \\
u(x,s) = 0,\\
u_t(x,s) = f(x,s) \,ds.$$
By the general solution you already derived, this is solved by
$$u(x,t) = \frac{1}{2}\left(\int^{x+(t-s)}_{x-(t-s)} f(y,s) \,dy \right) ds$$
Duhamel's principle then tells us that we can find the solution to the inhomogeneous problem by integrating all of the time slices and adding it to the original general solution. Thus, the solution to the inhomogeneous problem is given by
$$u(x,t) = \frac{1}{2}\left(\phi(x+t)+\phi(x-t) \right) + \frac{1}{2}\int^{x+t}_{x-t} \psi(s) \,ds +\frac{1}{2} \int_0^t \left(\int^{x+(t-s)}_{x-(t-s)} f(y,s) \,dy \right)ds$$
Comment: @KBG Here, $\phi = \psi = 0$ (cf e.g. [this video](https://youtu.be/vxmOnq1r9q8) and [this article](https://en.wikipedia.org/wiki/Duhamel%27s_principle#Wave_equation)).
Comment: Thank you! How would I compute the limit of this?
Comment: Put the initial conditions and right-hand-side $f(x,t) = e^{-t}sin(x)$ into the formula, calculate the solution and then determine the limit - it will depend on what u(x,t) comes out as.
Comment: If $\phi = \psi =0$ would the limit be zero?
Comment: I believe so yes :)
Comment: when using duhamels principle, im guessing f has to be in relation to some time derivative (as in f is adding energy into this system at t = s) but in that case when im solving the heat equation with IC
$$u_x(1,t)=u_x(0,t)=0 for t>0 \text{ and } u(x,0)=0$$

and i start solving the homogeneous equation should i impose an initial condition akin to $v_t(x,s) = f(x,s) ds $


How to make calling a method dynamic with a Switch Case- Java

Question: I want to call a method. Depending on a argument a certain method will be called.
Currently I am trying to achieve this using a Switch Case, but I cant get it to work.
Code:
String getoption = null;
switch (rateIndex){

case 3:
    getoption = "bar.getOneMonth();"
case 4:
    getoption = "bar.getTwoMonth();"
case 5:
    getoption = "bar.getThreeMonth();"

}

Big Decimal qMidRate = null;

for(MonthlyRates bar: results){
    qMidRate = getoption;
    //more logic
}

I am trying to get a Big Decimal value from the get methods, is there any way of doing this? any help would be appreciated.
Answer: If all those methods are returning strings, simply ditch the double quotes:
case 3:
    getoption = bar.getOneMonth();
    break;
case 4:
    getoption = bar.getTwoMonth();
    break;
case 5:
    getoption = bar.getThreeMonth();
    break;

Comment: assuming I would put it inside the for loop?
Comment: I'm sorry, I don't understand?
Answer: You can do this with method references/lambdas if you're using java 8.  Something like:
    // I have no idea what 'getOneMonth', etc. are returning or have as parameters...
    // This assumes they take a Long, and return a String, 'cause I don't know.
    Function<Long, String> choice = null;
    switch (rateIndex) {
        case 3:
            choice = bar::getOneMonth;
            break;
        case 4:
            choice = bar::getTwoMonths;
            break;
        // ...
        default:
            throw new HissyFit();
    }

    for (final MonthlyRates rates : bar.getMonthlyRates()) {
        final String methodCallResult = choice.apply(rates.getSomeLong());
    }

Comment: the get methods dont have any parameters and return a Big Decimal.
Comment: `Supplier` would work then.  But if you only need to call them once, like the other answer says, you can just store the result as a `BigDecimal` somewhere and use that.


Is my solution to this permutation question correct?

Question: Question: Suppose there are m girls and n boys in a class. What is the number of ways of arranging them in a line so that all the girls are together? (Biggs, Discrete Mathematics 2nd ed, Exercise 10.7.5)
My solution
Say $m=4$ and $n=3$
The number of ways they can be arranged are:
G - a girl, B - a boy
<code>position 1: [G G G G][B B B]
position 2: [B][G G G G][B B]
position 3: [B B][G G G G][B]
position 4: [B B B][G G G G]
</code>
So in this case the group of girls can be placed in $4$ different positions. On each position the group of girls can internally be arranged in $4!$ different ways, and the boys can be arranged in $3!$ different ways.
Hence the total number of arrangements are $4!*3!*4$
Converting the answer back to variables, I end up with: $m!*n!*(n + 1)$
The book provides no solution, so I would really like to know if I came up with the right answer..
Comment: It's not really a set theory question.
Comment: Note that $n!(n+1)=(n+1)!$
Comment: sorry my bad, the chapter was all about sets and permutations, just presumed set theory
Comment: @tomasz what category would you suggest?
Comment: Your answer is correct. One way to argue it for general $m$ and $n$ is that we can have $0$ or $1$ or $2$ or $\dots$ $n$ boys to the left of the clump of girls, so $n+1$ choices. Multiply $n+1$ by $m!n!$ to account for ordering.  There is a cuter argument that gets you an answer of $(n+1)!m!$ directly.
Comment: @hakanito: Arthur Fischer answered that for you. ;)
Comment: Ah, I see. Thank you all for your help! :)
Answer: The basic idea and the answer are correct, but for a complete solution, you should show it in abstract context, so start with arbitrary (unspecified) $m,n$ and try to show that you get $(n+1)!m!$ as a result.


PHP mailer sends multiple mails

Question: I saw a lot of questions with the same problem but I can't find what's mine. So I have a contact form to ask for an appointment at the dentist office but for some reason it sends the mail multiple times. Sometimes 4x, sometimes 9x, ...
I changed the mailaddres as an example but this is my code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
/*
require 'PHPMailer/PHPMailerAutoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
*/
if(isset($_POST['submit'])){

    // Send mail
//    $mail = new PHPMailer();

    // Data received from POST request
    $name = stripcslashes($_POST['name']);
    $phone = stripcslashes($_POST['phone']);
    $email = stripcslashes($_POST['email']);
    $message = stripcslashes($_POST['message']);

    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= 'From: <firstname.lastname@example.com>' . "\r\n";
    $subject = "Afspraak aanvraag van: " . $name;
    $message = "Naam: " . $name . "

Email: " . $email. "

Telefoon: " . $phone. "

Bericht: " . $message . ";
    mail('email@example.com',$subject,$message,$headers);

   if(mail($subject,$message,$headers)) {
        echo "
Sorry, something went wrong.
";
    } else {
        echo "
Thanks for your message

";
    }

/*
    // SMTP Configuration
   XXXXXX

    // $mail->Body    = 'This is the HTML message body in bold!';
    // $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
    $mail->MsgHTML("Name:" . $name . "

Email:" . $email. "

Phone:" . $phone. "

Messgae:" . $message);

  if (!$mail->send()) {
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message sent!';
}
*/
}
?>

Comment: You should redirect to another page after sending email. Maybe someone is refreshing post request, so you are sending multiple emails?
Comment: @Robert that sounds very logical to me. How do I add a redirect into the code?
Comment: Use function `header('Location: your another page url');`. I've just noticed that you inform user about successful email delivery with message 'Sorry, something went wrong'. It may be the possible cause of your problem and people are refreshing post requests.
Comment: @Robert Thanks a lot! This was exactly the problem. When I refreshed the page it sent the mail again. It has been fixed!
Comment: Use `Reply-To` header to set client mail and not yours. See this article: https://karl-voit.at/2021/07/21/reply-to/
Answer: Problem was fixed by redirecting to another page instead of the 'thank you echo message'. People refreshed the page with the result of duplicate mails.
Comment: for alternative. you could use die('Message Sent') to stop the process without redirecting to another page.

PHP mailer sends multiple mails


How can I replace a match only at a certain position inside the string?

Question: So, I have a function which has two params: string and match index to replace and i need to replace only match with that index. How can i do that?
Example:
replace('a_a_a_a_a', 1)

Result:
a__a_a_a

Comment: can you provide another example of input parameters so the required functionality is clearer?
Comment: Try using regexp, look at this : [Replacing the nth instance of a regex match in javascript][1]

  [1]: http://stackoverflow.com/questions/36183/replacing-the-nth-instance-of-a-regex-match-in-javascript
Answer: Could look like:
var mystr = 'a_a_a_a_a';

function replaceIndex(string, at, repl) {
   return string.replace(/\S/g, function(match, i) {
        if( i === at ) return repl;

        return match;
    });
}

replaceIndex(mystr, 2, '_');

The above code makes usage of the fact, that .replace() can take a funarg (functional argument) as second parameter. That callback is passed in the current match of the matched regexp pattern and the index from that match (along with some others which we are not interested in here). Now that is all information we need to accomplish your desired result. We write a little function wish takes three arguments:

the string to modify
the index we wish to change
the replacement character for that position
Comment: Close, but I think the `index` the OP is interested in is the `nth` occurrence of the pattern, not the string position of the match.
Answer: For those like me who find regex to be cryptic, here is "pure JavaScript" way as well:
function CustomReplace(strData, strTextToReplace, strReplaceWith, replaceAt) {
    var index = strData.indexOf(strTextToReplace);
    for (var i = 1; i < replaceAt; i++)
        index = strData.indexOf(strTextToReplace, index + 1);
    if (index >= 0)
        return strData.substr(0, index) + strReplaceWith + strData.substr(index + strTextToReplace.length, strData.length);
    return strData;
}

Usage:
var mystr = 'a_a_a_a_a';
var newstr = CustomReplace(mystr, "_", "__", 2); //replace the second appearance

Live test case: http://jsfiddle.net/tXx5n/2/
Comment: Very nice. For another - slightly more brief solution - see http://stackoverflow.com/a/10585234/3751385
Answer: Javascript match returns an array, in case of multiple matches, so you could so something like this:
var string = "....";
var patt1 = /..../gi;
var results = string.match(patt1);
var newString = results.splice(i, i).join();

Instead of using a match, you could use split instead in your specific case:
var results = string.split("_");
var newString = results.splice(i, i).join("_");

It depends on how your input data can vary and where you need to do the split/match (that is why I did not specify any regex above, the split example is complete)...
Comment: Sorry, I added a bad example, i need to modify my match like that — before: im_1_2_3_4, after im_1_%2%_3_4. Function still the same, detect all numbers in string and replace match with my index.
Answer: Use regex match with g flag
var str="test string".match(/t/g)  output would be array of matched strings in this case "t"
[t,t,t]
Answer: You need to use the function parameter of the replace function, and also maintain an index (i) of matches.

function replaceAt(string, replaceThis, replaceWith, at) {
  let i = 0;
  if (Array.isArray(at)) {
    return string.replace(replaceThis, (match, offset) => at.includes(i++) ? replaceWith : match)
  } else if (Number.isInteger(at)) {
    return string.replace(replaceThis, (match, offset) => i++ === at ? replaceWith : match)
  } else {
    return string;
  }
}
// usage:
console.log(replaceAt("aaaaabcde", /a/g, ".", [2, 0])); // ".a.aaabcde"
console.log(replaceAt("aaaaabcde", /a/g, ".", 2)); // "aa.aabcde"

String.prototype.replaceAt = function(replaceThis, replaceWith, at) {
  let string = this, i = 0;
  if (Array.isArray(at)) { // e.g. console.log("aaaaabcde".replaceAt(/a/g, ".", 2)); => "aa.bcde"
    return string.replace(replaceThis, (match, offset) => at.includes(offset) ? replaceWith : match)
  } else if (Number.isInteger(at)) { //e.g. console.log("aaaaabcde".replaceAt(/a/g, ".", [2, 0])); => ".a.bcde"
    return string.replace(replaceThis, (match, offset) => offset === at ? replaceWith : match)
  } else {
    return string;
  }
}
// usage:
console.log("aaaaabcde".replaceAt(/a/g, ".", [2, 0])); // ".a.aaabcde"
console.log("aaaaabcde".replaceAt(/a/g, ".", 2)); // "aa.aabcde"

function replaceExceptAt(string, replaceThis, replaceWith, at) {
  let i = 0;
  if (Array.isArray(at)) { // e.g. console.log(replaceExceptAt("aaaaabcde", /a/g, ".", 2); => "..a..bcde"
    return string.replace(replaceThis, (match, offset) => !at.includes(i++) ? replaceWith : match)
  } else if (Number.isInteger(at)) { //e.g. console.log(replaceExceptAt("aaaaabcde", /a/g, ".", [2, 0])); => "a.a..bcde"
    return string.replace(replaceThis, (match, offset) => i++ !== at ? replaceWith : match)
  } else {
    return string;
  }
}
// usage:
console.log(replaceExceptAt("aaaaabcde", /a/g, ".", [2, 0])); // "a.a..bcde"
console.log(replaceExceptAt("aaaaabcde", /a/g, ".", 2)); // "..a..bcde"

String.prototype.replaceExceptAt = function(replaceThis, replaceWith, at) {
  let string = this, i = 0;
  if (Array.isArray(at)) { // e.g. console.log("aaaaabcde".replaceExceptAt(/a/g, ".", 2); => "..a..bcde"
    //return string.replace(replaceThis, (match, offset) => !at.includes(offset) ? replaceWith : match)
    return string.replace(replaceThis, (match, offset) => !at.includes(i++) ? replaceWith : match)
  } else if (Number.isInteger(at)) { //e.g. console.log(replaceAt("aaaaabcde", /a/g, ".", [2, 0])); => "a.a..bcde"
    return string.replace(replaceThis, (match, offset) => i++ !== at ? replaceWith : match)
  } else {
    return string;
  }
}
// usage:
console.log("aaaaabcde".replaceExceptAt(/a/g, ".", [2, 0])); // "a.a..bcde"
console.log("aaaaabcde".replaceExceptAt(/a/g, ".", 2)); // "..a..bcde"


Is it Linux or window hosting?

Question: I Don't know much about server things.
But my client says his server is Apache version2.2, .php files run asPHP5 FastCGI
So is it Linux hosting server or Window hosting server.
Thank you.
Comment: I'm voting to close this question as off-topic because it is not a programming question.
Comment: Why not ask them?
Comment: Possible duplicate http://stackoverflow.com/questions/10205870/how-to-determine-if-a-webserver-is-running-linux-or-windows
Answer: You can run Apache on Linux and Windows so you can't really say what operating system is running on that server.

Is it Linux or window hosting?


iptables: what does "--src-type LOCAL" mean exactly?

Question: The iptables man page defines it as "a local address" but does this refer only to the 127 range (localhost) or does it include 10, 169, 192 as well ?
Comment: check https://www.halolinux.us/firewalls/addrtype-filter-table-match-extension.html
Answer: I believe the answer that addr-type LOCAL means loopback is wrong, because it is only a partial answer and is extremely misleading.
LOCAL means ANY IP assigned on one of the interfaces of the host, including the loopback. If you say that LOCAL is simply 127.0.0.0/8 (as sasanet has stated), then you'd limit it to the loopback interface, which is plain wrong.
Moreover, the IP can even be routable and public. For the host it's irrelevant, because from its perspective that IP is going to refer to the host itself. If you curl or ping to the public ip assigned on one if its interfaces, it will obviously not going to send the packet out, it will route it locally.
example:
ip address show dev eth0:
 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9001 qdisc mq state UP group default qlen 1000
    link/ether 0a:e7:8b:89:d5:f4 brd ff:ff:ff:ff:ff:ff
    inet 172.31.20.254/20 brd 172.31.31.255 scope global dynamic eth0
       valid_lft 3110sec preferred_lft 3110sec

ip route show table local:
local 172.31.20.254 dev eth0 proto kernel scope host src 172.31.20.254

(as already stated, it is obviously irrelevant if the ip is private or public, as long as it is assigned to the network interface)
Comment: By LOCAL any IP of any interface is meant that goes through this host. You can check it for yourself with: `iptables -A INPUT -p tcp -m addrtype --src-type LOCAL -j LOG --log-prefix "Source IP is LOCAL "`, alternatively you may try `-A FORWARD`
Comment: Yes, but "local" even in this sense is going to be routed through the local table, as far as I can tell, right? If you delete the rule mentioned in my answer in the local table, then you woun't be able to use that ip to refer to that host itself. I also tried it with 127.0.0.1 (and 127.0.0.0/8) and it's the same thing. So I'm guessing the local table is actually related.
The problem (I'd say) with the manual in the ip route is that, while it's technically correct, it's also slightly misleading, as you might think only of the loopback. But correct me if I'm wrong.
Comment: I was just trying to split hairs (and already gave a +1), I'll remove my comment heh.
Comment: Don't need to do that, really. Thanks for the +1 anyway (although I'm not particularly interested in that). This is something I realised not long ago, so the reason why I replied to your comment, was to confirm that what I said was actually correct. Thanks :)
Answer: The terminology "local route" means the packets will be delivered "locally" to your host, because the destination is assigned to one of your host's interfaces. It does not only mean localhost, as in loopback addresses (nor 169.254/16 as in "link-local" addresses).
Linux uses the Netlink protocol to send messages between kernel space and user space—one of the Netlink families therein is NETLINK_ROUTE, which can be used to receive routing updates, modify interface addresses, etc. For example, the ip-route command from iproute2 uses this.
Looking at the addrtype source code of iptables, you'll see references to linux/rtnetlink.h, which defines RTN_LOCAL as a message type. The rtnetlink(7) man page describes RTN_LOCAL as:
rtm_type          Route type
───────────────────────────────────────────────────────────
RTN_LOCAL         a local interface route

None of this feels exactly clear when you read about it, and some of the best references I can find are miscellaneous Internet sources, so it's understandable why there's confusion.
Comment: downvote because... ?
Comment: I am also wondering why it was downvoted. I also answered that LOCAL does not only mean loopback, indeed, but your answer was more extensive and detailed.
Answer: Pretty good explanation here: Explicit Matches
Another discussion about it:
https://www.linuxquestions.org/questions/linux-networking-3/wtf-addrtype-in-iptables-manpage-746659/#post3638892
Comment: So the answer is: "addresses on the host itself ... in the 127.x.x.x range".
Comment: @StevenMonday No the answer is what Lethargos wrote.
Answer: -m addr-type LOCAL is the 127.0.0.0/8-network.