Prevent rollup from renaming Promise to Promise$1

Question: Update: Turned out that this is not a problem with Babel, but with Rollup, which is run before. Thanks for your help anyway and sorry for the noise.
I use rollup to bundle a number of modules including a Promise polyfill (deliberately overwriting the global Promise). However, rollup recognizes Promise as a global name and transforms
export default function Promise(fn) { ... }
...
global.Promise = Promise;

to
function Promise$1(fn) { ... }
...
global.Promise = Promise$1;

The resulting code works, but I would like the following assertion to hold true:
expect(Promise.name).to.equal('Promise');

Is there any way to tell rollup to leave the constructor name intact?
Comment: @ralfstx Type checks based on `.constructor.name` should not be used precisely for this reason. Names get mangled by transpilers, bundlers and minifiers. Older browsers don't implement them at all. Use `instanceof`, `typeof` or shape detection (existence and type of properties) instead. Debugging and logging is a different topic, that's usually done in known environments and with the original source.
Comment: What babel plugins are you using? What specifically is Babel changing in your output file?
Comment: Don't test for names. They're insignificant.
Comment: Not sure about the update. Did you solve the problem? Are you now asking how to tell Rollup to leave the name alone? If you found a solution, please [post it as an answer](https://stackoverflow.com/help/self-answer), if not, please [edit] to clarify your setup and what you are looking for; or if you moved on just delete the question.
Comment: Thanks for the advice, I've now updated the question. I hesitated to change the topic as I wasn't sure if that's good practice...
Comment: @Bergi That's not quite true. Type checks are often based on `constructor.name` in JS. The name is also taken into account by the formatter used in the Node.js console ([example](https://github.com/nodejs/node/blob/master/lib/util.js#L473)).
Comment: @Bergi The thing is that I'm working on [such an environment](https://github.com/eclipsesource/tabris-js) that implements stuff like logging, and that's why I have this issue ;-) Apart from that, `constructor` and `constructor.name` are part of the ES 2015 spec, so I can't quite follow your advice to generally avoid them.
Comment: @ralfstx `name` might be part of ES6, but that doesn't mean it's web-compatible. IE doesn't support it at all, so I recommend to avoid it there. In your environment, it seems to be fine.
Answer: Try using rollup-plugin-inject and configuring it to add import Promise from 'your-promise-polyfill' to any files that reference Promise. That way, Rollup won't think that it needs to rename the function declared in the polyfill to avoid clashing with the global, because it won't be aware that there is a global that it's clashing with.
// rollup.config.js
import inject from 'rollup-plugin-inject';

export default {
  // ...
  plugins: [
    inject({
      Promise: 'your-promise-polyfill'
    })
  ]
};


How do I capture the output of a script if it is being ran by the task scheduler?

Question: Using Windows Server 2008, how do I go about capturing the output of a script that is being ran with the windows task scheduler?
I'm testing a rather long custom printing batch-script, and for debugging purposes, I would like to see all of the output from it every night.
Comment: Sometimes, this will not work i.e. no log file is generated. One scenario that can lead to this is when the task did not start at all, because Windows mistakenly thinks that it is still running. You can track that by loking at task history (history tab in task property - the information may take a few seconds to show up)
Answer: Try this as the command string in Task Scheduler:
cmd /c yourscript.cmd > logall.txt

Comment: Additionally, use `cmd /c "path with spaces/command.cmd > file.txt"` if you have spaces. The `2>&1` from [Ivan's answer](https://stackoverflow.com/a/23808212/3136474) also goes inside the quotes.
Comment: need to use double quotes to get mine to work: https://stackoverflow.com/a/6378038/1747983  `cmd /c ""C:\temp\My test dir\something 123\myTool.exe" > Tilo_log.txt 2>&1"`
Comment: Now I have a command window showing up when running the task. How to prevent that?
Comment: @Chris check out this answer: https://stackoverflow.com/a/52206695/184839
Comment: You'll miss errors without redirecting stderr by adding `2>&1` as stated in another answer on this page https://stackoverflow.com/a/23808212/727345
Comment: Note, that using single `>` will overwrite the file the instant another execution of the task **starts**, which depending on the frequency and duration may mean right away after completing the previous execution. Consider using `>>` to append to the log file instead, maybe implement some basic log rolling or at least rename the previous log file before overwriting it.
Answer: To supplement @user2744787's answer, here is a screenshot to show how to use cmd with arguments in a Scheduled Task:

Program/script: cmd
Add arguments: /c run_with_default_port.bat > IMQuantWebServices.log
Comment: Seems you are starting a service via a scheduled task. If this should be a service running persistently in the background, have a look at NSSM as an alternative. It runs any command as a windows service and handles restarting after failure etc.
Comment: weow, finally. this is the exact procedure to schedule a cmd job.
Answer: With stderr (where most of the errors go to):
cmd /c yourscript.cmd > logall.txt 2>&1

Comment: This improves on the accepted answer for the OP's request to log for debugging purposes because it will log errors too.
Answer: The >> will append the log file, rather than overwriting it each time. The 2>&1 will also send errors to your log file.
cmd /c YourProgram.exe >> log.txt 2>&1

Answer: You can have a debug.cmd that calls yourscript.cmd
yourscript.cmd > logall.txt

you schedule debug.cmd instead of yourscript.cmd
Answer: Use the cmd.exe command processor to build a timestamped file name to log your scheduled task's output
To build upon answers by others here, it may be that you want to create an output file that has the date and/or time embedded in the name of the file.  You can use the cmd.exe command processor to do this for you.
Note: This technique takes the string output of internal Windows environment variables and slices them up based on character position.  Because of this, the exact values supplied in the examples below may not be correct for the region of Windows you use.  Also, with some regional settings, some components of the date or time may introduce a space into the constructed file name when their value is less than 10.  To mitigate this issue, surround your file name with quotes so that any unintended spaces in the file name won't break the command-line you're constructing.  Experiment and find what works best for your situation.
Be aware that PowerShell is more powerful than cmd.exe.  One way it is more powerful is that it can deal with different Windows regions.  But this answer is about solving this issue using cmd.exe, not PowerShell, so we continue.
Using cmd.exe
You can access different components of the date and time by slicing the internal environment variables %date% and %time%, as follows (again, the exact slicing values are dependent on the region configured in Windows):

Year (4 digits):  %date:~10,4%
Month (2 digits): %date:~4,2%
Day (2 digits):   %date:~7,2%
Hour (2 digits):  %time:~0,2%
Minute (2 digits): %time:~3,2%
Second (2 digits): %time:~6,2%

Suppose you want your log file to be named using this date/time format: "Log_[yyyyMMdd]_[hhmmss].txt".  You'd use the following:
Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt

To test this, run the following command line:
cmd.exe /c echo "Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt"

Putting it all together, to redirect both stdout and stderr from your script to a log file named with the current date and time, use might use the following as your command line:
cmd /c YourProgram.cmd > "Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt" 2>&1

Note the use of quotes around the file name to handle instances a date or time component may introduce a space character.
In my case, if the current date/time were 10/05/2017 9:05:34 AM, the above command-line would produce the following:
cmd /c YourProgram.cmd > "Log_20171005_ 90534.txt" 2>&1

Comment: there is no leading zero on hours less than 10 :/ not sure how to fix but at least quote the file name
Answer: You can write to a log file on the lines that you want to output like this:
@echo off
echo Debugging started >C:\logfile.txt
echo More stuff
echo Debugging stuff >>C:\logfile.txt
echo Hope this helps! >>C:\logfile.txt

This way you can choose which commands to output if you don't want to trawl through everything, just get what you need to see. The > will output it to the file specified (creating the file if it doesn't exist and overwriting it if it does). The >> will append to the file specified (creating the file if it doesn't exist but appending to the contents if it does).
Answer: Combining the other answers, which each had some useful tips, but none of them captured every nuance:
In the Task Scheduler > Actions:
Action: Start a program
Program/script: cmd
Add arguments: /c ""C:\my path\my task.cmd" >> "C:\my path\my task.log" 2>&1"
The above example demonstrates these features:

Allows spaces in the path/filename. If there are no spaces in the path, then you can eliminate the nested quotes: /c "C:\path\task.cmd >> C:\path\task.log 2>&1"

Appends to the log. If you want to overwrite the log each time, then use > instead of >>

Includes both STDOUT and STDERR in the log. If you only want STDOUT, then remove 2>&1
Answer: Example how to run program and write stdout and stderr to file with timestamp:
cmd /c ""C:\Program Files (x86)\program.exe" -param fooo >> "c:\dir space\Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt" 2>&1"

Key part is to double quote whole part behind cmd /c and inside it use double quotes as usual. Also note that date is locale dependent, this example works using US locale.
Answer: This snippet uses wmic.exe to build the date string.  It isn't mangled by locale settings
rem DATE as YYYY-MM-DD via WMIC.EXE
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
set RDATE=%datetime:~0,4%-%datetime:~4,2%-%datetime:~6,2%


How can I get XPATH to return a node between two different siblings?

Question: I am working on pom file modifications to change the version node value.  I can get xpath to modify all version nodes, but I only want it to change the version node when both the artifactId and classifier match certain values.  Here is my xml:
<code><artifactItem>
    <groupId>com.xyz</groupId>
    <artifactId>foobar</artifactId>
    <version>${project.version}</version>
    <classifier>config</classifier>
    <type>zip</type>
    <overWrite>true</overWrite>
</artifactItem>
<artifactItem>
    <groupId>com.xyz</groupId>
    <artifactId>foobar</artifactId>
    <version>${project.version}</version>
    <type>jar</type>
</artifactItem>
</code>
If artifactId is foobar, and classifier is config, I want version returned so I can modify it.
Using other examples I found, I tried this, but it didn't work:
<code>/artifactItem/artifactId[.='foobar']
     /following-sibling::*
      [count(.|/artifactItem/classifier[. ='config']/preceding-sibling::*)
      =
      count(/artifactItem/classifier[. ='config']/preceding-sibling::*)
      ]
</code>
Any suggestions would be greatly appreciated!
thanks
Answer: <code>//artifactItem[artifactId='foobar' and classifier='config']/version
</code>
To explain:
We are selecting the version node, from the artifactItem node that has an artifactId of 'foobar' AND a classifier of 'config'.
You use the brackets to qualify a particular node using sub-XPATH statements where the context is the node before the brackets.
Is this what you are looking for?
Comment: that probably will do it, but I think we have a bug in our perl module processing my xpath.  I will update when we clean that up.
Comment: This worked, thanks.  We had to switch the perl module we were using from Twig.pm to XPath.pm.  We couldn't get Twig to handle the 'and' operator.  Thanks again for the help!


How to prove that the projection length $\frac{x^T y}{\|x\|}$ is normally distributed if $x,y\sim N(0,I_p)$?

Question: $x,y\in\mathbb{R}^p$ are independently drawn from the standard multivariate Gaussian distribution $N(0,I_p)$. How do you prove that the projection length $z=\frac{x^T y}{\|x\|}$ is normally distributed?
If $x$ is fixed, then $z$ is just a linear combination of the entries of $y$, so it is normally distributed. And we can easily calculate the mean and variance, so $z|x\sim N(0,1)$ for any $x$. Is this enough to conclude that $z\sim N(0,1)$ unconditionally?
Comment: If you know that $z|x\sim N(0,1)$ you can use total law of probability to reach your desired conclusion.
Answer: In essence yes! It follows from the law of total probability as mentioned by @Mathew Pilling. If you calculate $$P(z \le t) = \int P(z \le t|x) f_X(x)dx= \Phi(t)$$
since $P(z \le t|x) = \Phi(t)$, and $f_X$, the density of $x$ integrates to 1.


A CLR function equivalent to string.Format in C#

Question: I was looking for a CLR function that will do the same thing as String.Format in C#. As an example, I would like to do the following through a CLR function:
String.Format("My name is {0}, and I live in {1}",myName, cityName)

I would like to be able to pass variable number of parameters after the first parameter, which would be as many place holders are specified in the first parameter to this CLR function. Anyone has any idea on what would be the C# code for such a CLR function?
Answer: I'm looking for the same thing. I came across these two sites: http://www.fotia.co.uk/fotia/Blog/2009/05/indispensable-sql-clr-functions.html & http://stringformat-in-sql.blogspot.com/.
The first uses a CLR function, the other uses a stored procedure.
In the first post, the writer says that UDF parameters aren't optional so you can't have variable number of params (at least the way he is doing it). He just creates a different function with the number or args he will need.
[SqlFunction(DataAccess = DataAccessKind.None)]
public static SqlString FormatString1(SqlString format, object arg0, object arg1)
{
   return format.IsNull ? SqlString.Null :
       string.Format(format.Value, SqlTypeToNetType(arg0, arg1));
}

EDIT :  This is how I solved this problem for me.

Using the stored procedure from the second article, I created this function to format the text for me using a pivot table. Our database is setup with a table dbo.[Rules] that has a column [Description] that has a string that needs to be formatted such as: "NET INCOME MARGINAL (${0} TO BELOW ${1})". We then have a 1-many table dbo.[RuleParameters] with a row for each value that needs to be substituted. The column dbo.[SortOrder] specifies which order the arguments go in. This function will work for AT MOST 4 arguments which is the most that we have.

CREATE FUNCTION [dbo].[GetRuleDescriptionWithParameters]
(
    @Code VARCHAR(3)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @Result NVARCHAR(400)

    SELECT
        @Result =
            dbo.FormatString([Description],
                ISNULL([1], '') + ',' +
                ISNULL([2], '') + ',' +
                ISNULL([3], '') + ',' +
                ISNULL([4], '')
                )
    FROM
    (
        SELECT
        r.[Description]
        ,rp.Value
        ,rp.SortOrder

        FROM
            [Rules] r
        LEFT OUTER JOIN [RuleParameters] rp
            ON r.Id = rp.RuleId

        WHERE r.Code = @Code

    ) AS SourceTable
    PIVOT
    (
        MAX(Value)
        FOR SortOrder IN ([1], [2], [3], [4])
    ) AS PivotTable;

    RETURN @Result
END

EDIT #2: Adding more examples
Format string function:
CREATE FUNCTION [dbo].[FormatString]
(
    @Format NVARCHAR(4000) ,
    @Parameters NVARCHAR(4000)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @Message NVARCHAR(400),
@Delimiter CHAR(1)
DECLARE @ParamTable TABLE ( ID INT IDENTITY(0,1), Paramter VARCHAR(1000) )
SELECT @Message = @Format, @Delimiter = ','
;WITH CTE (StartPos, EndPos) AS
(
    SELECT 1, CHARINDEX(@Delimiter, @Parameters)
    UNION ALL
    SELECT EndPos + (LEN(@Delimiter)), CHARINDEX(@Delimiter,@Parameters, EndPos + (LEN(@Delimiter)))
FROM CTE
WHERE EndPos > 0
)
INSERT INTO @ParamTable ( Paramter )
SELECT
[ID] = SUBSTRING ( @Parameters, StartPos, CASE WHENEndPos > 0 THEN EndPos - StartPos ELSE 4000 END )
FROM CTE
UPDATE @ParamTable SET @Message = REPLACE ( @Message, '{'+CONVERT(VARCHAR,ID) + '}',     Paramter )
RETURN @Message
END
GO

Here is how I call the stored procedure:
SELECT r.[Id]
        ,[Code]
        ,[Description]
        ,dbo.GetRuleDescriptionWithParameters([Code])
        ,rp.[Value]
        ,rp.SortOrder
FROM [Rules] r
INNER JOIN [RuleParameters] rp
    ON r.Id = rp.RuleId

Now I can just call the function like this to get everything formatted nicely for me! Here is sample usage with the results:
Id  Code    Description                     (No column name)          Value     SortOrder
1   1       NOT THE MINIMUM AGE             NOT THE MINIMUM AGE       18        1
3   8       NET INCOME (BELOW ${0})      NET INCOME (BELOW $400)   400    1
4   9       NET (${0} TO BELOW ${1})          NET ($400 TO BELOW $600)  400         1
4   9       NET (${0} TO BELOW ${1})          NET ($400 TO BELOW $600)  600         2

Normally when calling this, I wouldn't join on the [RuleParameters] table, but I did in this case so that you can see the data before and after in one data set.
Comment: Valdetero - How would you use the stored procedure approach? Can you give an example else its difficult to see how to use it. Thanks.
Comment: Btw, this may have bad performance for many records. Sometimes you don't care about the cost when you just need something to work. This is going to be used in SSRS server reports for me; otherwise I would just do it in code.

I have added my sample usage. Please mark as answer if it helps you.


Can music be arrhythmic?

Question: The question is in the subject. Can music be arrhythmic(metrically) by the meaning of classical music theory?
Comment: That depends on the concept you to use for "music". To most people used to western music even traditional music from beyond the East of Europe is considered arrhythmic.
Comment: @musicamante it also depends on the definition of "classical music theory."
Comment: You might clarify why you put "metrically" in parenthesis. If you actually mean can music be non-metrical, that isn't the same as being without rhythm.
Comment: My choir has performed versions of Bach motets in which every note is drawn out a long time (many seconds) and every singer decides on their own when to move to the next note.  Doesn't get much more arrhythmic than that.
Comment: Taking a stab.  As someone who has played a lot of music, but studied very little theory, I would say a collection of tones, and beats with no discernable pattern is just noise.
Comment: Exhibit A: Krzysztof Penderecki - https://youtu.be/HilGthRhwP8
Comment: Certainly. Music is ultimately based on song or dance, and it is only dance that needs to be rhythmic.
Comment: This question is extremely vague in terms of its scope. What is arrhythmia in music, let alone classical? Without a pulse? There are pieces without time signatures, do those fit?
Comment: @JasonPSallinger can you define what a (discernable) pattern is? The usual definition of music is noise organized in time, but i'm curious about yours.
Comment: @AnswerMyQuestion Borrowing from the definition you cite, I would say notes are not organized in a repeating fashion at all.  The brain will make connections based on groupings in time, whether by a repeating interval, or intervals of a curve - one that could be graphed with smooth precision.  If you can't graph the notes to some well-defined function of time, then you will have cacophony.
Comment: Without delving into noise territory, there's also Murder Most Foul, by Bob Dylan. That's certainly music for my ears, but no rhythm as far as metronomes can count.
Answer: The answer will be 'yes' for any definition of arrhythmic, as there are no rules about what music can and can't do - but it's probably still worth noting that it's not totally clear what 'arrhythmic' means without being more specific about the definition. Only a limited number of music styles are based on an entirely regular meter, with most styles allowing (or even assuming) a more flexible timing 'grid' on which events can fall. And even when we consider music with very little in the way of rhythmic repetition that would allow a meter to be discerned, the human brain is still likely to pick up rhythmic patterns from the timings of most possible clusters of events.
Some might say that a piece of music with a very low density of discernable events, such as an entirely steady drone, is 'arrhythmic', but others might require that for a piece of music to be 'arrhythmic' it should actively exhibit events that don't seem to adhere to a rhythm.
Answer: Yes. There are a variety of ways metrically arrhythmic musical events can occur.
Aleatoric music
The idea behind aleatory is that musical events occur unpredictably. The primary modern example of this is John Cage's Music of Changes (Wikipedia, YouTube)
Another example is Joshua Banks Mailman's "comprovisation" series, in which sensors are attached to the body, and musical meta-elements are controlled by body movements. (By meta-elements, I mean that movement doesn't directly affect the pitch, rather it affects the rate of change of pitch.) The technique is fully described in his article "Cybernetic Phenomenology of Music, Embodied Speculative Realism, and Aesthetics-Driven Techné for Spontaneous Audio-Visual Expression" (Perspectives of New Music vol. 54, no. 1, pp. 5–95 [2016]).
The Wikipedia article on aleatoric music provides a wide variety of examples of music written in this way.
Free time
Music in "free time" is performed without a strict underlying pulse (meter); rather, the rhythmic timing is intuitive. The concept is discussed on SE MP&T: Free time in music.
The Wikipedia article also gives a wide variety of examples.
Cadenza
The core idea behind a cadenza is that it be improvisational; thus, the meter may not be strict, and specific rhythms may or may not be discernible.
For example, see the following SE MP&T Q&A: Why aren't there barlines in the piano solo parts in Beethoven's Piano Concerto No. 5?
Rubato
Rubato is the stretching and compressing of musical time for expressive purpose. Although it maintains the rhythm, it can obscure the meter.
Comment: If you're gonna reference John Cage, we should mention one of his most well known "compositions": *4'33"*, which is literally just 4 minutes and 33 seconds of silence and ambient noise.  It is of course pushing the limits as to what qualifies as "music", but that was kind of the point.
Comment: Some handbell pieces include sections where players are supposed to ring selected bells at random times.  Typically there will be rhythmic indication for when the selection of bells should change, but I could imagine that a work that was designed to serve as incidental music for a play or narration might mark chord changes as occurring at certain points in the text, and such a piece could be characterized as arrhythmic.
Answer:
Can music be arrhythmic(metrically) by the meaning of classical music theory?

I don't think you need to bring in "classical" theory. The essential meaning of rhythm is periodicity, something that repeats. You just need to have some music with no repeating element.
That could get a bit tricky philosophically, because you need to ask what elements repeat and what time scale are you considering. Even the theory of meter can get vague about what specifically creates the accent patterns of meter. In a certain way it is just presupposed to exist conceptually.
A simple beat is rhythmic, it repeats. Tempo changes don't necessarily mean arrhythmic. An accelerando and rubato change the tempo, but you wouldn't describe those as arrhythmic.
A drone seems an obvious possibility for arrhythmia, but even things like didgeridoo, bowed string, circular breathing have patterns. Eventually you breath in, the bow changes direction.
The human mind tries to find patterns (rhythms) and it seems there is significant flexibility about what can be identified as a pattern. I think you need to get into the avant-garde to have music that could truly be considered arrhythmic. You could go the John Cage route and call complete silence your music. You could turn on some sine wave generator and have drone a steady pitch and call it music. White noise: music. Etc, etc.
One final thought. Even in computer programming people will point out your can't have truly random numbers.
On a superficial level it seems easy to be random, but on a deeper philosophical level it's difficult.
Comment: Random and nonperiodic are not the same, I think. Or at least, random and non-repeating are not the same. So you're final sentence should be, "it seems easy to not repeat (rhythmically/time-wise), but [...] it's not".
Comment: Computer programming people will point out you can totally have random numbers, but pure computers can't generate them. You can build an actually random number generator and plug it into a computer, and now the computer can have actually random numbers whenever it likes!
Comment: @user253751 do you mean _pseudo_random? In computing they try to get natural sources of entropy for true randomness. My point is that special work needs to be done to be random.
Comment: @user253751 No I mean they can plug a natural source of entropy into a computer. You might argue it's not part of the computer itself, but the computer has the ability to access it.
Comment: @awelotta, I'm not sure what you mean. If it's something like "a sequence cannot be repeated in randomness", that isn't what I meant. Random means lack of pattern, there are degrees of randomness, and some philosophical sense that true randomness is impossible.
Comment: @user253751, that would be exactly the point, not part of a computation, more importantly, not trivial, not easy. And to the _actual_ point, in music it's in the realm of avant-garde.
Comment: @MichaelCurtis it's pretty trivial now that natural entropy sources are built into every CPU
Comment: @MichaelCurtis I meant, you say that the "essential meaning of *rhythm* is periodicity". Therefore, I don't get how pattern/randomness is relevant to rhythm.
Comment: @awelotta, what is the distinction you are making between rhythm, periodicity, pattern, etc? For all practical purposes the terms are synonymous. The relevance is that true randomness would lack a period by which you could divide up events in time into patterns.
Comment: @user253751 if this was StackOverflow then talking about what CPUs can do and what is trivial in programming would make sense. This is a different forum.
Answer: European classical music theory could perhaps withstand the removal of the concept of rhythm, but it definitely depends on the concept of sequence, of events happening in a particular order.  Consider: most aspects of the analysis of a chorale harmonization or of a melody's structure would be unchanged if the durations of all the notes were changed to random values.  Indeed, much medieval music, notably liturgical chant, is preserved without any rhythmic information.  On the other hand, if you change the order of the notes, the pieces would quickly lose their identity.
Despite this, European classical music (indeed, European music generally) has been fundamentally rhythmic since techniques for recording rhythm were invented, and probably before.  Every other musical tradition with which I am familiar is also rhythmic to one degree or another.  (There are several such traditions, though I have only passing familiarity with them, including music of Ghana, Karnataka, and Java, of indigenous peoples of the Americas, and to a lesser extent Chinese opera.)
It also bears mention that rhythm and meter are not synonymous.  Much polyphonic music from the late middle ages and the early renaissance is not metrical in the modern sense, but it is clearly rhythmic.
Answer: Drone music can fit that pattern. A single note or chord in this type of music can ring for so long before another one is struck that all sense of rhythmic connection between the two "events" is lost. This is also the case for ambient music in general (of which Drone is technically a subgenre).
Check out Sunn O))) meets Nurse with Wound - The Iron Soul of Nothing for an example.
Noise music can also be arrhythmic by definition of it being noise, although at the same time it's by definition not music, so I'm not sure it fits your criteria.
Comment: Notes/chords don't even need to be that long, if their start and end isn't clearly defined.  For example, the extremely reverberant, crossfading/overlapping notes in the [Cathedral](https://en.wikipedia.org/wiki/Cathedral_Oceans) [Oceans](https://www.youtube.com/watch?v=6Su690udXSk&list=PLDfp4Ro1qTmd9QX4Ksaq4-n8NSPAu1mtf) series.
Answer: An important division of extemporaneous music (manodharma sangita) in the Indian classical tradition is rāga ālāpana. In rāga ālāpana, the musician develops a rāga in a step-by-step fashion while obeying the structure and characteristics of the rāga, and this is done without any strict rhythm. So, this could be another example of arrhythmic music, to add to the other nice answers to this question.
Answer: I hesitate to pretend to speak on this, since I know nearly nothing about it, but I am dimly aware that there are Africa-continent (and probably other) musical styles that involve mostly drums and percussion instruments, but/and at significantly different repetition rates, so that the whole thing only repeats itself after a considerable interval of time. In particular, listening to just some moments of the pieces might seem to be a cacophony. I hope someone here knows more about this.
(Question, then: does lack of small-scale pattern discourage us from believing in a large-scale pattern, by instinct?)
Comment: This is actually the opposite of what the user was asking about I think.  Traditional African music tends to be much more heavily about the rhythm and less about tonality.  Certainly they use *different* and often more complex rhythms than classical European music, but it would be very wrong to refer to it as "arrhythmic".
Comment: https://en.wikipedia.org/wiki/Polyrhythm#Sub-Saharan_African_music_traditions I think you're overestimating/overstating the effect. I'm not an ethnomusicologist, but AFAIK there is still something like a bar, and it's relatively short.

Can music be arrhythmic?


DJANGO > Renderizar um FOR dentro de outro

Question: Estou com uma situação que é a seguinte:
Preciso fazer no html uma tablea onde tenho que mostrar os totalizadores e uma linha e os valores que compoem esse totalizador, como um pequeno exemplo abaixo
Receitas = 100.000,00
   Salarios = 60.000,00
Extras    = 40.000,00
Porém não sei muito bem como seria fazer isso.
Abaixo tenho os models:
1º GrupoDre (seria os totalizadores)
class Grupodre(models.Model):
master_user = models.ForeignKey('accounts.User', models.CASCADE, verbose_name='Usuario Master')
num_grupodre = models.IntegerField('Código')
descricao = models.CharField('Nome Grupo', max_length=20)
ordem = models.PositiveIntegerField('Ordem no relatório')

class Meta:
    verbose_name = 'Grupo DRE'
    verbose_name_plural = 'Grupos DRE'
    unique_together = [
        ('master_user', 'num_grupodre')
    ]

def __str__(self):
    return str(self.descricao)

2º Plano Financeiro (seria referente a classificação dos lançamentos)
class PlanoFinan(models.Model):
Scategoria_Choices = (
    (None,'Informe o sinal'),
    ('D', 'Despesas'),
    ('R', 'Receitas'),
)

# informação do dono da conta (usuario Master)
master_user = models.ForeignKey('accounts.User',models.CASCADE,verbose_name='Usuario Master')
# dados principais
num_plfin = models.IntegerField('Código')
descricao = models.CharField('Descricão',max_length=60)
sinal = models.CharField('Sinal Conta',max_length=1,choices=Scategoria_Choices)
grupodre = models.ForeignKey('niluscad.Grupodre',models.SET_NULL,verbose_name='Grupo Dre',null=True,blank=True)

class Meta:
    verbose_name = 'Plano Financeiro'
    verbose_name_plural = 'Plano Financeiro'
    unique_together = [
        ('master_user', 'num_plfin')
    ]

def __str__(self):
    return self.descricao

3º Lançamentos (model onde recebe os valores para totalizar)
Class Lancamentos(models.Model):
# informação do dono da conta (usuario Master)
master_user = models.ForeignKey('accounts.User',models.CASCADE,verbose_name='Usuario Master')

# dados principais (empresa e numero do lançamento)
num_lan = models.IntegerField('Nº Registro')
parcela = models.IntegerField('Parcela',default=1)
company = models.ForeignKey('niluscad.Company',models.CASCADE,verbose_name='Empresa')

#dados do titulo
cadgeral = models.ForeignKey('niluscad.CadGeral',models.CASCADE,verbose_name='Cliente',blank=True,null=True)
dt_lancamento = models.DateField('Data Lançamento',null=True,blank=True)
dt_vencimento = models.DateField('Data Vencimento',null=True,blank=True)
plr_financeiro = models.ForeignKey('niluscad.Planofinan',models.PROTECT,verbose_name='Plano Financeiro')
conta_finan = models.ForeignKey('nilusfin.Contafinanceira',models.PROTECT,verbose_name='Conta Recebimento')
c_custo = models.ForeignKey('niluscad.Ccusto',models.PROTECT,verbose_name='Centro de Custo')
vlr_lancamento = models.DecimalField('Valor do Lançamento',max_digits=13,decimal_places=2,blank=True,null=True)
valor_text = models.CharField(verbose_name='Valor',  max_length=20)
saldo = models.DecimalField('Saldo', max_digits=13,decimal_places=2,blank=True,null=True)
descricao = models.CharField(verbose_name='Observação', max_length=70,null=True,blank=True)
titulo = models.BooleanField('É Titulo', default=False)

#Dados Cotação/Indice
indice = models.ForeignKey('nilusfin.Indice',models.PROTECT,null=True,blank=True)
cotacao = models.ForeignKey('nilusfin.Cotacao',models.PROTECT,null=True,blank=True)

situacao = models.BooleanField('Baixado',default=False)
reaberto = models.BooleanField('Reaberto',default=False)
data_baixa = models.DateField('Data de Recebimento',null=True,blank=True)
lancamento_pai = models.ForeignKey('self',models.SET_NULL,blank=True,null=True,verbose_name='Lançamento Pai')

# Dados Baixa e Situação
tipoLancto_Choices = (
    ('R', 'Receita'),
    ('D', 'Despesa'),
)

tipo_lancamento = models.CharField('Tipo', max_length=1, choices=tipoLancto_Choices)

 class Meta:
    verbose_name = 'Lançamento'
    verbose_name_plural = 'Lançamentos'
    unique_together = [
        ('master_user', 'num_lan','parcela')
    ]

def __str__(self):
     return str(int((self.pk)))

Gostaria como posso montar uma View para assim renderizar no template conforme exemplo acima.
Obrigado a todos pela atenção.
Answer: Dê uma vista de olhos na documentação que ela consegue ser melhor do que as respostas nesta comunidade. Convém ler bem a documentação para compreender as raízes do Django.
https://docs.djangoproject.com/pt-br/2.0/ref/class-based-views/generic-display/
Comment: Então meu amigo, já dei uma olhada, o problema é que a UPDATEVIEW pega um registro de acordo com o parametro da seleção dentro da URL.
o problema é que ele retorna, mas demora muito, queria ver se consigo um UPDATEVIEW onde o registro me retorne mais rápido.


Replacing values >2 and <-2 with 0 in excel

Question: I want to replace values >2 and <-2 with 0 in excel. Your help would be appreciated.
Comment: < -2 included to < 2. Do you mean just "< -2" or ">2 or <-2"?
Comment: I want any value which is < -2 or <2 should be rplaced with 0. cheers
Comment: Any number less than -2 already is less than 2, just because -2 < 2. So, simple condition <2 can be used. But, now the question state >2 OR <-2, I think question was edited.
Answer: Use if function. I am showing you an example for cell A1:
<code>=IF(OR(A1>2,A1<-2),0,A1)
</code>
Answer: Try something like this in a formula,
<code>=IF(ABS(A2)>2,0,A2)
</code>
Comment: If I'm reading the question correctly, I think it wants to be `ABS(A2)>2`
Comment: @Trengot - you are correct .. :) Got those flipped. I'll fix my post.
Comment: =IF(ABS(A2)>2,0,A2) it working for one column; however how i should use this formula to look for these values in whole excel sheet. with multiple columns. thanks in advance
Comment: @user3459293: the formula is "relative" if you put it in cell H2, then copy it to H3, it will change to `=IF(ABS(A3)>2,0,A3)`. Likewise, if you copy it to I2, it will change to `=IF(ABS(B2)>2,0,B2)`.  So you build the columns somewhere (possibly even a new sheet if it's that large a task), and copy/paste the formula around.  ie On sheet2, cell A1: `=IF(ABS(Sheet1!A1)>2,0,Sheet1!A1)` it's remapping values from sheet1. You can then copy/paste that formula across sheet 2, and "remap" the values from sheet1.


Python Url API Request with Header - Keep getting Session Expired Can't View Json Data

Question: I'm trying to produce the JSON data so I can search for available camp rentals and the only way seems to be a request with a header otherwise I get a Not Authorize message when just using the URL. Unfortunately I'm having no luck this way as well since I keep getting a Session has expired message. I'm not a web developer so not sure what the cause is. Any help would be greatly appreciated it. Thank you
import time
import sys
import requests

url = "https://reservations.piratecoveresort.com/irmdata/api/irm?sessionID=_rdpirm01&arrival=2021-10-26&departure=2021-10-28&people1=1&people2=0&people3=0&people4=0&promocode=&groupnum=&rateplan=RACK&changeResNum=&roomtype=&roomnum=&propertycode=&locationcode=&preferences=&preferences=&preferences=&preferences=&preferences=WTF&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&masterType=&page=&start=0&limit=12&multiRoom=false"

payload={}
headers = {
   'authority': 'reservations.piratecoveresort.com',
   'method': 'GET',
   'path': '/irmdata/api/irm?sessionID=_rdpirm01&arrival=2021-10-26&departure=2021-10-28&people1=1&people2=0&people3=0&people4=0&promocode=&groupnum=&rateplan=RACK&changeResNum=&roomtype=&roomnum=&propertycode=&locationcode=&preferences=&preferences=&preferences=&preferences=&preferences=WTF&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&preferences=&masterType=&page=&start=0&limit=12&multiRoom=false',
   'scheme': 'https',
  'accept': 'application/json, text/plain, */*',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'en-US,en;q=0.9',
  'authentication': '',
  'content-type': 'application/json; charset=utf-8',
  'cookie': 'rdpirm01=',
  'dnt': '0',
  'referer': 'https://reservations.piratecoveresort.com/irmng/',
  #'sec-ch-ua': "Chromium";v="94", "Google Chrome";v="94", ";Not A Brand";v="99",
  'sec-ch-ua-mobile': '?0',
  'sec-ch-ua-platform': "Windows",
  'sec-fetch-dest': 'empty',
  'sec-fetch-mode': 'cors',
  'sec-fetch-site': 'same-origin',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36',
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)

Result
Session Expired
Answer: You're getting session expired because the session cookie (and authentication token possibly too) are expired. You can fix this using a requests session which will set these session headers for you. Read more here:
https://docs.python-requests.org/en/master/user/advanced/
Comment: Thank you so much for the quick response. I made the change and now I get a Not authorized result. Any suggestions? Thanks again!
Comment: Your authentication token (the authentication header) is likely out of date. There are two ways to go about this, a short-term fix would be to login to the site, go to the request headers in the network dev tools and copy the authentication header. The better solution would be using the session you can log in via requests making a request to the login page with your username and password. If this is done correctly it will set your authentication token for your session. I would recommend using a tool like postman to view the structure of the requests/responses


Recommended method to upgrade PHP 5.1.6 to 5.2.x on CentOS 5.4

Question: It's been awhile since this type of question was asked here. Perhaps the recommended solution has changed.
I have a CentOS 5.4 mail server running RoundCube webmail. By default, RoundCube expects PHP version 5.2 or above. CentOS 5 is stuck at revision 5.1.6 with backports of certain features from 5.2. I disabled the PHP check for Roundcube and it works well. However, one of the plugins I would like to use uses a method introduced in PHP 5.2.
Due to the binding of PHP and Postgres/MySQL in this case, what is the best way to upgrade the PHP version from 5.1.6 to 5.2.x? I've seen 3rd party repos, CentOS testing, Fedora... or I could compile from source. I'd like to keep this system in a stable state so that it doesn't blow apart during the next round of updates.
Any recommendations?
Answer: I've done this many times using the atomic repos. In very simple terms, three steps are all that's needed in most situations:
wget -q -O - http://www.atomicorp.com/installers/atomic.sh | sh
yum update php
service httpd restart

I obviously can't guarrente it will work for you, but for myself this has become the standard method.
Comment: I ended up using this solution.
Comment: +1 for atomic repos, i use them too.
Comment: +1. 1 minute job. just works.
Answer: Simply Install Remi repo. And Run:
yum update -y
and wait until the updates have finished, then reboot your VPS using init:
init 6
Now you have successfully updated php on your system.
Comment: Why should anyone reboot?
Answer: I'd say that any of those methods MAY work fine, but you won't know until you try it, so you better make sure your backups are in order. That being said, upgrading php is much easier on Linux than on Windows, and I'd be surprised if you had any problems. Assuming your install is, if not vanilla, at least a common install, you should be fine with a pre-packaged RPM.
It is possible to run different versions of php on the same webserver; unfortunately you can only run one as an Apache module, which leaves you fiddling around with the CGI interface.
The beauty of modern RPM is that you can roll back the install. That will make it a little easier.
On the other hand, if you build from source, you can just build it in a different directory. Then all you have to do is change which mod php apache loads, and change the location of the php.ini file, and you've upgraded without any risk to your current configuration.
Answer: I believe there a number of solutions, and the one you pick depends on your style of system administration.
The 'easy' way is to install php and related packages from another repository, like this one. The upside is that it takes less time, the downside is that you are trusting an outside source for your binaries on your system, both for timely updates and for maintaining the integrity and security of the packages.
The 'hard' way is to compile your own. I say it is 'hard' but it really is not too bad. What I do is I have the ./configure commands all saved, so when a new release is put out, I simply have to use the same switches to get my php environment the same as it was for prior releases.
For systems without fussy requirements I use the rpm rout (actually 5.1 works fine for those systems), but for those with custom php environments I still compile from source.
Another benefit of compiling php on your own is that you actually understand and learn more about the software and how it works on your server. You can take pride in that and it will set you apart from some other sysadmins!


Discord Python, creating a Channel and moving directly people to it?

Question: I already created this code:
#Creating the Channel
        guild = bot.get_guild(771495836701425725)
        await guild.create_voice_channel(f"Rainbow Ranked for {members2move}", category=940356081891287110, user_limit=members2move)
        print("Created a new Voice Channel!")
        print(f"Moving {members2move} People.\n{string_message_split}")
        async def move(ctx, channel : discord.VoiceChannel)
        bot.move_member(person_to_move, channel_to_move_person_to_move_to)

But i dont know how i can get the ID from the Channel i recently created
Comment: your naming convention is so... strange
Comment: @ŁukaszKwieciński at least it's descriptive :)
Answer: create_voice_channel returns the channel and you can access a channel's id,
apparently you have to pass a channel object to the move_member function not just the id
#Creating the Channel
        guild = bot.get_guild(771495836701425725)
        v_channel = await guild.create_voice_channel(f"Rainbow Ranked for {members2move}", category=940356081891287110, user_limit=members2move)
        print("Created a new Voice Channel!")
        print(f"Moving {members2move} People.\n{string_message_split}")
        async def move(ctx, channel : discord.VoiceChannel)
          person_to_move.move_to(v_channel)

Comment: Thank u very much, i will try it as soon as Discord works again. Do u prolly know, why bot.move_member doesnt work? so it marks "move_member" and says: Unresolved attribut reference "move_member" in class bot
Comment: I just learned that it was changed, the method is now move_to() that you call on a member. I have edited my answer appropriately. Here is the reference [move_to](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.move_to).
Comment: Oh okay, thank u very much man :D
Comment: I tried also something:
guild = bot.get_guild(771495836701425725)
            message_authorid = await guild.get_member_named(name=message.author)
            user_ids2move = user_ids.extend(message)
            print(message_authorid)

But when i try it, somehting with member has no len shows up, but idk why
Comment: i forget to mention, that i want to get the ID from a name
Comment: I didn't quite understand what you meant, but you can get the author id with message.author.id. The error is probably caused by the name parameter, you are trying to pass the Member object instead of the name. Here's the reference for the [Member](https://discordpy.readthedocs.io/en/latest/api.html?highlight=member#discord.Member) class.
Comment: thanks a lot, u helped me very much
Answer: When you create a channel, the channel is returned by the create_voice_channel function. You should be able to get the channel (and so the ID of the channel) like this:
    guild = bot.get_guild(771495836701425725)
    channel = await guild.create_voice_channel(f"Rainbow Ranked for {members2move}", category=940356081891287110, user_limit=members2move)
    print(f"Created a new Voice Channel; it has the ID {channel.id}!")

Answer: import discord
from discord.ext import commands
import os

client = commands.Bot(command_prefix='>')

@client.event
async def on_ready():
    print("Log : "+str(client.user))

@client.event
async def on_voice_state_update(member, before, after):
    if member.guild.id == guild id:
        channel = after.channel
        try:
            if before.channel.members == [] and not before.channel.id == channel id:
                if before.channel.category_id == category id:
                    await before.channel.delete()
        except:
            pass
            if channel.id == channel id:
                    channel = await after.channel.clone(name=f"{member.name}'s Channel")
                    await member.move_to(channel)

client.run("token")


Testar conteúdo de variável

Question: Usando ASP.Net MVC e AngularJS testei o conteúdo de um campo da view assim:
$scope.estado.ldRedeBasica =  @(Model.ldRedeBasica == null ? "[]" : Html.Raw(Model.ldRedeBasica));

Só que retornou o seguinte erro:

Mensagem de Erro do Compilador: CS0173: O tipo de expressão condicional não pode ser determinado porque não há conversão implícita
  entre 'string' e 'System.Web.IHtmlString'

O interessante é que em outra parte do código funciona:
$scope.ViewBag.Impostos = @(ViewBag.Impostos == null ? "[]" : Html.Raw(ViewBag.Impostos));

Com contornar este problema?
Answer: Faça assim:
$scope.estado.ldRedeBasica =  @(Model.ldRedeBasica == null
                                ? new MvcHtmlString("[]") // ou poderia ser `Html.Raw("[]")`
                                : Html.Raw(Model.ldRedeBasica));

    Documentação do MvcHtmlString
O erro ocorre pois Html.Raw não retorna string, mas sim uma implementação do tipo IHtmlString.
Imagine a situação:
var x = (condicao == true) ? "string" : 32784;

Qual seria o tipo de x?... impossível dizer. O erro que você tem é do mesmo tipo do erro acima.
Para ser possível determinar o tipo de uma condição usando operador ternário, é necessário que uma das expressões seja conversível para o tipo da outra expressão... que não é o caso.

nem de string para IHtmlString
nem de IHtmlString para string

Agora, para saber o motivo do outro código funcionar, ai será necessária uma investigação mais profunda... não sendo possível dizer só com o que foi posto.
Comment: Agradeço a resposta! Realmente não retornou o erro original. Agora esta retornando _Uncaught SyntaxError: Unexpected token ;_ no console o código esta assim: `$scope.estado.ldRedeBasica =  ;`.
Comment: De que tipo é `Model.ldRedeBasica`?
Comment: Se for um array ou lista, você deverá serializar o objeto para JSON antes de usar `Html.Raw` nela.
Comment: Resolvi assim: `$scope.estado.ldRedeBasica =  @(String.IsNullOrEmpty(Model.ldRedeBasica) ? Html.Raw("[]") : Html.Raw(Model.ldRedeBasica));`. Obrigado pela ajuda.
Comment: Pelo que disse, dá para ver que o tipo é string. Use `String.IsNullOrWhiteSpace` ao invés disso, para descartar também a possibilidade de espaços em branco.
Comment: Foi mal é String mesmo! Vou fazer a alteração. Mais uma vez obrigado!

Testar conteúdo de variável


$base_path is not added to AJAX URL request in login form

Question: I have a D7 site in a subfolder, and would like for AJAX requests to find the correct docroot folder.
When trying to login from localhost/mysite/user, AJAX sends a request to localhost/system/ajax. I've read that you can use the global variable $base_path for this, so I gave it a try, still the same error. I've checked in Firebug and indeed Drupal.settings.basePath does have the correct path. In settings.php is it written like this $base_path = '/mysite/';.
This made me wonder if the JS logic does not include the $base_path value by default and what would be a correct way to add this in. The site is tracked in Git, so I've also experimented with Apache configurations, such as ProxyPass, ProxyPassReverse, and ReWrite rules in order to prevent having to push changes that would risk breaking the site on the remote server.
I'm new to Drupal and not so experienced with Apache directives, any help here would be awesome :)
Answer: First off, in the settings.php file you should have an example of http://www.example.com and a comment there, saying that you should not append a trailing slash.
Next, in your case looks like http://localhost would be the correct value of $base_url, if any - try hashing out $base_url line to see if the site is fine without it - as it might be.
Comment: Hi, I'm confused, is it the same problem that's referred above? To state is very shortly: `$base_path` is not included in AJAX requests when a form, such as a login form is submitted.
Comment: Assuming `mysite` is at the root of htdocs, you could try `$base_url = 'http://localhost/mysite';` I prefer to establish a fake domain such as `mysite.localhost.com` - (http://www.codingcereal.com/2011/05/setting-up-multiple-subdomains-in-your-localhost-using-xampp/). Then, I'm usually fine with base_url commented out. Just give it a try - the AJAX requests should point to correct location.
Comment: `$base_url` is set to `http://localhost/mysite` and `$base_path` is set to `/mysite/` assuming `$base_url` and `$base_path` are not the same thing, correct? Or is the formatting wrong? Should a path start with the disk-mount's root folder? See [reference](http://api.drupal.org/api/drupal/globals). Because `Drupal.settings.basePath` is available, I assume that I must supply the global `$base_path` a value as well.
Comment: I will have a look into the suggestion you mentioned, I thought there would be some way that Drupal would add a base when the relevant variables are added to settings.php or if there is a Drupal way of injecting the base information somewhere in the codebase.
Answer: Took suggestion from Artur, problem solved by defining two domains in hosts file. One for the development environment and the other as a backup of the production environment. Then it was a case of setting up virtual hosts like this in httpd.conf (example for the development environment):
NameVirtualHost *:80
<VirtualHost *:80>
    ServerName www.project.devel
    ServerAlias project.devel *.project.devel
    DocumentRoot /www/mysite/devel/docroot/
    RewriteEngine On
    RewriteOptions inherit
</VirtualHost>

Login also worked even when domain was removed from the English language row in the languages table in the Drupal database. $base_url and $base_path also were commented out in settings.php, not needed with fake domains.


Postfix & Office 365: relay all outbound email (including local) but deliver inbound email

Question: We're slowly migrating over to Office 365 away from Postfix/Dovecot, with the goal of enabling a few users at a time. Mail for our domain should come in to Office 365 then if there's no address match found within Office 365, it should get forwarded on to Postfix which delivers it to a Dovecot mailbox (we are using a virtual users setup, all users being stored in a separate LDAP server). This allows us to use Office 365 for users that have been set up, but for others that haven't, mail goes to the existing Postfix/Dovecot system.
I have followed these instructions on making connectors etc and it works - after whitelisting EOP IPs, Office 365 will deliver to Postfix fine. The problem is getting things to go in the opposite direction. All outgoing email should be relayed through Office 365, and if I set a relayhost variable and remove our local domain from mydestinations then this works... but then Postfix won't deliver any incoming mail (results in a bounce loop). If I keep our domain in mydestinations then mail gets delivered locally and doesn't go through the relay, which means that users still on the Postfix system are unable to send email to Office 365 users.
Is there a way to force all outbound email (including locally delivered) to go via the relay yet still accept inbound email for the same domain? I've been running up against a wall all yesterday and the only real solution I can think of is to run two separate Postfix instances - one that relays everything and the other that is just used for incoming mail. But surely there's a way to do this with just one instance? I've searched but everywhere just seems to assume you're only relaying email and doing nothing else.
postconf -n looks like this (domain changed to example.com). I've taken out all the changes I made in the attempt to get Office 365 relaying:
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
content_filter = smtp-amavis:[127.0.0.1]:10024
dovecot_destination_recipient_limit = 1
inet_interfaces = all
inet_protocols = all
mailbox_command = /usr/lib/dovecot/deliver
mailbox_size_limit = 0
mailbox_transport = dovecot
message_size_limit = 20480000
mydestination = $myhostname, silver.example.com, localhost.example.com, localhost, example.com
myhostname = smtp.example.com
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 192.168.0.0/24 192.168.10.0/24
myorigin = /etc/mailname
readme_directory = no
receive_override_options = no_address_mappings
recipient_bcc_maps = hash:/etc/postfix/recipient_bcc
recipient_delimiter = +
relayhost =
smtp_tls_note_starttls_offer = yes
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
smtpd_recipient_restrictions = check_recipient_access hash:/etc/postfix/recipient_access, check_sender_access hash:/etc/postfix/sender_access, check_sender_access cidr:/etc/postfix/o365, reject_authenticated_sender_login_mismatch, permit_sasl_authenticated, permit_mynetworks, reject_invalid_hostname, reject_non_fqdn_hostname, reject_non_fqdn_sender, reject_non_fqdn_recipient, reject_unknown_sender_domain, reject_unknown_recipient_domain, reject_unauth_pipelining, reject_unauth_destination, reject_rbl_client bl.spamcop.net, reject_rbl_client b.barracudacentral.org, reject_rbl_client zen.spamhaus.org, reject_rbl_client cbl.abuseat.org
smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, defer_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_path = private/auth
smtpd_sasl_type = dovecot
smtpd_sender_login_maps = hash:/etc/postfix/local_senders, ldap:/etc/postfix/ldap_senders.cf
smtpd_tls_CAfile = /etc/ssl/certs/example.com.cabundle
smtpd_tls_cert_file = /etc/ssl/certs/example.com.crt
smtpd_tls_key_file = /etc/ssl/private/example.com.key
smtpd_tls_loglevel = 1
smtpd_tls_mandatory_protocols = !SSLv2,!SSLv3
smtpd_tls_received_header = yes
smtpd_tls_security_level = may
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_tls_session_cache_timeout = 3600s
smtpd_use_tls = yes
tls_random_source = dev:/dev/urandom
virtual_alias_domains = events.example.com
virtual_alias_maps = hash:/etc/postfix/redirect, ldap:/etc/postfix/ldap_virtual_users.cf, ldap:/etc/postfix/ldap_virtual_groups.cf
virtual_transport = dovecot

To get all mail relaying, I could set relayhost = example-com.mail.protection.outlook.com and remove example.com from the mydestinations list, which gets delivery working for Office 365 but then breaks the old system.
I looked into using transport_maps to try sending all emails for specific email addresses (ie. the ones moved to Office 365) via the relay and everything else works locally, but the values in there seem to always get ignored.
I'm totally out of ideas, so if anyone has any I'd be grateful.
Comment: I would setup all users on o365, point MX there and add a subdomain for postfix, use o365 mail enabled contacts to send the emails to the local accounts.  Sadly o365 doesn't have the same dual delivery options that Google app has... Which honestly I would use for this specific case as an inbound relay for both.
Comment: That was my original plan (subdomain + forwarding), but I found if I set up our o365 domain as an internal relay then set up connectors and change MX to point to o365, any email sent to o365 that doesn't match an account instead gets forwarded on to our Postfix system, which is exactly the behaviour I want. Not sure if that's a recent development or not - last year when I looked at this project it didn't seem to be a possibility but maybe I overlooked it.
Comment: Hello @DavidM - I know it's a stretch but I have a similar situation 3 years later with a difference being Postfix doesn't accept emails sent from O365 because it thinks Postfix is authoritative for a domain. Do you have some feedback on what to change in the config to allow this? https://serverfault.com/questions/1066334/configure-postfix-to-allow-servers-send-email-to-it-for-the-domain-postfix-think
Answer: OK I'm not totally happy with this, but I got it working. I feel like there's a more straightforward way though, but I can't figure it out.
After further research, I found that virtual_alias_maps is run before anything in transport_maps, which is why I thought it was being ignored. So if you have addresses being rewritten then whatever the output from the virtual alias rewrites needs to match what you're going to feed into transport_maps. Then my transport_maps hash looks like this:
email@example.com        smtp:example-com.mail.protection.outlook.com
@example.com  :
*       :

This would cause email sent to email@example.com to be relayed to Office 365, but everything else gets delivered locally.
It works, but I still feel like there's a better way to handle this.


Angular objects not recognized -Protractor-net

Question: Script fails on this step on protractor-net ....NgWebDriver.cs file
probably on command step get('$browser') notifyWhenNoOutstandingRequests(callback)   - Any idea on what $browser or notifyWhenNoOutstandingRequests used for?
<code>this.jsExecutor.ExecuteAsyncScript(ClientSideScripts.WaitForAngular, this.rootElement)
angular.element(el).injector().get('$browser').notifyWhenNoOutstandingRequests(callback);
</code>
Answer: Including the angDriver.IgnoreSynchronization=true statement solved it for me. Probably since my application is continuously polling for data so Requests never ends.


A question on linear programming problem (operation research)

Question: Suppose we want to solve the following lpp:

Min $C^T x$ subject to $Ax=b$ where $A$ is a $m \times n$ matrix, $C$ is in $R^n$ and $b$ in $R^m$. Show that if there exists $x$ in $R^n$ with $Ax=b$ and the minimum value is finite (i.e. there is a lower bound) then $C^Tx=k$ ($k$ is a constant) for all solutions $Ax=b$.

How should I proceed? Any help will be appreciated.
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Answer: Try proving the contrapositive: if the problem is feasible but the objective value is not constant, then the problem is unbounded.


Eclipse WindowBuilder generates forms- 1.3.0.jar and miglayout15-swing.jar files in Project directory

Question: I'm having a problem with Eclipse.
I was using the Google WindowBuilder for my very first time and as I watched
into my project directory, there were two new .jar-files
"forms- 1.3.0.jar" and "miglayout15-swing.jar".
Which kind of files are this? I think they aren't even metioned in my source code.
The java application can be run without the files, but I noticed that
no System.out.print commands are executed.
When deleting the files, Eclipse marks the project folder with a red exclamation mark.
Anyone knowing this issue?
How can I get rid of these files?
Answer: Right-click on the project in Eclipse, select Properties | Java Build Path. Under the tab Libraries select forms-1.3.0.jar and click on Remove.
Answer: The file 'forms-1.3.0.jar' is used by the visual swing (or other) editor.

Navigate to the folder eclipse is housed in.
Using the search bar, search for "forms-1.3.0". Not the zipped folder, the jar file above it
Drag it onto the project file with the exclamation mark.

Do the same thing with "miglayout15-swing.jar".
I don't know how to get rid of them, but if you're asking how to get rid of the exclamation mark, this is it.


Expected waiting time with $m$ tellers and $n$ customers at a bank

Question: Suppose we have the following scenario:

There are $n$ customers at a bank who wish to speak with bank tellers.
  There are $m$ tellers, and each of the $n$ customers is willing to
  speak to any of the $m$ tellers. Rather than forming individual lines
  for each teller, the customers form a single queue, and the next
  person in line goes to the next available teller. The amount of time
  each customer spends with the teller is exponentially distributed with
  mean $\lambda$. Compute the expected waiting time for the person next
  in line in the queue. (You may neglect the time it takes someone to
  walk from the queue to the teller.)

Anyone know how to solve this? This isn't a homework question, but rather a question from a class that I took back in college (it is of particular relevance at the moment as I am needing to compute this sort of a quantity for a piece of software that I am writing).
Comment: First in line or last in line?
Comment: First. I would assume that to compute the expected time for the last, you could simply apply linearity of expectation.
Comment: The waiting time for the first in line is the minimum of $m$ independent exponentials. This has exponential distribution mean $\lambda/m$.
Answer: Because you imply there are people queued, I assume $n > m.$
Each person in line begins service when the next teller
becomes available. That happens at rate $m/\lambda,$
so the mean waiting time in the queue for the next customer
is $\lambda/m.$ The mean time until that customer finishes
being served is $\lambda/m + \lambda.$
Notes: (1) To avoid potential confusion, texts on queueing models typically
use $\lambda$ for the rate of arrival of new customers, and
$\mu$ for the service rate.  Means of exponential distributions
are the reciprocals of rates.
(2) The distribution of the waiting time for the minimum of
$k$ exponential waiting times (next available server) is
exponential with a rate of $k$ times the rate for
individual servers (assuming all rates equal).
(3) If you want to look for more on this topic, I suggest you
read about $M/M/k$ queues. The first M stands for (Markov,
memoryless, or exponential) interarrival times, the second
M for exponential service times, and the k for the number
of servers.


Sort NSMutableDictionary in ASC order

Question: In my Xcode Project (Objective-C), i store json Result in a NSMutableDictionary, but the result is in false order direction.
How can i sort a NSMutableDictionary is ASC order on Objective-C.
Here is my NSMutableDictionary:
{
    3 =     (
        11,
        12,
        13,
        14,
        15,
        16,
        17,
        18,
        19,
        20
    );
    2 =     (
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        10
    );
    1 =     (
        0,
        1
    );
    4 =     (
        21,
        22,
        23,
        24,
        25,
        26
    );
}

I expect a sort order 1,2,3,4 for UITableView Section.
Comment: Dictionaries have no order. You would need to create an array from the keys and then sort that array.
Answer: @rmaddy is right,the following is the implementation code, very simple.
- (NSMutableArray *)sortDictionary:(NSMutableDictionary *)dictionary {
    NSArray *sortedKeys = [[dictionary allKeys] sortedArrayUsingSelector:@selector(compare:)];
    NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:sortedKeys.count];
    for (NSString *key in sortedKeys) {
        [sortedArray addObject:[dictionary objectForKey:key]];
    }
    return sortedArray;
}

example
NSDictionary *dict = @{@"3":@{@"3333":@"3333"},
                       @"2":@{@"2222":@"2222"},
                       @"1":@{@"1111":@"1111"},
                       @"4":@{@"4444":@"444"}};

[self sortDictionary:dict];

result:
sortedArray :(
        {
        1111 = 1111;
    },
        {
        2222 = 2222;
    },
        {
        3333 = 3333;
    },
        {
        4444 = 444;
    }
)

Comment: That doesn't fix the issue. Even if you sort the key and store them in "order", order in the print it no guaranteed. Nor the access.
Comment: Thank you, I think I was just confused, the dictionary is unordered.

Sort NSMutableDictionary in ASC order


How do I distinguish my voice singing a c3 from a c4?

Question: I was trying to figure out my voice range, but I actually run against the stupid problem that I don't know if I sing a c3 or a c4. I was using an online piano to match my voice, but I simply don't know if I'm singing a c3 or a c4 to match the note I hear from the piano. (I am sure I'm singing a c, though.)
I've found a video of a guitarist explaining how to determine it, but I am being insecure about it. I probably have a range of something like c2-e4 or a few notes higher, but hey - it might be an octave up?
Comment: I actually do think there's a question here & I really don't think it's a dupe... for someone unused to comparing pitches of instruments with utterly different decays &  overtones, this could be a valid concern & confusing aspect. Just because 'we' can clearly tell the difference doesn't mean everyone can. [On the other hand, how to provide it with a good answer is beyond my ability, I think]
Comment: How do you know you're singing a C of some kind? I mean, what method are you using to determine that it might be c2 - e4?
Comment: Hello and welcome to Music.SE!
You can click [here](http://music.stackexchange.com/help/on-topic)
to see our scope (what/what not to ask) and how to ask questions
[here](http://music.stackexchange.com/help/how-to-ask).
Comment: Hi,
I was using an online piano.
I am editing the question a bit - I have read the posts about determining vocal range, it's about the "how do I distinguish c3 from c4" part, which I could not find.
Comment: You're saying you can't hear the difference between a C3 and C4 on the online piano when comparing it to your voice? They both sound the same?
Comment: @Todd Wilcox : ehh... yess.. I play a c3 on that piano, sing something that matches, but then I press c4 just to check, and it could also be that one.. and then I get insecure... i.e. I measured my voice several times, but i also ended up with c3 being the lowest note (in stead of c2). I THINK it must be c2, but I get really confused.

I don't know if that makes me a completely tone-pitch deaf person..

(EDIT) P.S. I'm also a mathematician. Does not help in explaining this to me i fear ;-)
Comment: Sounds like you need someone else to help you. The beginning of the first answer of the duplicate question is "get a few lessons with a teacher". Sounds like the best answer for you also.
Comment: Hi guys, thanks for the nice answers. I figured out (also by you) that indeed I need to ask someone - it turns out that for me its easy to sing the same tone as another male, but indeed to compare my voice with an "alien" (??) sound like from a piano is a bit difficult for me for some reason. Probably it IS a new question as stated by Tetsujin, but also, the best answer is "ask someone who can hear it". There's only so much you can learn from The Internet (unless there's an online tool to analyze sounds or something).
Comment: I almost asked the exact same question today in fact and it's definitely a valid problem. The human voice is rarely a pure tone. "use a tuner that displays the frequency not just the note" is the right answer. You can double-check your piano is playing the right notes too :)
Answer: You can use one of the various Tuner apps found in app stores if you have a smartphone. There are also Tuners for the PC. These will measure and display the pitch of your sound (voice). That's how I realized that I was singing everything one octave lower and consequently, that I was more of a Barry White than a Michael Jackson.
Personally, I am using AP Tuner for Windows for my PC and DaTuner Lite  for my Android Smartphone. But there should many other programs suitable to your needs.
I reckon unless you are a high voice, that your range is probably C2-E4 and not C3-E5. It's quite unlikely for male voices not to hit notes lower than C3 and extremely unlikely to hit E5.
Comment: Many guitar tuners also do this. Good point that reaching E5 is a bit unlikely, C5 is "tenor high C", right?
Comment: Yes. C5 is the standout note of operatic tenors (though lower tenors might not be able to hit it). It is unlikely to be able to hit C5 in anything other than the falsetto register unless trained/ very lucky. I am a bass baritone, for me C4 already feels quite high whereas C3 sits very comfortably in my range. Once I discovered the octaves I was hitting it became quite easy to align my voice to the right octave. From my experience, modern male singers will stay within C3 and C5 with few deviations.
Comment: Modern pop music seems to be _very_ tenor-focused, right now. So many "girly voiced pretty-boys" ;)
Comment: Thanks a lot!!! This answer answered my question in like 3 seconds after installing that windows program! Indeed, I am in that C2-E4 range :-)
Comment: I've seen basic tuners bounce between octaves when they pick up overtones (components of the sound that are one more octaves higher than the fundamental frequency). Tools that line up a spectral analysis to a keyboard are really good for visualizing overtones and harmonics, and it becomes pretty easy to spot the fundamental frequency.
Answer: Use your piano, press the key, and attempt to match the pitch with your voice. In the beginning students will be insecure about their voices. just keep at it for an hour every daily, if you know do-re-mi you can start little exercises. WHen I studied voice training we sang Do Mi Fa Mi Do, then up a halfstep to C#, , then D, then Eb, then E, so the notes you sing will be
C E G E C
C# F G# F C
D F# A F# D
Eb G Bb G Eb
and so on until the highest note is too high for your personal range, then go back down, until the low note is too low for you.
This will get you going, and your ears will open up!
Comment: There are some mistakes in that exercise (e.g. I think you meant that to be Do Mi Sol Mi Do, and that C# triad is spelled strangely, you probably want to write it in Db).  But I'm not sure how this exercise would help--the OP has no trouble matching a C, they just can't tell you which octave the C is in.


Leaving a Domain effects

Question: I have a server on a DOMAIN running special services on the user account
WHATEVERDOMAINIS\Admin. I want to remove it off the DOMAIN because the controller no longer exist. I am just worried if I do remove it and place it on local account
"Administrator" the services that were installed from WHATEVERDOMAINIS\Admin will no longer work and the programs will be all unconfigured. Any insight?
Answer: Switch that service account to run as a local user with equivalent permissions and then unkoin from the domain. If your AD DS domain is gone then it's just using cached credentials anyway and isn't getting any special rights via it's AD DS group membership.
Comment: when I check the service properties it already says "Local System Account".I assume its already ready to move to local account as is?

Leaving a Domain effects


Como criar um arquivo ZIP no Shell?

Question: Como faço para criar um arquivo ZIP no Shell com os arquivos da data de hoje? Os arquivos estão todos no mesmo diretório.
Comment: Já tentou alguma coisa? Conhece os comandos `zip`, `find` e `man`?
Comment: Eu estava usando o compress-archive
Comment: Mas estava com dificuldades na hora de pegar os arquivos com a data de hoje
Answer: Você pode tentar alguma coisa parecida com:
find . -ctime -1 -iname "*.txt" -exec zip arquivos.zip {} \;
O find tem algumas opções interessantes para procurar arquivos baseados na data de criação, acesso e modificação. Dá uma olhadinha no man dele.

Como criar um arquivo ZIP no Shell?


how to force iPad to load in landscaperight orientation?

Question: I have an iPad app that supports UIDeviceOrientationPortrait and UIDeviceOrientationLandscapeLeft.
I did include this method :
    - (BOOL)shouldAutorotateToInterfaceOrientation:
      (UIInterfaceOrientation)interfaceOrientation
    {
        return (interfaceOrientation == UIInterfaceOrientationPortrait ||
        interfaceOrientation == UIInterfaceOrientationLandscapeLeft );
    }

The issue I have is that I need it to load in the UIDeviceOrientationLandscapeLeft mode, just for the load, because my UI controls will be setup properly. how can I force it only once on load.
One thing I wanna note is that this has to be min iOS 5.
Answer: Even if this answer is not what you expected:
Give yourself a favor: it is really complex to force the device into a specific orientation.
You can search here on SO, what all works and does not work, and works in 6.1 and not in 6.01. and so on.
So fastest and safest is, to fix your code such that it can corectly initialize in both orientations.
Answer: I recently had similar problem, but I wanted to change from Landscape to Portrait by force, I knew in old versions there were built in methods but unfortunately we are never sure when and what is working for us, but I gave this code a try and It worked for me, but my scenario was to forcing from landscape to portrait, which is opposite to your scenario, but anyways it works, here is the code possibly for your scenario;
    -(NSUInteger)supportedInterfaceOrientations

{
    return UIInterfaceOrientationMaskLandscape;

}

-(void)viewWillAppear:(BOOL)animated {

    UIApplication* application = [UIApplication sharedApplication];

    if (application.statusBarOrientation != UIInterfaceOrientationLandscapeLeft)
    {
        UIViewController *c = [[UIViewController alloc]init];
        [self presentModalViewController:c animated:NO];
        [self dismissModalViewControllerAnimated:NO];
    }

    [super viewWillAppear:animated];
}

EDIT working on IOS 6.1 I have added two more methods which I did not add in my previous post, I add now all what is working for my application...
- (BOOL)shouldAutorotate
{

    return NO;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationLandscapeLeft;
}

the idea is to check the statusbar orietnation and add and dismiss a modalViewController and it works for me to force from one to another orientation.
Comment: but where in this code will it actually rotate the statusbar from landscape to portrait? or vice Versa ( depending on your scenario
Comment: I tried this solution (but a variant where they chnaged the orientation of the status bar), It did not work for me, as you can read herre ein SO. It does not work alsways. There does not exist any reliable solution. bye the way, Did you forget to change the orientation of the statusBar?
Comment: check my EDIT in answer, I have this working code in my app, If you have shouldautoRotate set to NO and preferredInterfaceOrientation is landscapeleft, then while displaying the new viewcontroller ,just add a modalViewController and dismiss it within viewWillAppear, this does the trick.
Answer: Update in the Project Settings OR the info file.
In iOS 6.x you should override supportedInterfaceOrientations.
Try also preferredInterfaceOrientationForPresentation.
Comment: but I want the porject to support two orientations after the load, just force it to load in landscape just for the load.
Comment: I added another method to override -  preferredInterfaceOrientationForPresentation. Did you try to see if this force landscape?
Answer: Despite any app Info.plist settings or -shouldAutorotateToInterfaceOrientation: (or -shouldAutorotate) method overrides, view controllers start off in portrait and are then rotated into landscape by iOS.
What is preventing your UI layout from being setup properly?


Qual a diferença entre estas duas expressões booleanas?

Question: Estou verificando a tabela verdade neste site sobre as seguintes expressões:

Porém cada uma delas me resulta em uma saída diferente:
Comment: Se a tabela verdade das duas são diferentes então obviamente existe diferença entre as duas expressões.
Comment: Não entendi qual é a dúvida.
Comment: @Maniero olá meu amigo novamente. Para mim estas duas expressões booleanas são idênticas as duas possuem essas duas entradas barradas, correto? Porém no site que utilizei para gerar a tabela verdade, as mesmas me geram uma saída diferente da outra, isto me mostra que as duas expressões não são idênticas. A minha pergunta foi em cima disto, pois agora estou em dúvida e queria saber qual a diferença das duas se não forem realmente iguais.
Comment: @anonimo isso é obvio, não? Porém a questão que eu quero saber, é o porque da diferença...
Comment: Então estude os teoremas de De Morgan da álgebra booleana que verá que ¬(A AND B) = ¬A OR ¬B e também que ¬(A OR B ) = ¬A AND ¬B.
Comment: É uma relação de identidade, amigo. Isso é baseado nas leis de De Morgan, e é verdade pelo mesmo motivo que 1 + 1 = 2. Se você é um rapaz das práticas basta executar um LogiSim e montar o circuito citado acima. Você vai observar que este é um comportamento de identidade, já reduzido em sua forma mais básica. Em outras palavras, é tipo uma daquelas fórmulas de matemática que você "precisa" decorar. O seu resultado é diferente porque `negar duas portas com AND` e `negar a saída de duas portas com AND` é essencialmente diferente.
Answer: É uma questão de precedência de operações, como ocorre na matemática (multiplicação e divisão sempre ocorrem antes que adição e subtração a não ser que tenha algo os agrupando, como o uso de parênteses), ou em toda expressão em códigos que escrevemos no computador, acho que posso posso falar assim porque já conhece isso.
A imagem é clara para quem conhece bem o assunto, mas as tabelas que estão na pergunta deixam mais claro até para quem não conhece isso que é bem diferente.
O ponto é um operador lógico AND (já falei sobre ele em código) que diz que para o resultado ser verdadeiro os dois operando devem ser verdadeiros, o resto sempre dá falso. O apóstrofo nega o operando dele (NOT), ou seja, o que é verdadeira vira falso e vice versa. Os parenteses agrupam a operação e o que está dentro deve ser realizado antes do que está fora, portanto o que está fora operará com o resultado de tudo o que está ali dentro.
Então na primeira tabela pega B e o nega, afinal o operador de negação está próximo dele. Ele tem prioridade sobre o outro operador. C também é negado. Com os dois valores negados procede-se a relação de E. A primeira expressão tem 0 e 0, então ambos são negados individualmente, e ficam 1, aí 1 E 1 dá 1. Na segunda linha e demais é feito o mesmo, mas como sempre pelo menos um deles fica 0, o E exige que ambos sejam 1 para dar 1, então o resultado é 0.
A segunda tabela muda por causa dos parenteses. B é relacionado com C através da operação de E e esse resultado obtido é negado pelo operador que está valendo para todo o valor resultando dentro dos parenteses. Nas três primeiras linhas há um 0, então o resultado será 0 porque o E exigue que ambos sejam 1 para dar 1, aí dando 0 há uma negação e o resultado final fica 1. Na última linha ambos são 1, então dá 1 e negado o final dá 0.
As tabelas estão invertidas em relação à imagem.
Comment: Obrigado meu amigo!
Answer: Após ler alguns livros, estou respondendo a minha própria pergunta com mais detalhes e dando ênfase ao que realmente é importante e a qual foi o intuito da pergunta..

Seguindo a Tabela Verdade acima é possível notar a diferença entre as portas lógicas e o mais importante, que é o "tipo de simbologia da barragem" das entradas".
Utilizando estas entradas como exemplo:

Podemos observar que as saídas de  é diferente de , pela seguinte questão:

A primeira expressão booleana está barrando as entradas A e B
A segunda expressão booleana está barrando as saídas da porta lógica AND das entradas A e B. Sabendo-se disto com a "simbológica desta barragem", devemos aplicar o Teorema de De Morgan.

Nota

Com a aplicação do teorema na segunda expressão podemos observar que na verdade ela é:  (tanto que esta mesma expressão booleana possui a mesma saída da expressão booleana ).
O mesmo vale para a expressão booleana , quando aplicado o teorema citado esta expressão é equivalente a: .
Comment: Sendo bem sincero, achei que a outra resposta respondeu de forma mais completa a pergunta. A sua resposta basicamente copiou o que já tinha na pergunta e citou vagamente o teorema de De Morgan. Pelo texto, basicamente é dito que é diferente porque é diferente. Talvez completar a resposta com o uso a fundo do teorema e **mostrar** porque as tabelas verdades são diferentes ficaria mais completa.
Comment: @AndersonCarlosWoss a resposta do usuário acima foi aceita, porém complementei a minha com um pouco mais de ênfase no que realmente eu queria saber, não expliquei utilizando o tereoma de demorgan pois eu já estou supondo que os outros usuários saibam o mesmo, apliquei apenas o raciocínio correto que deve ser para os dois tipos de expressões lógicas, obrigado.


PHP texto do banco para html

Question: Estou com problema para retornar texto com formatação HTML para a view. Preciso retorna-lo com quebra de linhas. Tentei também coloca-lo sem as tags HTML no banco e depois utilizei a função nl2br() que transforma /n na tag
, porém em ambos os casos ele retorna com "" aspas entre o texto como está na imagem abaixo do firebug. Tentei com diferentes funções PHP para retirar as aspas, mas sem sucesso.
Answer: Se você quiser tirar essas aspas aí você terá que fazer assim:
 trim(nl2br($texto));

A não ser que na hora que você está imprimindo a variável você tenha feito assim:

   <?php echo  nl2br($texto); ?>

Porque nesse caso, a quebra de linha dada na div conta como espaço (o que gera aquelas aspas no interpretador do firebug).
No caso, você pode fazer assim:

<?php echo trim(nl2br($texto)) ?>

Fiz o seguinte teste para você verificar que meus dois últimos exemplos possuem diferenças:
<?php ob_start() ?>

Meu nome é Wallace

<?php var_dump(ob_get_clean()) ?>

<?php ob_start() ?>

    Meu nome é Wallace

<?php var_dump(ob_get_clean()) ?>

Os resultados são:
string(31) "
Meu nome é Wallace

"

string(34) "

    Meu nome é Wallace

"

Perceba aí que essas quebras de linha são processadas como conteúdo da string.
A primeira string ficou com a aspa em baixo porque precisei dar uma quebra de linha para colocar o var_dump(ob_get_clean())
Comment: @Bia não que não fosse a forma correta, fora de mim afirmar isso. Apenas fiquei na dúvida se era a melhor forma, mas pelas explicações do Wallace, tá mais que provado :)
Comment: Funcionou, obrigada.
Comment: Pensei nisso também, mas fiquei na dúvida se era a maneira correta hehe
Comment: +1 ta ligeiro hein hsausha
Comment: também uso essa forma, porque não seria correta? @DiegoFelipe
Comment: Vou deixar a resposta mais completa. Aguardem os prints
Answer: Se não for visível no seu html estas aspas duplas a explicação delas aparecerem no seu element inspector é simples: Organização do texto.
Como citado nesta resposta : SOEN

Original
This is just the way that chrome presents the text node content in the
element inspector. You can see white-space better this way. The quotes
are purely virtual.
Tradução
Esta é apenas a maneira que o Chrome apresenta o conteúdo do nó de
texto no Inspetor de elemento. Você pode visualizar melhor assim. As citações são puramente virtual.

Caso exista as aspas no seu html use trim para remove-las:
Exemplo:
$str = '"Hello"';
echo trim($str, '"'); // saída: Hello

Comment: @WallaceMaxters foi o que eu pensei, estou acostumado a utilizar apenas o Firebug no mozilla, utilizei o Inspecionar Elemento do Chrome e meus textos também possuem Aspas duplas, parece que é do programa mesmo, se as aspas não aparecerem na visualização ela não deverá se preocupar.
Comment: Estamos nesse caso pressupondo que o problema seja as àspas salvas no banco. Mas ainda acho que não é isso. As aspas não são das palavras e sim do interpretador do `firebug`
Answer: Acredito que o problema não é com a função nl2br. Verifique a saída antes de aplicar a função para ter certeza. Parece também que o firebug coloca aspas automaticamente no console quando se trata de mais de uma linha, para melhorar a visualização.
Comment: +1 Apenas não compreendo o por que de tantos negativos, se vocês  verem nesta resposta do SOEN  perceberam que o element inspector age assim: http://stackoverflow.com/questions/12608899/chrome-adding-quotes-to-html
Comment: Oi amigo, obrigado pela referência. Não se trata de negativos em relação ao firebug. A questão é identificar se a situação apresentada é um "problema" (resposta com aspas a partir do PHP), e **resolvê-lo**, ou apenas um comportamento do firebug (resposta sem aspas do PHP, apresentado com aspas no console).

PHP texto do banco para html


Pivot Creates an extra Row for Null values of Pivot Key

Question: I am using oracle sql developer and trying to pivot in based on IssueId and expecting to get one row. But it creates an extra row for null values of issue but I want all values in one row. Please, see below scenario for better explanation of this confusing problem.
Table I have after joins :
Data:

Current Result with Extra Null Row:

Expected Result:

My Query:
select *
from
(
select  TableB.SEQ_ID,TableA.ISSUEID , TableC.Question
from TableC RIGHT JOIN  TableB  ON TableC.QUESTIONID = TableB.QUESTION_ID
LEFT JOIN TableA ON TableB.QUESTION_ID = TableA.QUESTIONID AND ISSUEID = 3250

) d
pivot
(
  MAX(Question)
  for SEQ_ID   in ( 1, 2, 3 ,4, 5 )
) piv;

Any suggestions related to this is appreciated. Thank You!
Comment: [Please post formatted text not images](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557).
Answer: Assuming the intermediate result set is what you expect to see and the left/right outer joins are necessary for what you're trying to do, you could just replace the null issue IDs from rows not matching in table A, using an analytic aggregate:
max(TableA.ISSUEID) over () as ISSUEID

With sample data that gets the same intermediate result you showed, the modified inner query:
select  TableB.SEQ_ID, max(TableA.ISSUEID) over () as ISSUEID, TableC.Question
from TableC
RIGHT JOIN  TableB  ON TableC.QUESTIONID = TableB.QUESTION_ID
LEFT JOIN TableA ON TableB.QUESTION_ID = TableA.QUESTIONID AND TableA.ISSUEID = 3250;

gets
    SEQ_ID    ISSUEID QUESTION
---------- ---------- -------------
         1       3250 How are You?
         2       3250 Hows it going
         3       3250 Is It Okay?
         4       3250 Whats Up?
         5       3250 Really?

and when pivoted:
select *
from
(
  select  TableB.SEQ_ID, max(TableA.ISSUEID) over () as ISSUEID, TableC.Question
  from TableC
  RIGHT JOIN  TableB  ON TableC.QUESTIONID = TableB.QUESTION_ID
  LEFT JOIN TableA ON TableB.QUESTION_ID = TableA.QUESTIONID AND TableA.ISSUEID = 3250
) d
pivot
(
  MAX(Question)
  for SEQ_ID   in ( 1, 2, 3 ,4, 5 )
) piv;

gets
   ISSUEID 1             2             3             4             5
---------- ------------- ------------- ------------- ------------- -------------
      3250 How are You?  Hows it going Is It Okay?   Whats Up?     Really?

You could get the same result with:
select * from (
  select b.seq_id, a.issueid, c.question
  from tableb b
  join tablec c on c.questionid = b.question_id
  cross join (
    select issueid from tablea where issueid = 3250
  ) a
) d
pivot
(
  max(question)
  for seq_id in (1, 2, 3 ,4, 5)
);

(or cross apply in 12c+), which also works with condition >= 3250. This just lists all five questions against every matching issue ID. That may not actually be what you want to do, but it's what your very limited sample data and expected results suggest.
Comment: This will work only for one issueid! In my case there are hundreds of them.
Comment: Your query is filtering on a single one. We can't guess what you really want to do.
Comment: I did that to make the scenario clear. Actually the condition is TableA.ISSUEID > 3250 instead if TableA.ISSUEID = 3250. So there will be multiple rows after transpose based on different IssueIDs.
Comment: @Programmermid - but if they all end up with all the questions anyway, what's the point of the joins? You seem to want to just show one row for every issue ID which shows all five questions. If that isn't what you want then you should ask a new question with more representative data and expected results.
Answer: If you only want valid issues, then don't mess around with all those outer joins.  Just start with the table that has the rows you want to keep, us left join for the other tables, and filter the first table in the where clause:
from (select TableB.SEQ_ID, TableA.ISSUEID , TableC.Question
      from TableA LEFT JOIN
           TableB
           on TableB.QUESTION_ID = TableA.QUESTIONID LEFT JOIN
           TableC
           on TableC.QUESTIONID = TableB.QUESTION_ID
      where  tableA.ISSUEID = 3250
     ) d


Trigonometric Identities help

Question: How do you solve this? I can't figure out what I should do.
$$\sin ^4\left(A\right)+\cos ^2\left(A\right)=\cos ^4\left(A\right)+\sin ^2\left(A\right)$$
Also, why is this equal zero? Can someone explain how that simplifies to be zero?
$$\frac{\left(\frac{1}{\cos \left(x\right)}\right)-1}{\left(\frac{1}{\cos \left(x\right)}\right)+1}+\frac{\cos \left(x\right)-1}{\cos \left(x\right)+1}$$
Comment: Please ask one question per question, unless they are intricately related.
Answer: Note that $\sin^4 A-\cos^4 A=(\sin^2 A-\cos^2 A)(\sin^2 A+\cos^2 A)=\sin^2 A-\cos^2 A$.
For the other question, we have $\frac{1}{\cos x}-1=\frac{1-\cos x}{\cos x}$ and $\frac{1}{\cos x}+1=\frac{1+\cos x}{\cos x}$. When we divide, the $\cos x$ cancel, and we get $\frac{1-\cos x}{1+\cos x}$.
Answer: You just have to know that:
$\sin^4(a)=\sin^2(a)\sin^2(a)$
$\cos^4(a)=\cos^2(a)\cos^2(a)$
$\sin^2(a)+\cos^2(a)=1$

$$\begin{align}
\sin^4(a)+\cos^2(a)&=\cos^4(a)+\sin^2(a) \\
\sin^2(a)\sin^2(a)+\cos^2(a)&=\cos^2(a)\cos^2(a)+\sin^2(a) \\
\sin^2(a)\left(1-\cos^2(a)\right)+\cos^2(a)&=\cos^2(a)\left(1-\sin^2(a)\right)+\sin^2(a) \\
\sin^2(a)-\sin^2(a)\cos^2(a)+\cos^2(a)&=\cos^2(a)-\sin^2(a)\cos^2(a)+\sin^2(a) \\
1-\sin^2(a)\cos^2(a)&=1-\sin^2(a)\cos^2(a) \\
0&=0 \\
\end{align}$$
Answer: For the 1st problem there's a little trick: add zero.
\begin{array}{lll}\sin^4A+\cos^2A&=&\sin^4A+(-\cos^4A+\cos^4A)+\cos^2A\\
&=&(\sin^4A-\cos^4A)+\cos^4A+\cos^2A\\
&=&(\sin^2A-\cos^2A)(\sin^2A+\cos^2A)+\cos^4A+\cos^2A\\
&=&(\sin^2A-\cos^2A)+\cos^4A+\cos^2A\\
&=&\cos^4A+\sin^2A
\end{array}
For the other problem, the trick is to multiply by one.
\begin{array}{lll}
\frac{\left(\frac{1}{\cos \left(x\right)}\right)-1}{\left(\frac{1}{\cos \left(x\right)}\right)+1}+\frac{\cos \left(x\right)-1}{\cos \left(x\right)+1}&=&\frac{\left(\frac{1}{\cos \left(x\right)}\right)-1}{\left(\frac{1}{\cos \left(x\right)}\right)+1}\cdot\frac{\cos(x)}{\cos(x)}+\frac{\cos \left(x\right)-1}{\cos \left(x\right)+1}\\
&=&\frac{1-\cos(x)}{1+\cos(x)}+\frac{\cos \left(x\right)-1}{\cos \left(x\right)+1}\\
&=&\frac{1-\cos(x)}{1+\cos(x)}-\frac{1-\cos(x)}{1+\cos(x)}\\
&=&0
\end{array}

Trigonometric Identities help


Conjecture similar to Fermat's Theorem.

Question: I was wondering about a problem which i could reduce to asking the following
Does there exist a set $a,b,c$ of prime numbers such that $$a^a+b^b=c^c$$
Is it really a tough problem or do you think it can be solved with some amount of work .
Thank you for your ideas and help .
Comment: Out of curiousity, what contest is this coming from?
Answer: Assume $a, b, c$ are primes with $a<b<c$. Then $b$ and $c$ are both odd, so that $a^a$ must be even, so that $a=2$.
Then we have $4+b^b=c^c$, but with $c$ being at least 2 more than $b$, this is impossible, so there are no solutions with all primes.
Edit:
A slightly different argument shows that there are no solutions in natural numbers even if we do not insist that $a, b, c$ be prime:
$$(n+1)^{n+1} > n^{n+1} = n\times n^n$$
so that for $n > 2$ we have
$$(n+1)^{n+1} > 2n^n \geq a^a + b^b$$
for any $a, b \leq n$, so it is impossible to add 2 terms of the sequence $1^1, 2^2, 3^3, \ldots$ to get another term of the sequence.
Comment: What about not prime solutions?
Comment: Pretty sure there are none of those either, but no time to look at it at the moment. Might be worth a new question? (or might be very easy).

Conjecture similar to Fermat's Theorem.


Adjusting background-position of image pieces

Question: I'm trying to make a puzzle out of a background image with numbered pieces. The pieces will eventually be movable with javascript. Right now, I'm stuck simply trying to position the pieces of this image. The html has a div with id called puzzlearea, and I have appended children with javascript, which I know works because it displays the new div pieces and their numbers. The CSS refuses to move the pieces relative to this background, and my two test pieces are stuck in the top left corner, seemingly ignoring my background-position values. Here is the CSS:
body {
   text-align: center;
   font-family: cursive;
   font-size: 14pt;
}

#puzzlearea {
   width: 400px;
   height: 400px;
   margin: auto;
   position: relative;
   background-image: url("planck-image.png");
}

.tile {
   font-size: 40pt;
   color: red;
   line-height: 70pt;
   width: 90px;
   height: 90px;
   border: 5px solid black;
   background-position: -200px -200px;
   position: fixed;
}

Update: Screenshot.
Would you have any ideas as to why the positioning is not occurring?
Comment: A Working example (jsfiddle.net or stacksnippets) are useful. However, your image in gdrive needs permission. Don't share like this, are not useful. Talking about your issue, **fixed positioning are attaching to the root document, not to the parent relative element**. Change to `absolute` instead
Comment: It would be helpful if you show an image of what is happening (and possibly of what you expect). As we can't see the planck-image.png, it is tough to guess what is needed.
Comment: Ok, I've added a link to a screenshot. I'm not reputable enough to just paste the image here.
Comment: Sorry, wrong link. It should work now. I also tried changing .tile to position: absolute, but no effect.
Answer: You need position: absolute on .tilein order to be able to place them with the top/bottom/left/right parameters (and you need those too).
fixed position refers to the viewport, not the parent element.
Comment: Ok, it seems I was missing the left/right, etc. parameters. Rookie mistake. Absolute is right. Thanks for your help!


How to change Run window view to just the output in IntelliJ in a Gradle-based project

Question:
It currently looks like this, which is very similar to the Debug window's console, and which I do not like.
Before it used to show something along the lines of
<code>*java kotlinc stuff like that commands here(It was condensed so I'm not sure on the exact details)*

Part 1: 232
Part 2: 1783
</code>
Now it shows the above screenshot.
I'm not sure what caused this issue, I was having a few issues with the Kotlin plugin, I proceeded to reinstall and restart IntelliJ it which fixed the issues I was having but it changed the view to this.
I'm running on version 2020.3.1 of IntelliJ Ultimate
Answer: For Gradle-based projects, IDE by default delegates the build and run actions to Gradle.
If you want to run and build with IDE's own runner and builder, switch to IntelliJ IDEA the Settings (Preferences on macOS) | Build, Execution, Deployment | Build Tools | Gradle | Build and run using.
See also Configure the build and run actions documentation about this functionality.