Differential equation where Picard-Lindelöf can not be applied

Question: My question is the following :

Let $f:\mathbb{R}\to\mathbb{R}$ be  continuous function and let $u:[a,b]\to\mathbb{R}$ be a $C^1$ function such that
  $$\forall t\in[a,b],u'(t)=f(u(t))\text{ and }u(a)=u(b)=k\in\mathbb{R}.$$
  Show that $u$ must be constant.

What I have done :
We show that $\max u=k$ (and a similar proof would show that $\min u=k).$ Let's suppose that $\max u=M>k.$ We note $c\in]a,b[$ a point such that $u(c)=M.$ The mean value theorem give us a point $d^+\in ]a,c[$ such that $$u'(d^+)=\frac{u(c)-u(a)}{c-a}=\frac{M-k}{c-a}>0.$$ We note $m=u(d^+).$ The intermediate value theorem tell us that it exists a point $d^-\in]c,b[$ such that $u(d^-)=m$ : we can suppose that $u'(d^-)\leq 0,$ else we would have that, for all $x\in]c,b[$ such that $u(x)=m,$ $u'(x)>0.$ It would be true in particular for $x_{max},$ the biggest $x$ such that $u(x)=m$ : as $u'$ is continuous, it would give us $u'(t)>0$ for $t$ in a neighborhood $[x_l,x_r]$ of $x_{max},$ which would implies $$\int_{x_{max}}^{x_r}u'(t)\,dt=u(x_r)-u(x_{max})>0,$$ and so $u(x_r)>m.$ By continuity of $u$, it is impossible (mean value theorem applied to $u$ on $[x_r,b]$ : there would be no point in this interval which would reach $m$, while $u(x_r)>m$ and $u(c)<m$). Finally, we have two points $d^+$ and $d^-$ such that
$$0<u'(d^+)=f(u(d^+))=f(m)=f(u(d^-))=u'(d^-)\leq 0,$$
and so a contradiction. We get our result.
My question :
Is my proof correct ? And if yes, is there a faster way to prove that result ? Thank you for your time !
Edit : After some discussion with Jonas, we agree that this proof is correct and are talking about details in this specific way of proving that result. I am starting a bounty to answer the second part of my question : does someone see a faster way to solve it ? Thank you for your attention.
Answer: Using integration by substitution it is seen that:
$$
 0 = \int_{k}^{k} f(x) dx = \int_{u(a)}^{u(b)} f(x) dx = \int_{a}^{b} f(u(t)) u'(t) dt = \int_{a}^{b} ( u'(t) )^{2} dt.
$$
Thus $u'(t) = 0$ on $[a,b]$, so $u$ is constant.
Comment: Wonderful !!  Thank you very much !
Answer: Your proof seems correct to me.
Let me suggest a simpler argument (somewhat based on yours):
Since $f$ is only continuous the solutions may not be unique but still, in order to start at $k=u(a)$ and reach some bigger value at a later time necessarily $u'(t)>0$ for some $t\in(a,b)$. But since $u(b)=k$ the solution needs to return and pass in particular through $u(t)$ but in the opposite direction, which requires that $u'(t)\le0$ (it could be zero because of the possible nonuniqueness). This contradiction show the solution cannot reach a higher value. Similar arguments apply to the other direction.
Comment: Thank you for your answer. I agree that the argument is shorter, but I try to find a really formal proof : so when we say "in the opposite direction, which requires that...",  I agree that it is a totally right argument, but I want to show every point really clearly. An other point : when you say "it could be zero because of the possible nonuniqueness", I think it comes from the fact that $u$ can cross the level line as $x\mapsto x^3$ cross $y=0,$ i.e. with a nul-derivative ?
Comment: What you call "formal" some call "unreadable". :) But notice that you don't need the intermediate value theorem, integrals, etc, for a "formal" proof. No, not like $x^3$, either you assume more than continuity for $f$ or you really will have in general nonunique solutions (so either you consider a particular $u$ as in your argument, or you consider all solutions at the same time, as in my argument, in which case nonuniqueness is a crucial point).
Comment: I agree that at a certain level, these arguments have not to be developed, but one should do some proofs as this one before to allow himself just giving the ideas ;) And, about this problem of "$\leq$", here note that I study a fixed solution, so I don't care about other potential solutions : the only fact I wanted to precise is that the point where $u$ will reach the value $m$ while "decreasing", then at that point the derivative could be equal to $0$ as in the cube example !
Comment: So I think I did not really understand what you want to mean with "nonuniqueness" here ?
Comment: Perhaps nonuniqueness of the point $x$ where $u(x)=m$ ?
Comment: No problem, see you later and thank you for your time and attention !
Comment: Please just tell me the next time that you have not the time to follow your help, instead of erasing your comment...
Comment: I erased my comment because I was going to add details to my answer, as promised, but could not do it immediately. Unfortunately I can do it only when I can do it, sorry for that, and to give an explicit example required sitting down and compute. Never mind, I will leave all as it is, after all all I have already answered, crystal clear. Next time try to be more appreciative.
Comment: I have only remarked that you have answered a lot of other questions while I was standing for the following of our discussion. However, my comment could have been to fast and inappropriate, and so I apologize about it. Hope we will finish to discuss about that topic !
Comment: True, but many are much more automatic than yours (which incidentally I appreciated much more than others). I was tempted to only write "Draw the phase portrait", but presumably it would be considered almost  offensive, since it would very much nonformal. :)
Comment: I agree that all the proof is in these some words, and that all the difficulty is to translate it as an homework (perhaps I should have precise that it was the goal of this verification before all !). For information, the teacher has said that the proof was correct, but asked : how would you precise that you can consider $x_{max}$ ? I answered : $x_{max}=\sup\{x\in[c,b]\, ;\,u(x)=m\}=u^{-1}|_{[c,b]}(\{m\}),$ so a closed of a compact - and so a compact : it contains its $\sup$... Just to show the degree of details he was looking for ^^'


How to Accelerate Firewalld or should it be abandoned for nftables instead?

Question: We have a problem where we set up a server running a service and it is capable of hundreds of simultaneous connections on port 3535 (arbitrarily assigned for this application).  We have firewalld running on this near-end-host allowing connections from the far-end host and that is all working fine.  The problem we ran into is the far-end-host is only able to establish a few connections at a time and it is taking upwards of 30 seconds to get those connections.  The most we have seen on the near-end-receiving host is about 35 connections on average.  We turned firewalld off and immediately it went to 850 connections and the far-end reported no problems and no delays when connecting and ran flawlessly for 15 minutes (until we turned firewalld back on).
We have a very simple rule set and are not doing any kind of throttling.  Is there default throttling in firewalld that I need to disable or should I go to nftables and if so will it actually perform better or am I chasing a ghost?  My ISP is not using VMWARE and so no external solution is available.
Thanks in advance.
David
Comment: Firewalld still uses nftables as backend (or it can be iptables). So unless you have a too heavy raw traffic that CPU can't withstand, you still need to understand what is happening, how are packets dropped when they should not etc. There's the *conntrack* part to also check. Bugs get corrected, so the kernel version also matters.
Comment: The CPU load when this is happening is .01 or .02 and responsive, etc.  Even when the far-end-system is complaining of connection issues, we can telnet to the port from our remote site and it responds immediately.  Regarding iptables vs nftables... the system has iptables on it.  nftables package is not installed yet.  I'm just trying to figure out if there is a default throttle or if iptables is too slow and nftables will solve the issue.  We're not talking about insignificant performance variabtion.  It basically went from 3% to 80% when we turned off the firewall.
Comment: You'd need to supply your whole network settings (including firewalld, iptables (eg: iptables-save -c), interfaces, addresses, routes, routing rules in this question to get help. If it's something to keep secret, I'm not sure much can be told. + OS, kernel version iptables version etc.
Comment: I'm not asking for a specific "fix this".  I'm asking for general knowledge.  Because this is an extremely simple setup.  Our entire firewalld ruleset is about 6 rules (allow this, this and this, block everything else).  There is only one route, the default route.  The primary questions are:  (a) Is there some form of default throttling in firewalld/iptables and if so how do I turn off all throttling and (b) is nftables faster than iptables? Neither of those questions require specific detail.
Comment: Oh ok. That's the first time I see this kind of issue reported around. I'm surprised this is related to firewall *performances*. I'd say there's something else, but you're the person knowning your setup.
Comment: It's definitely firewall. As soon as I turn it off, performance skyrockets.  Most people think their systems are fast but they really have no idea.  They also don't understand how to test effectively to isolate. Software firewalls require a *lot* of extra cpu horsepower to do packet filtering.  We *always* opt for external hardware based firewalls and never have this problem.  But this vendor insists on software firewalls local to the box. VERY MUCH appreciate everybody's input.
Comment: Is this compatible with "The CPU load when this is happening is .01 or .02 and responsive"?
Comment: I'm not sure what you are asking.  I think you're asking if the CPU Load is virtually zero when this is happening and the answer is yes. The server is extremely responsive so it's not a CPU load issue.  That's why I suspected throttling.  And I have ruled out the sending side and the recipient software because the issue goes away the install firewalld is disabled.
Comment: I believe this is a performance limitation of firewalld.  Others have also had the issue and it has gone unresolved:  https://forums.centos.org/viewtopic.php?t=58673
Answer: firewalld maintainer here.
Firewalld does not currently support acceleration (software fast path or hardware offload). However, I think that both could be added by using nftables flowtable infrastructure. Only a few NICs support flowtable offload though.
That being said, what you're describing sounds wrong. That's abysmal performance. Firewalld doesn't actually do the firewalling. It builds iptables/nftables rule sets and applies them. The iptables/nftables rule execution happens in the kernel/netfilter.
You may consider disabling some optional firewalld features. IPv6_rpfilter is known to have performance issues in scaled environments because it requires a FIB lookup. Also consider other things that may cause frequent rule updates or add a large amount of rules, e.g. fail2ban.
Edit 2023-06-07: firewalld now supports nftables flowtable. This may significantly improve forwarded traffic throughput.
Comment: Thank you so much for the information and that makes sense.  We ultimately went back to an external firewall solution.
Answer: After much research it appears that nftables is not a "savior" here.  It does not perform any better in this situation than iptables and so is not helpful.
The overall performance problem appears to be a limitation of the firewalld software firewall and must be addressed by an external firewall, etc.  Other's have had the same issue and it has gone unresolved:  https://forums.centos.org/viewtopic.php?t=58673
Answer: You could try to copy the iptables / nftables rules generated by firewalld, disable firewalld, and then paste the iptables / nftables rules again, so you could infirm or confirm firewalld has some other limiting parameters.
If it is still capped, it is the generated rules and you could try to optimize the rules or build the from scratch with iptables / nftables.
If it isn't, you then it might be a firewalld limitation, or more probably a firewalld bug.
Comment: it's a limitation.  these software firewalls are MASSIVELY slower than hardware firewalls. I know they are being implemented all over, but I think most users don't realize how slow they are.  So we went back to hardware.


Null pointer exception when running viewmodel test using liveData and rxJava Single

Question: I want to cover ViewModel with unit tests. But getting NullPointerException when running them.
ViewModel implementation is as follows:

interactors and Schedulers are injected through the constructor
subscribe on RxJava Single
and post values in liveData

// constructor
 public ProductListViewModel(
        GetCellphonesInteractor getCellphonesInteractor,
        GetCellphonesByNameInteractor getCellphonesByNameInteractor,
        GetFilteredCellphonesInteractor getFilteredCellphonesInteractor,
        BaseSchedulerProvider schedulerProvider
    ) {
        this.getCellphonesInteractor = getCellphonesInteractor;
        this.getCellphonesByNameInteractor = getCellphonesByNameInteractor;
        this.getFilteredCellphonesInteractor = getFilteredCellphonesInteractor;
        this.schedulerProvider = schedulerProvider;
        getCellphones();
    }

// method
void getCellphones() {
        getCellphonesInteractor
            .getCellPhones()
            .subscribeOn(schedulerProvider.io())
            .observeOn(schedulerProvider.io())
            .subscribe(new SingleObserver<Cellphone[]>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {
                    disposables.add(d);
                    _isRefreshing.postValue(true);
                }

                @Override
                public void onSuccess(@NonNull Cellphone[] cellphones) {
                    _cellphonesLiveData.postValue(cellphones);
                    _isRefreshing.postValue(false);
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    _isRefreshing.postValue(false);
                }
            });
    }

In test class

Set rules
Mocked interactors
Set observers for liveDatas
Make assertions

public class ProductListViewModelTest {
    @Rule
    public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule();

    @Rule
    public RxSchedulerRule rxSchedulerRule = new RxSchedulerRule();

    @Rule
    public MockitoRule rule = MockitoJUnit.rule();

    @Mock
    GetCellphonesInteractor getCellphonesInteractor;
    @Mock
    GetCellphonesByNameInteractor getCellphonesByNameInteractor;
    @Mock
    GetFilteredCellphonesInteractor getFilteredCellphonesInteractor;

    @Mock
    Observer<Cellphone[]> cellphones;
    @Mock
    Observer<Boolean> isRefreshing;

    TrampolineSchedulerProvider trampolineSchedulerProvider = new TrampolineSchedulerProvider();

    private ProductListViewModel productListViewModel;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        productListViewModel = new ProductListViewModel(
            getCellphonesInteractor,
            getCellphonesByNameInteractor,
            getFilteredCellphonesInteractor,
            trampolineSchedulerProvider
        );
    }

    @Test
    public void testGetCellphones_whenReturnsData() {
        Cellphone[] dummyCellphones = DummyCellphoneFactory.generateCellphones();
      Mockito.when(getCellphonesInteractor.getCellPhones()).thenReturn(Single.just(dummyCellphones));

        productListViewModel.isRefreshing.observeForever(isRefreshing);
        productListViewModel.cellphonesLiveData.observeForever(cellphones);

        productListViewModel.getCellphones();

        Mockito.verify(isRefreshing).onChanged(true);
        Mockito.verify(cellphones).onChanged(dummyCellphones);
        Mockito.verify(isRefreshing).onChanged(false);
    }
}

Here is stacktrace, which points to subscribeOn in getCellphones method of viewModel
java.lang.NullPointerException
    at com.online.shop.ui.list.ProductListViewModel.getCellphones(ProductListViewModel.java:61)
    at com.online.shop.ui.list.ProductListViewModel.<init>(ProductListViewModel.java:51)
    at com.online.shop.ui.list.ProductListViewModelTest.setUp(ProductListViewModelTest.java:53)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.RunBefores.invokeMethod(RunBefores.java:33)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.mockito.internal.junit.JUnitSessionStore$1.evaluateSafely(JUnitSessionStore.java:55)
    at org.mockito.internal.junit.JUnitSessionStore$1.evaluate(JUnitSessionStore.java:43)
    at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:61)
    at com.online.shop.ui.utils.RxSchedulerRule$1.evaluate(RxSchedulerRule.java:25)
    at com.online.shop.ui.utils.RxImmediateSchedulerRule$2.evaluate(RxImmediateSchedulerRule.java:46)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
    at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:121)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:829)

Comment: Please provide the exception stacktrace.
Comment: Where do you call `MockitoAnnotations.openMocks(this)`? See https://stackoverflow.com/a/68701517/61158
Comment: @akarnokd Deleted that line by accident. Using  MockitoAnnotations.initMocks(this); in setup method
Comment: Do you still get the NPE?
Comment: @akarnokd yes, even though after using openMocks
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/243688/discussion-between-temur-isroilov-and-akarnokd).
Answer: Based on the stacktrace and the arguments of ProductListViewModel, I presume you called the getCellphones(); before storing the reference this.getCellphonesInteractor = getCellphonesInteractor; it uses.


Prove function is surjective?

Question: I am trying to show the function $f: X \rightarrow S^2$ defined by
\begin{equation}
f(x,y) = \Big(\sin\Big(\frac{\pi}{2} - \frac{\pi}{2}y\Big)\cdot \cos(x), \sin\Big(\frac{\pi}{2} - \frac{\pi}{2}y\Big)\cdot\sin(x), \cos\Big(\frac{\pi}{2} - \frac{\pi}{2}y\Big)\Big)
\end{equation}
is surjective. I feel this should be simple but am struggling to come up with a point which produces $(x,y,z)$.
Comment: In order to check subjectivity you need to specify what is $X$.
Answer: I assume that $X=\mathbb R^2$, since this will make things simple. For many other choices of $X$, the proof will be similar.
This map $f$ is the composition
$$
\mathbb R^2\overset{\phi}{\to}\mathbb R^2\overset{\psi}{\to} \mathbb S^2,
$$
where $\phi(x,y)=(x,(\pi/2)(1-y))$, and $\psi(x,y)=(\sin y \cos x,\sin y \sin x,\cos y)$. $\phi$ is surjective, as it is essentially a linear function. $\psi(x,y)$ is also surjective, because for all $(X,Y,Z)$ such that $X^2+Y^2+Z^2=1$, we want to solve
$$
\tan x=Y/X,  \cos y= Z
$$
We can let
$$
y=\pm \cos ^{-1} Z, x=\tan^{-1} (Y/X)+k\pi.
$$
Choose the sign of $y$ and $k$ to match the signs of $X,Y,Z$.
So $\psi$ is surjective. Then $f=\psi(\phi(\cdot))$ is surjective.

Prove function is surjective?


Remove part of a text string

Question: SELECT
   right(name,7),
   substring(params, charindex('|-|', params)+3,LEN(params)) as 'List Name',
   convert(varchar,dateadd(hh,-8,created_date), 101) as Date,
   convert(char, dateadd(hh,-8,created_date), 108) as Time
FROM
   [meldb].[dbo].[mr_message]
WHERE
   name in ('CL_LIST_STARTED', 'CL_LIST_STOPPED')
   AND dateadd(hh,-8,created_date) > '7/1/2014'
ORDER BY
   created_date ASC

List name will return something like:
firstname.lastname-|LISTNAME|-|PARENTLISTNAME

I'm trying to isolate LISTNAME and PARENTLISTNAME into separate columns, but since they can vary in char size I can't just specify right or left
Btw I didn't create this table I'm just stuck using it
Any ideas?
Comment: Please **do not** put code samples or sample data into comments - since you cannot format it, it's **extremely hard** to read it.... Instead: **update** your question by editing it to provide that additional information! Thank you.
Comment: Cool...   Oh, and I just realized you're saying it's exactly 2 delimiters, not a variable number of delimiters, right?  Then we can hardcode the nesting with CHARINDEX...  go for it!  I'll race you :)
Comment: sql server, sorry forgot to specify
Comment: Can you show some example rows? Is the format how you have it with . separating firstname last name and - separating listname and parentlist name.
Comment: seprators are |-|  but there are two instances of "|-|"

so far im here:
Comment: SELECT right(name,7),
  substring(params, charindex('|-|', params)+3,LEN(params)) as 'List Name',
  convert(varchar,dateadd(hh,-8,created_date), 101) as Date,
  convert(char, dateadd(hh,-8,created_date), 108) as Time

 FROM [meldb].[dbo].[mr_message]
  where name in ('CL_LIST_STARTED', 'CL_LIST_STOPPED')
  and dateadd(hh,-8,created_date) > '7/1/2014'
  order by created_date asc
Comment: Yes, if you really want to do this in t-sql, I think you're on track with CHARINDEX.  You'll have to do a loop where you store the last value from CHARINDEX as the start-location for the next call.  Have you tried that yet?
Comment: Oh, you want this for multiple rows like a single select?   Hmmmm... maybe need a UDF then.
Comment: Also, can you indicate the SQL Server version?
Comment: Do you want to separate `params` into three columns?
Comment: @Jesuraja in a weird way yes, i dont care for the firstname.lastname, so realistically it would be sep into two columns
Answer: Do you want to split params into three columns? Please check below query.
SELECT
   SUBSTRING(params, 1, CHARINDEX('-', params)-1) AS FullName,
   SUBSTRING(STUFF(params, CHARINDEX('|-|', params), LEN(params), ''), CHARINDEX('-', params) + 2, LEN(params)) AS 'List Name',
   SUBSTRING(params, CHARINDEX('|-|', params) + 3, LEN(params)) AS 'Parent List Name',
   CONVERT(VARCHAR,DATEADD(hh,-8,created_date), 101) AS DATE,
   CONVERT(CHAR, DATEADD(hh,-8,created_date), 108) AS TIME
FROM
   [meldb].[dbo].[mr_message]
WHERE
   name IN ('CL_LIST_STARTED', 'CL_LIST_STOPPED')
   AND DATEADD(hh,-8,created_date) > '7/1/2014'
ORDER BY
   created_date ASC

Comment: close but that retruned the following three colums:
fulle name - first.last
list name  - LISTNAME|-|PARENTLISTNAME(partial)
Parent list name - LISTNAME|-|PARENTLISTNAME(complete)
Comment: Can you update exact Sample input and Expected Output in your question?
Comment: well it retruned more but i was referencing the 3 substring colums
Comment: Update please check now
Answer: Did you try it yet?
Ok...   happy friday :)
declare @str varchar(100);
set @str = 'jim.smith|-|firstItem|-|secondItem';

--- for your query, change @str to the column name, obviously ---
select
    substring(
                    @str
                    , charindex('|-|', @str) + 3
                    , ( ( charindex('|-|', @str, charindex('|-|', @str) + 3) ) - ( charindex('|-|', @str) + 3) )
                )
    ,substring(
                    @str
                    , charindex('|-|', @str, charindex('|-|', @str) + 3) + 3
                    , len(@str) -- guaranteed to be past the end, to catch all
                )

Comment: oh, it's in there :)  I like more lines than most people ...  have a good weekend
Comment: worked Mike! thanks, I wasnt including the second charindex and it was driving me nuts! much appreciated!
Answer: Here is the format I came up with using PAT index and the separators you mentioned:
SELECT name,
substring(name, 0, charindex('.', name)) as 'FirstName',
substring(name, charindex('.', name) + 1, patindex('%|-|%', name) - patindex('%-|%', name) -2) as 'LastName',
substring(name,patindex('%-|%', name)+2, patindex('%|-|%', name) - patindex('%-|%', name)-2) as 'ListName',
substring(name, patindex('%|-|%', name)+3, len(name) - patindex('%|-|%', name)) as 'ParentListName'
from FancyNames

Link to SQL Fiddle: http://sqlfiddle.com/#!6/03c2c/38

Remove part of a text string


Signature verification problems for ecdsa-with-SHA384 on Android 6

Question: I've problems verifying a certificate which is signed with ECDSA with SHA384 on Android 6.0 and up. However, it is working for Android 4.1 - 5.1. I tracked it down to an error in the Certificate class. An exception is thrown in the verify method:
java.lang.RuntimeException: error:0f092074:elliptic curve routines:ec_asn1_pkparameters2group:NON_NAMED_CURVE

Any idea why this is happening with Android 6.0 and how it can be fixed? I already tested it with Spongycastle as a security provider, but the verify function always throws that exception.
Thanks & Regards
Answer: Finally found the issue - not the verification of the signature itself was the problem, but loading of the intermediate certificate which holds the ec public key.
    Subject Public Key Info:
        Public Key Algorithm: id-ecPublicKey
        Unable to load Public Key
2536673920:error:0f092074:elliptic curve routines:ec_asn1_pkparameters2group:NON_NAMED_CURVE:external/boringssl/src/crypto/ec/ec_asn1.c:225:
2536673920:error:0f07f076:elliptic curve routines:d2i_ECPKParameters:PKPARAMETERS2GROUP_FAILURE:external/boringssl/src/crypto/ec/ec_asn1.c:253:
2536673920:error:0f08000f:elliptic curve routines:d2i_ECParameters:elliptic curve routines:external/boringssl/src/crypto/ec/ec_asn1.c:503:
2536673920:error:0608808f:public key routines:eckey_type2param:DECODE_ERROR:external/boringssl/src/crypto/evp/p_ec_asn1.c:140:
2536673920:error:0608600f:public key routines:eckey_pub_decode:elliptic curve routines:external/boringssl/src/crypto/evp/p_ec_asn1.c:180:
2536673920:error:0b07c07c:X.509 certificate routines:X509_PUBKEY_get:PUBLIC_KEY_DECODE_ERROR:external/boringssl/src/crypto/x509/x_pubkey.c:168:

This leads to the question - why does BoringSSL have problems decoding the public key in this certificate? And I guess this has to be a bug in BoringSSL. I checked the certificate with OpenSSL and had no problems there.
When the Spongycastle Provider is explicitly used when loading the intermediate certificate and later verifying the signature of the document signing certificate, everything works fine.
Comment: THANK YOU! This solved my problem for using secp256k1 aswell. I was getting: java.security.InvalidKeyException: java.lang.RuntimeException: error:0f00007b:elliptic curve routines:OPENSSL_internal:UNKNOWN_GROUP
Answer: I ran into the same issue on Android 6.0. Using the Spongycastle Provider explicitly didn't seem to help, unless I did something wrong. Here is the stack trace:
W/System.err: java.lang.RuntimeException: error:0f092074:elliptic curve routines:ec_asn1_pkparameters2group:NON_NAMED_CURVE
W/System.err:     at com.android.org.conscrypt.NativeCrypto.X509_get_pubkey(Native Method)
W/System.err:     at com.android.org.conscrypt.OpenSSLX509Certificate.getPublicKey(OpenSSLX509Certificate.java:418)
W/System.err:     at org.spongycastle.jce.provider.CertPathValidatorUtilities.findTrustAnchor(CertPathValidatorUtilities.java:182)
W/System.err:     at org.spongycastle.jce.provider.PKIXCertPathValidatorSpi.engineValidate(PKIXCertPathValidatorSpi.java:95)
W/System.err:     at java.security.cert.CertPathValidator.validate(CertPathValidator.java:193)
W/System.err:     at ***.(***.java:##)
W/System.err:     at android.app.Activity.dispatchActivityResult(Activity.java:7137)
W/System.err:     at android.app.ActivityThread.deliverResults(ActivityThread.java:4916)
W/System.err:     at android.app.ActivityThread.handleSendResult(ActivityThread.java:4963)
W/System.err:     at android.app.ActivityThread.access$1600(ActivityThread.java:221)
W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1848)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err:     at android.os.Looper.loop(Looper.java:158)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7224)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

On Android 9.0 it works again, but I'd still like to get it working on 6.0. It fails on certPathValidator.validate():
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
// keyStore = KeyStore.getInstance("BKS", "BC"); // explicitly use BC - also fails
// [...] populate key store
PKIXParameters params = new PKIXParameters(keyStore);
CertPathValidator certPathValidator = CertPathValidator.getInstance(CertPathValidator.getDefaultType()); // CertPathValidator.getDefaultType() = PKIX
PKIXCertPathValidatorResult pkixCertPathValidatorResult = (PKIXCertPathValidatorResult) certPathValidator.validate(certPath, params);

I am using these libraries:
implementation files('libs/core-220.127.116.11.jar')
implementation files('libs/prov-220.127.116.11.jar')
implementation files('libs/pkix-220.127.116.11.jar')
implementation files('libs/bcprov-jdk15on-1.64.jar')
implementation files('libs/bcpkix-jdk15on-1.64.jar')


Why are pure tones depicted as sine waves?

Question: This is pretty much the only thing in music theory (that i've covered so far) that I cannot understand. What I would expect to hear is what you get from LFO, or Low Frequency Oscillator represented by a Sine wave where the pitch is varied. Here the change in pitch is very smooth because, well, it's a sine wave :D
But then a pure tone is also represented by a sine wave. I presume that when such a wave is plotted on a graph, the x axis is time, but the y axis can't be pitch. You see, it seems that when playing a sine wave, nothing varies but time. However, a cyclic change always represents a change between two variables, indeed a relationship (horay for maths!) So what's the relationship?
Furthermore, I would of thought that the graphical relationship would be the one obtained from a frequency analyser, where you just have one vertical line representing the fundamental (the keyword being one, all frequencies are represented by a vertical line on a freq analyser, x = pitch, y = hertz).
Now in the hopes of not going to off the beaten track, independent of the reason for using sine waves, are there any usages of cosine? Is this just the same thing? Even though a cosine is just a sine wave but shifted, I suppose this wouldn't make a difference, right? How about the tangent, or other functions?
Comment: The y-axis is amplitude.  Pitch is based on the frequency (inverse of the wavelength), so given a fixed x-axis it would be indicated by how compressed the wave appears horizontally.  Cosine is no different from sine, it just doesn't really make sense to "start" making sound at anything other than zero.  You could generate sound based on a tangent, but going from infinitely loud to zero to infinitely loud again is both impossible and just noise.  Basically I think all your questions are just based on a misunderstanding of what a waveform shows.
Comment: The y axis represents air pressure or air displacement (they are 90 degrees out of phase) at a fixed point in space. Cosine is the same thing, just shifting the time axis along a little bit. In fact, any combination of sines and cosines of the same frequency will give you a pure tone.
Comment: I just have to say, it's "beaten track", not "beat and track". "Beaten" as in "beaten down by many passing feet over a long period of time". The beaten track is the road well-travelled. Going down the beaten track is following the same path taken by many before you. Going off the beaten track is striking out through the weeds, undergrowth and forest. It may be dangerous, uncomfortable, or lonely, but it also likely involves going where no one has gone before.
Comment: The maths and physics of this have been well handled in the replies, so I'm just going to throw in something from a totally different perspective, that of musical perception: if you listen to different tones, or sounds of different timbres, (eg with an analog synth) and look at their waveforms on an oscilloscope, you will immediately see that those that sound like 'pure tones' appear as sinewaves on the scope - so it's not that they are 'depicted' as sinewaves, they 'are' sinewaves. ie what we perceive intuitively as a pure tone maps across to the maths as per the other answers.
Comment: Actually when a waveform is mathematically analyzed and broken down into its components (a process called *Fourier analysis*), both the sine *and* cosine are used. When you see or hear "sine wave", it really refers to either a sine or cosine wave, since they have the same shape and human ears can't hear the phase difference which is the only difference between sine and cosine. Maybe the animated graphic on the right side of this page will help with your overall question: http://en.wikipedia.org/wiki/Fourier_transform#Introduction
Comment: The tangent is pretty different from sine and cosine. It's sort of one step removed from the fundamentals of trigonometry, whereas sine and cosine are right there at the foundation. We talk about tangent a lot in high school because it makes analyzing triangles easier. The analysis of periodic functions (what mathematicians would call most sound waves) relies heavily on Euler's formula, which uses complex numbers, sine, and cosine, but not tangent: http://en.wikipedia.org/wiki/Euler%27s_formula
Answer: I'm just going to answer the question "What about tangent, or other functions", since the rest seems to have been fairly well handled.
All sounds that we hear as having a definite pitch or note can be represented by a periodic function. As I wrote in my comment, any repeated shape represents a periodic function. Most periodic functions, both in the real world and in theory, are pretty complicated, at least mathematically.
If we want to do math on the sounds we are hearing, we will have to get a grip on these periodic functions. What would really help is a way to simplify them. As discussed, Fourier analysis lets us do exactly that. We can take a complicated periodic function with some really annoying math and break it down into simpler periodic functions where the math is much easier.
The simplest periodic functions are sine and cosine, and they are virtually the same thing and they are closely related. Tangent is a very famous periodic function and is quite helpful in basic trigonometry (literally the study of triangles). Tangent has many other uses, but most people first see the tangent function as a way to analyze triangles.
Even though we usually learn about sine, cosine, and tangent at the same time, the tangent function is actually different from sine and cosine in some important ways. It is not continuous, which means you couldn't draw very much of it without picking up your pencil and putting it down again. It's even worse than that, because it has an infinite number of discontinuities (places where you have to pick up the pencil). Note that not only is this a stark contrast with sine and cosine, but also with periodic functions that model sound waves. Sound waves are continuous functions if we plot them out.
So if we want to take a periodic function and break it into simple pieces, we don't want to break it into tangent pieces. Tangent will not help us, it's really more likely to make things worse. When Fourier (the mathematician who invented Fourier analysis) was trying to take apart periodic functions, he was looking for a way to turn them into sines and cosines, not any other periodic function (and there are many).
I could write several pages on why sine and cosine are not merely simple periodic functions, there are actually the simplest possible ones, but I don't think this is the best place for that. Let me briefly say, however, that a circle is perhaps the simplest shape, and if you follow a point as it goes around a circle, its vertical movement traces out a sine wave at the same time that its horizontal movement traces out a cosine (this depends on where on the circle the point starts, but one will be sine and the other cosine, or at least one will be one quarter cycle behind the other in phase).
Below is a video of that, and hopefully this will give you a way to see how the sine wave (or cosine, same thing, really) is the simplest periodic function, and therefore the one we want to break more complicated functions into, and also the one that to our ears appears to be the most basic if we turn it into sound.
See also the Physics version of this question with a similar answer: https://physics.stackexchange.com/questions/352754/why-cosine-and-sine-functions-are-used-while-representing-a-signal-or-a-wave
Comment: Thank you very much Mr. Wilcox, this is indeed very informative. I especially appreciate the efforts in making a direct reference to the field of maths in which this can be studied, for your explanation itself is useful, but the reference to Fourier analysis is what allows the usefulness of your words to be extended beyond it's lifetime :)
Comment: Thank you for these great illustrations, this is how I learned to understand it and I'm only beginning (probably much too late in life) to learn the mathematics involved in something like user20319's answer.
Answer: Sine and cosine are the same, just offset by 90 degree.  They form a "quadrature pair": if you add their squares, you get a constant.  When you draw a sine wave as a representation of audio, it represents either pressure (compared to neutral) at some "listening" point, or an impulse density.  Both together form a quadrature pair again: if you square and add their respective sizes for a stationary sine wave noise, you get a constant representing the sound energy density.
Now why sine waves?  Some people state that's because you can let everything be composed of sine waves but that's circular reasoning: almost any wave shape can be used as a basis for decomposing signals: one can easily represent a sine wave as a composition of an infinite number of square waves just like it is possible to do the reverse.
However, what singles out sine waves is that they are the Eigenfunctions of linear time-invariant systems (which are the vast majority of systems working on sound: any ambient surrounding without some loose snaring part, amplifiers as long as they are not overdriven, delay circuits, equalizers and a number of others): if you feed such systems with a sine wave, the output will be a sine wave of the same frequency though possibly different volume and phase.
No other wave form has that feature: square waves don't remain square when fed through such systems, sawtooth waves don't remain sawtooth, frequency sweeps of constant amplitude change into sweeps with varying amplitude.
There is no such thing as a "muffled" sine wave from behind closed doors: it may be attenuated but its sound quality is totally the same.
Comment: Ah! Nice point about eigenfunction! I was just about to ask a similar question, but that single word answers it perfectly.
Answer: Because a circle is the purest periodic shape:

Any periodic orthogonal function could form the basis of more complicated, "less pure" sounds (i.e., sounds with many harmonics). See Dave Benson's excellent (and free!) Music: A Mathematical Offering (Cambridge U. Press), ch. 2, "Fourier Theory."
Answer: I like Darren's beginning very much, converting your question to "Why do we perceive sine waves as pure tones?"
When the wave that is traveling through the air reaches the ear drum, the ear drum vibrates.  That vibration is transferred to the three little bones in the middle ear. To make a long story short, the next-to-last step in achieving hearing is that the fluid inside the snail-shaped thing goes forward and back just as the air molecules did while the sound wave was going through the air towards your ear.  Now, inside the snail-shaped thingie, there are a large number of little hairs attached to the "floor" or the "wall."  They sway with the vibration that was communicated from the middle ear. They oscillate, like a sine wave - forward and back, forward and back.
The frequency of oscillation gives rise to different pitches.
Answer: To supplement the impressive mathematical background exposed in the other answers (kudos to Geremia's link), I want to summarize my own, to get two more practical aspects in:

A tone is decomposed by our ear/brain combination into a base tone and overtones. (That other decompositions are also theoretically possible has therefore no impact). The overtones add what is called timbre. Obviously one achieves a quite pure tone, if the timbre is removed. For direct experience listen to a sine generator, or lacking this, to a flute, which is quite close to sine and in contrast to a clarinet, which is far from it.
A sine wave depicts a harmonic oscillation. I now have to resort to a mechanical wave. A harmonic oscillation is an undampened oscillation, where the restoring force is proportional to the equilibrium offset. For a pendulum this means proportional to the angle to the vertical. There is no simpler formula than direct proportion, therefore sine wave is the most simple wave.


Form element validation #element_validate not working

Question: I am porting this contrib module to D8 and need some help.
The module is shipped with a custom node type. Certain elements options in the node_form will be populated dynamically. Also other modules needs to able to provide options for these fields.
hook_form_FORM_ID_alter calls the wrapper class MyModuleManager that performs several helper duties. All is going well except that I can not get the custom element_validation to work.
Upon form validation a warning is generated
Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'FilebrowserManager' not found in Drupal\Core\Form\FormValidator->doValidateForm() (line 282 of core/lib/Drupal/Core/Form/FormValidator.php).

together with the fatal error:
Recoverable fatal error: Argument 1 passed to Drupal\Core\Field\WidgetBase::massageFormValues() must be of the type array, string given, called in /var/www/drupal8/core/lib/Drupal/Core/Field/WidgetBase.php on line 376 and defined in Drupal\Core\Field\WidgetBase->massageFormValues() (line 511 of core/lib/Drupal/Core/Field/WidgetBase.php).

The fatal error occurs exactly when validating $form['my_field']
class MyModuleManager implements MyModuleManagerInterface {
  use StringTranslationTrait;

  public function addFormElements(array $form, FormStateInterface $form_state, NodeInterface $node, AccountInterface $account, $collapsed = TRUE) {
    ...

    return $form;
  }

  public function addFormDefaultOptions(array $form, FormStateInterface $form_state) {

    // Replace MyModule_hook by Events
    // ...
    // Events returns dynamic $options

    $form['my_field']['widget']['#options'] = $options;
    $form['my_field']['widget']['#element_validate'] = array(array($this, 'myModuleValidateTrue()'));

    return $form;
  }

  public function myModuleValidateTrue() {
    return;
  }

}

As the warning tells it can not find the callback in FormValidator I suspect the problem might be the way I wrapped my code in this class. Being new to OOP I would appreciate all help.
Answer: It's probably this line:
$form['my_field']['widget']['#element_validate'] = array(array($this, 'myModuleValidateTrue()'));

Which should be this, without parentheses in the method name:
$form['my_field']['widget']['#element_validate'] = array(array($this, 'myModuleValidateTrue'));

See PHP: Callbacks / Callables for the full story.


Topologist's sine curve from Munkres book

Question: I was reading an example of connected but not path connected space from J.Munkres book and ran into two questions:
1) He claims that $f^{-1}(0\times [-1,1])$ has largest element. Is it because any nonempty, closed, bounded set on real line has maximal element, right?
2) We take $n\in \mathbb{N}$ how we can find $u$ s.t. $0<u<x(1/n)$ with $\sin(1/u)=(-1)^n$?
I guess since sequence $\dfrac{1}{\pi/2+\pi n+2\pi k}\to 0$ as $k\to \infty$ and $n$ is fixed. Then we can take $u$ from this sequence. Is my reasoning correct?
Answer: For your first question, $A = f^{-1}(0 \times [-1, 1])$ is the preimage of a closed set under a continuous function. Therefore it's closed. It's also bounded, since $\overline S$ itself is bounded. It follows that $A$ contains its least upper bound.
For your second question, your choice of $u$ works.


Norm of an integral operator $L^1 \rightarrow L^\infty$

Question: Let $T:L^1(\mathbb{R}^n)\rightarrow L^\infty(\mathbb{R}^n)$ be an integral operator, i.e. there exist $K:\mathbb{R}^n\times\mathbb{R}^n\rightarrow\mathbb{R}^n$ such that for all $f\in L^1(\mathbb{R}^n)$ it holds
$$Tf(x):=\int_{\mathbb{R}^n}K(x,y)f(y)\:dy\quad\text{for all }x\in\mathbb{R}^n.$$
Does anyone knows how to prove that $\|T\|_{L^1\rightarrow L^\infty}=\sup_{x,y}|K(x,y)|$?
Comment: Perhaps a bounded approximate identity is of use here.
Answer: Recall the definition of norm of $T$ :
 $$
 \parallel T\parallel = \sup_{f,\
 \parallel f\parallel_{L^1} = 1} \parallel Tf\parallel_{L^\infty} $$ $$=  \sup_{f,\
 \parallel f\parallel_{L^1} = 1}  \sup_{x\in \mathbb{R}^n} |Tf(x)|
 =   \sup_{f,\
 \parallel f\parallel_{L^1} = 1}  \sup_{x\in \mathbb{R}^n} \bigg|
 \int K(x,y)f(y) dy \bigg| $$
If $k:=\sup_{x,\ y} |K(x,y)|$ (cf. essential sup), then $$ \parallel T\parallel \leq
  \sup_{f,\
 \parallel f\parallel_{L^1} = 1}  \sup_{x\in \mathbb{R}^n}
  k \int |f(y)| dy = k $$
And we have a sequence $(x_n,y_n)$ s.t. $|K(x_n,y_n)| \rightarrow k$
Then let
$$f_n= \frac{1}{{\rm vol}\ B(y_n,\epsilon ) } \chi_{B(y_n,\epsilon )}
\Rightarrow
\parallel f_n\parallel_{L^1}=1
$$
 so that $$ \parallel T\parallel \geq
    \sup_{x\in \mathbb{R}^n}
   \bigg| \frac{1}{{\rm vol}\
B(y_n,\epsilon ) }\int_{B(y_n,\epsilon )} K(x,y) dy \bigg| \geq
\bigg| \frac{1}{{\rm vol}\ B(y_n,\epsilon ) }\int_{B(y_n,\epsilon )}
K(x_n,y) dy \bigg|  $$
Here last term can be arbitrarily close to $k$ by $n,\ \epsilon$.
Comment: the supremum need not to be attained. probably you should add a note about an limit argument.


Erro de mensagem alert

Question: Gostaria de saber como posso concertar o seguinte problema que estou tendo com a resposta do alert. Eu faço o INSERT de itens para MySQL, até ai tudo bem. Contudo, se algum arquivo der falha e outros conseguirem ser enviados no loop o aviso alert da mensagem de erro.
Gostaria de saber como posso alterar o código abaixo para funcionar da seguinte forma:
Contar o valor total de dados enviados com sucesso e dados que ocorreram falha no envio, desta forma podendo ficar com um só alert, exemplo:
Total de envios com Acerto X com Falha X.
<?php
for($i=1; $i<=$total; $i++) {
    // Insere os dados no banco de dados
    $sql = $MySQLiconn->query("INSERT INTO `medias` SET `cat`='".$subcat["cat"]."', `subcat`='".$subcat["id"]."'");
}

if($sql) { ?><? }
else {
    ?>

    <?
}
?>

Comment: comece conSertando a gramática...
Comment: Não percebi nada...
Answer:
query("INSERT INTO `medias` SET `cat`='".$subcat["cat"]."', `subcat`='".$subcat["id"]."'");
  if ($sql) {
  $total_envios++;
  } else {
  $total_erros++;
  }
}

if ($sql) {
    echo "
        alert('".$total_envios." Itens inseridos com sucesso !!!\n
        ".$total_erros." Itens com falhas no cadastro !!!"."');
        window.location.href='index.php';
        ";
 } else {
    echo "
        alert('error Erro ao tentar inserir os itens tente nova mente');
        ";
 }

?>
Comment: Ola Marcio, bem vindo ao SOPT. Obrigado por responder mas considere acrescentar uma pequena explicação sobre o que alterou e porque alterou.
Answer: Você tem que contar o resultados da query dentro do loop:
<?php
    $total_sucesso = 0;
    $total_erros = 0;

    for($i=1; $i<=$total; $i++) {
        // Insere os dados no banco de dados
        if ($MySQLiconn->query("INSERT INTO `medias` SET `cat`='".$subcat["cat"]."', `subcat`='".$subcat["id"]."'")) {
            $total_sucesso++;
        }
        else {
            $total_erros++;
        }
    }

    ?>
    <?
?>

Dá até pra você exibir uma lista com os itens que deram erro:
    if ($MySQLiconn->query("INSERT INTO `medias` SET `cat`='".$subcat["cat"]."', `subcat`='".$subcat["id"]."'")) {
        $total_sucesso++;
    }
    else {
        $total_erros.= $subcat["cat"] . "\n";
    }

E então, na mensagem:
alert('<?=$total_sucesso; ?> envios com sucesso. Erros: <?=$total_erros;?>.');

Comment: Isso eu havia feito o método que eu estou usando atualmente cria uma listagem de dados enviados com acerto e falha com tudo imagina como ficaria a lista se eu enviar 100 itens de uma só vez por isso optei em usar o alert pois fica um aviso único.
Answer: Misturar tags abertura do PHP dentro de string JavaScript não é uma boa ideia, porque dificulta a leitura do código.
Sugiro simplificar da seguinte maneira:
<?php
// salvar os dados em variáveis
$mensagem = 'error Erro ao tentar inserir os itens tente novamente';
$location = false;
if ($sql) {
    $mensagem =  $total . ' Itens inseridos com sucesso';
    $location = 'index.php';
}

// criar e exibir o javascript
echo '';

utilizei a função printf() em algumas linhas para exibir as strings formatadas. O simbolo %s será substituído pelo parâmetro seguinte. Veja a documentação para mais detalhes.
Answer: A maneira mais correta de fazer esse tipo ação, é usar Ajax.

PHP não se relaciona com JavaScript e Vice&Versa (ñ faça gambi pfpfpf)
Quando precisamos desse tipo de relacionamento (pergunta - resposta) utiliza-se a função Ajax

Vamos ao problema:
Foi executada uma Query no Back-End e após foi informado o resultado.
Como o javascript não consegue enxergar essa resposta, até o momento não temos uma solução.
Para chegar em uma solução, será necessário fazer o uso de Ajax, que vai disparar um requisição ao seu arquivo, e nessa requisição, você dirá que precisa de uma reposta, usando semântica HTTP que no caso será GET.
A resposta virá no corpo de sua requisição, e no javascript você então receberá essa reposta, e poderá avaliar o resultado. Assim poderá lançar uma mensagem ao usuário.
Exemplo prático usando a JQuery
$.get('/pagina_do_meu_site&ajax="verifica"').success(function(response){
    if(response>0){
      alert('Itens inseridos com sucesso');
    }else{
      alert('Houve falha na inserção de dados');
    }
});

No back-end PHP (vou utilizar o modo mais simples)
<?php
  if($_GET['ajax']=='verifica'){
      echo '1';  //aqui o php retornará o valor 1 para o javascript
      exit;
  }
?>

Comment: ^^ Ta serto (y)
Comment: Sem [Not Enough jQuery](http://meta.stackexchange.com/a/48195/223068), por favor. Usar ajax é Overkill pra uma coisa tão simples! O Javascript está sendo usado APENAS para exibir uma mensagem, nada mais! Você quer usar ajax para isso? Da forma que está sendo feita atende perfeita o que o OP quer. Imagina se o usuário faz 10 inserts na base, são 10 alerts pipocando na tela dele... ridículo.
Comment: Jovem, utilizar a maneira mais fácil nem sempre é a correta. É por isso que programadores PHP são mal vistos dentro das empresas, por tomar esse tipo de atitude.
Comment: Eu não disse *mais fácil*, disse mais coerente. Você não sabe como as informações estão sendo enviadas, como é o form nem nada, e já vem sugerindo isso tudo ? Mudança total de estrutura ?
Comment: Só php permite cara, por isso é tao mal vista, isso não existe, comunicar diretamente back-end com front-end.
Comment: Eu sei, mas isso é um contexto mais amplo. Você não sabe como está a estrutura do usuário, nem se ele separa as camadas. Enfim...
Comment: Nem por isso minha resposta está errada. Há um diferença de você pegar um usuário que segue padrão e outro que não segue. Nem por isso eu menosprezo tais repostas. A minha resposta foi mostrar a diferença entre padrões de projeto, se você me negativou, tudo bem, é o seu direto. Há dois mundos paralelos jovem, estou mostrando um dos lados.
Comment: Exatamente, não disse que a resposta está errada ou é ruim, só não é pertinente à pergunta. Você pode sugerir como um comentário a mudança de estrutura, mas não como resposta, na minha opinião. E ainda com tecnologias(ajax e jquery) que nem foram relacionadas na pergunta. No SO gringo você teria recebido uns 10 votos negativos.
Comment: Grato pela ajuda de todos.

Erro de mensagem alert


I'm looking to compare if there is a significant difference between pre-treatment and post-treatment values

Question: 3 sites are sampled pre-tx, and the same 3 sites post-tx. I am trying to compare
the number of cocci in site 1,2,3 pre and post tx (refer to table)
But the issue is i've recorded my values in ranges (i.e. categories of <10; 10-20;20-50;50-100 & >100). What statistical test should I be using, or is there any i can use with this?
Answer: Recording continuous or ordinal values only in bins is a serious design flaw that will not be remedied by any statistical method.  You can discarded a great deal of information/power/precision.
If site represents your independent samples, your sample size is 3 so you do not have power to do a statistical test (binning makes the effective sample size even lower than 3).
Note that pre-post analyses require a very stringent assumption that nothing else changed between pre and post.  For next time you might consider a randomized crossover design.
Answer: As answered, the data is not in a form that lends itself to answer the question at hand. If, however, nothing else is available, perhaps you might try to fit a loglinear model to the three way contingency table Site x Visit x Cat (where Cat is a nominal variable with levels <10, 10-20, etc.)
Doing that, if the effect of Visit is significant, you wold have a lead that something changed between visits, and looking the percentages of observations in different levels of Cat you would probably have a good idea of the direction of change.
Another idea would be to cross-classiffy  Pre- and Post- Cat and test for symmetry. Essentially, this means that a subject e.g. in the pre- 10-20 level of Cat is as likely to end in a post- e.g. 20-50 as one initially in 20-50 to end in 10-20. I do not know if that would make sense in your setting.


C# Reference to class value

Question: My problem, i create one 'Class A' which updates and handles values.
'Class B' is created within 'Class A', and just needs to read the values of Class A.
Now i could create the values of class A as:
public static int AInt { get { return aInt; } }
static int aInt;

And access them within B as A.AInt.
However i could use pointers but this seems very anti-c#.
public class A
{
    int aInt;

    unsafe public A()
    {
        fixed(int *aPtr = &aInt)
        B b = new B(aPtr);
    }

    // Changes aInt
}

unsafe public class B
{
    int *bInt;

    public B(int *a)
    {
        bInt = a;
    }

    // Does stuff according to bInt value changes
}

I'm a little confused as to a better approach of supplying one class' value to another without explicitly calling an update method for the values. I feel the first example is how it should be done, but i'm from a c++ background so pointers are the norm for me.
To do pointers just seems too messy in c# as you have to change compilation flags and have to change any variable with the fixed() and mark a method/class as unsafe.
Thanks for any guidance/tips for a better solution.
Comment: Don't use `unsafe` unless you really need or you're 100% sure it's a right way to do a thing. For your example - it isn't.
Comment: Your question is unclear. Please read it again and edit it to make it more clear.
Comment: Might also be better suited for programmers.stackexchange.com
Comment: Both ways work but it did seem unneccessary. Thank you for you quick reply.
Comment: What is the actual problem/question?  _"access them within B as `A.AInt`"_ seems OK.
Comment: I don't understand how its not clear or not a real question? I thought it was a reasonable question to ask seeing as the difference in memory between c# and c++ is quite different. Not to mention i actually researched in alternatives to this before posting. I'm not getting irate or annoyed at people i am just asking.
Answer: You should rather pass reference to whole A object, not certain property within that object:
public class A
{
    public int aInt;

    public A()
    {
        B b = new B(this);
    }

    // Changes aInt
}

public class B
{
    A _a;

    public B(A a)
    {
        _a = a;
    }

    // can use _a.aInt here
}

Or create an event in A and subscribe to that event in B
Comment: Would this be a viable approach even though there will only ever be One of A? A is also the entry point and is quite a large object, but as it passing a reference it wont be an issue.
Comment: If there will only be one `A` why don't make it static? With static class you don't have to pass anything, just access properties using `A.aInt`.
Comment: That is very true, seeing as B wont exist unless A exists anyway. I wish i could mark more than one answer, these are all excellent. Thank you.
Answer: There are plenty of ways of doing this as you have noticed.
If aInt will remain a static variable (read: i mean it wont change, not static type) then you can just pass it into B via a constructor or a property, or you can pass the whole object into B.
B b = new B(this.aInt); //this is A

or
B b = new B(this); //this is A

If you expect aInt to change and B to get notified then you can create an event in A and subscribe to it in B.
If you expect aInt to be different, but you will let B poll for aInt out of A you can pass a Func delegate into B and have that Func return aInt to you.
Comment: downvotes with no explanation are weird.
Comment: @NomeSkavinski I wasn't talking about you, I was talking about whoever downvoted me first. I don't mind being downvoted as long as there is an explanation of what's wrong.
Comment: Ah yes, i could use a delegate to ask for the value. I didn't think of that even though i am using them for my controller input. Thanks alot.
Comment: I didnt downvote, i voted up.
Answer: Not sure what you want to do within class B, but eventuall a simple extension class is enough:
public class A
{
    int aInt;

    public A()
    {
        aInt = 1;
        aInt = aInt.DoSomething();
        // aInt is now 6
    }
}

public static class Extension
{
    public static int DoSomething (this int value)
    {
        return value += 5;
    }
}

Comment: Very nice, i like. Definitely keep extensions in mind for future issues, thank you for bringing this to my attention.
Comment: Extensions are a much overseen feature of C#

C# Reference to class value


Estimating the variation of the scaling factor from a transformation onto a theoretical graph

Question: I have a numerically calculated graph, on unit-less coordinates.
I have experimental data which corresponds to a point on that graph.
The data has units, and to make it unitless one has to divide it by a "constant" which determines where these points end up on the graph, I call this "constant" the scaling factor.
To find the corresponding point on the graph, the scaling factor needs to be found.
To find the scaling factor, I minimize the sum of square distances of the data from the graph (the graph is invariant to this scaling, since it's already in the unit-less coordinates).
How should I estimate the variation for the estimated scale factor from such a fit?
Is bootstrapping the correct way to go, or is there anything smarter to do?
Is there any sense in doing residual analysis?
Edit:

Here, the point of clouds with an arbitrary scaling coefficient is depicted in red.
The green cloud is the cloud after the scaling transformation using the scaling factor which minimizes the sum of squares deviation of the data from the graph.
Comment: @ssdecontrol Well, regarding the "error", if the actual value does not vary, but only my estimation of it (i.e. in an ideal world the distribution would be a delta function) the variation can be thought of as an error, can it not? But in this instance, I can't be sure how much of the variation is due to measurement noise and how much is due to actual variation in the sample... So distribution is more accurate here anyway.
Comment: I can't follow your situation. Can you make this more concrete? Can you provide an example &/or some sample data?
Comment: @gung I've added an image with a description, hope it makes it more tangible.
Comment: You're talking about scale on unit-less coordinates. That makes no sense...
Comment: @AlexR. the data points have units, the graph does not. to plot the points on this graph, you have to divide the data points by a number with units which cancel the units of the data, but the size of that number determines where these points end up on the graph.
Comment: @AlexR. thanks, for the feedback, I've edited the question to better explain this part.
Comment: Thanks for clarifying. I still don't understand how "error" is defined here, or for that matter what you would be bootstrapping
Comment: @ssdecontrol By error I mean to give an idea of the distribution of scaling factors which agree with the measurements.

Bootstrapping is done by composing many randomly selected subsets of the measurement data and getting the scaling factor for each subset, thus getting a distribution of possible scaling factors which agree with most of the data.
Comment: "variation" would be a more appropriate word than "error" in that case. What kind of residual analysis did you have in mind? I don't see any residuals here.
Comment: @ssdecontrol Yeah, I was saying error, since I use it to show error margins... But if you think it'd make it clearer I can fix it. BTW, I've edited the previous comment while you were typing this one regarding bootstrapping, in case you have missed it.
Comment: There's no such thing as an "error margin" if there's no "error". It's just a visualization of a distribution -- very important, but _not_ an error.
Comment: I was wondering about the "residual analysis" you refer to in the main question
Comment: @ssdecontrol Regarding the residual analysis - some of my colleagues argued that bootstrapping artificially over samples the data, and a preferred way to estimate the variation of the data is to examine the distribution of the distance of the cloud around the point it belongs to on the graph... It makes no sense to me, since it doesn't refer to the distribution of the scaling factor... And I want to show how sure I am of that scaling factor.
Comment: @Mr.WorshipMe you are right that it makes no sense. That "residual analysis" addresses an entirely different problem.
Comment: @ssdecontrol Thanks, So do you think what I'm currently doing with bootstrapping is the way to go? I don't know of any alternative that makes sense.
Answer: As we discussed in the comments, there's no "residual analysis" to be done here.
There is one potential issue with bootstrapping. Each draw is supposed to simulate a different run of your experiment, such that a large number of draws approximates the "population" of possible experiment outcomes. Therefore, in order for the bootstrap procedure to work here, you must be able to justify the claim that all possible experimental outcomes are represented in your data.
For example, let's say there's a bowl of 100 red and blue jelly beans on the table, and you'd like to estimate the proportion of red ones. In truth, there are 50 of each color. You blindly draw a sample of 15 jelly beans, of which 3 are red and the rest are blue. No matter how many bootstrap replicates of this 15-bean sample you take, you will never be able to accurately estimate the true proportion of red jelly beans in the bowl. Your estimates will always converge incorrectly to $3/15$ instead of $50/100$. This might have been what your colleagues were referring to when they said the bootstrap "artificially over samples the data."
Put another way: the bootstrap is only valid when your sample is a reasonable approximation of its population. It's up to you to make that determination.


Unbounded operator whose spectrum is the entire complex plane?

Question: The question is simple: how to find an unbounded operator $T:H\to H$ where $H$ is a Hilbert space such that $\text{Sp} T = \mathbb C$? This seems a very basic thing, but I have not found an example in the literature.
In some proofs, we need to consider this case separately. This example should be quite important.
Answer: Yes, such an example can be found on page 254 of Reed & Simon's Methods of Modern Mathematical Physics I.
Let $AC[0,1]$ be the family of all absolutely continuous functions on $[0,1]$ whose derivatives are in $L^2[0,1]$. Let $T:L^2[0,1] \to L^2[0,1]$ be the densely defined operator $i \frac{d}{dx}$ whose domain is the set
$$
D(T) = \{ f \in L^2[0,1] : f \in AC[0,1] \}.
$$
$T$ is then a closed operator whose spectrum is the entire complex plane $\Bbb C$. Indeed, observe that
$$
(\lambda I - T)e^{-i\lambda x} = 0
$$
and the function $f(x) = e^{-i\lambda x}$ belongs to $D(T)$ for each $\lambda \in \Bbb C$.
Answer: Here is an elementary example.
Let $a_n$ be a  sequence dense in the complex plane. For example $a_n$ is an enumeration of $\mathbb{Q}\oplus i\mathbb{Q}.$ Consider the operator $T$ on $\ell^2(\mathbb{N})$ given by
$$T\{x_n\}=\{a_nx_n\}$$ with domain $$D(T)=\left\{\{x_n\}\,:\, \sum |a_nx_n|^2<\infty\right \}$$ Then $T$ is closed and the spectrum is equal to the entire complex plane.
Another example: let $$(Tf)(x,y)=(x+iy)f(x,y)$$ act on $L^2(\mathbb{R}^2)$ with domain $$D(T)=\left\{f\,:\, \iint (x^2+y^2)|f(x,y)|^2 \,dx\,dy<\infty\right \}$$
Comment: @operatorerror It seems we got the same example at the same time :) There was an error concerning the domain, which I have just corrected.
Comment: Let the record show I did not see your second example when I wrote my answer ;). In any event, to the OP, the first of these examples is more instructive, it's how you typically build operators with particular properties.
Answer: Consider $L^2(\mathbb C,dA(z))$ with $dA(z)$ the area measure and take
$$
Tf(z)=zf(z).
$$
Recall that the spectrum is the (essential) range of the function defining a multiplication operator.


Drupal 8 what is the ajax event for auto complete dropdown?

Question: Drupal 8, what is the ajax event for auto complete dropdown? i have created form alter, there i am altering my form field that is auto complete field, so now what is the ajax event for this auto complete drop down.
change,
select,
keyup all are not working for this.
Answer: use autocompleteclose event.
<code>#ajax' = array(
  'callback' =>'get_user_details',
  'event' => 'autocompleteclose',
);
</code>


Explaining DADA to EGBG (and in the other direction) in theoretical terms

Question: Please can you help me describe the transition between these two sets of notes in theoretical terms:
DADA

(For clarity, on the guitar: open D string, g string 2nd fret, b string 3rd fret, e string 5th fret)
EGBG

(Guitar: d string 2nd fret, open g string, open b string, e string 3rd fret)
DADA isn't a chord as only two notes but could be described with as an interval: a perfect fifth (D to A). EGBG could be described as an Em chord (EGB) but that's missing the important high G note.
How do I describe these two sets of notes and transition between them? Does playing these two chords in different orders change the key? (Minor v Major)
Comment: Can you explain what you mean by "missing the important high G note"? EGB is an E minor chord regardless of what order the notes come in or whether they are low or high.
Comment: Yes, the doubling of notes in a chord does not change what kind of chord it is. EGEEBGEBBEG is still an E minor chord.
Comment: I believe what you are describing here are different "voicings" of the same chord.  For example, the Em chord played in the open position on a guitar equates to EBEGBE.  See, for example [guitarplayer.com](https://www.guitarplayer.com/technique/essential-chord-shapes-you-need-to-know-alternate-voicings-for-common-chords)
Comment: EGBG, with two Gs sounds a little different.. adds that element of unison for example. Wasn't sure whether I just consider both EGB and EGBG the same chord or not
Answer: Taking D and A notes as a sort of D chord, which could be just about construed as D maj (more chance of hearing an F# harmonic than an F), then the transition between the two could be I>ii, as the other chord is definitely Em.
However, playing the Em first, followed by the D could put things into Em key, as Em and D both emanate from that key.i>VII would be RNs.
So, either scenario works, but adding a 3rd chord would clarify things. With an A(7) chord, it fits firmly into D, whereas with a B(7)it fits firmly into Em.
Incidentally, there is no 'important high note'. As Todd says, three notes such as 1,3,5 will constitute a triad chord, no matter what order, and no matter how many different 1s, 3s and 5s are played. Where did that idea come from?
Comment: Since it's the same name as the 1, it simplifies things! Although, for chords which have extra notes, 9, 11, 13, those numbers represent notes above '1' - (or '8').
Comment: Thanks for the insight! Just personally - I thought playing two Gs in the chord an octave apart, made for a different sound when moving between the two shapes. Was keen to explore the interpretation in theory (clearly I'm not very knowledgeable on the theory front!)
Comment: so 1s, 3s, 5s and Octaves.. I didn't realise that the octave just gets considered as 1.
Comment: Actually I would think the other way around. D > Em alone sounds more like VIIb > Im, and Em > D, like a plagal cadency IIm > I.
Comment: @DVCITIS It sounds different because the voicing and [voice leading](https://youtu.be/ZKM8FtLgvRk) are very different.  That doesn't make it a different chord, but you're right in that the same chord with a very different voicing can generate a radically different effect in a musical context :)   Also take note that we usually place *extra* importance on what note is the bass note of the chord, and sometimes this could cause us to choose a different chord name (but not always!)
Answer: It's ambiguous. Here are merely some of the diatonic possibilities:
Em: VII i
D: I ii
G: V vi
C: ii iii
Am iv v
The reason why these are the first possibilities is twofold: First, the D-A interval first suggests a D chord. It's literally a D5 chord, which is a D chord but is ambiguous in terms of flavor - major or minor. Depending on context, D-A could be heard as an Asus4 chord, but we don't have any reason to hear that in this case.
The second factor is the E minor chord. That is not ambiguous at all - it's an E minor chord. Since it is a major second away from the likely D chord, it tends to imply the D chord is major, because the only diatonic pair of minor chords a major second apart are ii - iii in a major key or iv v in a minor key, which are less common, but possible.
Since there isn't a firmly established key implied by just these two chords, playing additional chords wouldn't necessarily be heard as a key change. Changing the order in which you play these two chords doesn't do very much at all. It's still ambiguous, you would just reverse the order of all the possible interpretations.
Comment: @DVCITIS Changing the order doesn't change the "key" when there is no key in the first place. Playing the E minor chord first *might* make *some* listeners hear a ii I progression in D major, but it's going to be ambiguous in both directions.
Comment: Thanks for the response. My question wasn't about playing the notes back and forth it was about where things ended.


What's the meaning of $x \choose y$ in the Catalan number formula?

Question: What's the meaning of $\choose$ in this formula:
$$C_n=\frac1{n+1}\binom{2n}{n}=\frac{(2n)!}{n!(n+1)!}\qquad\mathrm{for}\;n\geq 0$$
Is it a division?
Answer: The notation $n\choose r$ means "the number of ways of choosing $r$ things out of a total of $n$ given things, where order is not important."  Its value is $n!/r!(n-r)!$.
For example, given five coins, say a penny, a nickel, a dime, a quarter, and a dollar, there are 10 ways to choose two coins with order unimportant, because ${5\choose 2} = 5!/2!3! = 120/(2)(6) = 10$.
Comment: It might also be useful to note that it is referred to commonly as the Binomial Coefficient
Comment: And we might add that the way to pronounce $\binom{n}{r}$ is "$n$ choose $r$".


Induce reachability status check failure

Question: I have some tools that monitor the status checks of all my organisation's EC2 instances. I'd like to test them by deliberately inducing a failure of the reachability status check (that comes by default with all EC2 instances, pictured in the EC2 console below) on one of my instances - ideally through some means that lets me individually break the InstanceStatus version of the check and the SystemStatus version.

How can I do this?
Answer: I typed your query into Google ("test aws instance status checks") and found this page on the AWS forum which has two ways to do it.

An easy way to trigger a status check failure is to disable the
  default NIC in the instance. For Linux instances,

sudo ifconfig eth0 down

should do the trick.
Recovery is by adding an additional ENI to the instance and connecting
  in through that, then bringing the original ENI up with "sudo ifconfig
  eth0 up".

The same page has this

I know this is an old post, but I saw a suggestion from another post
  on reddit/r/aws.
  It looks like you can temporarily set a different state for an alarm.
  I mention temporary because during the next period, the alarm will be
  re-evaluated for it's new state.
Taking a look at the docs I think you should be able to do the following:

aws cloudwatch set-alarm-state \
  --alarm-name "ec2_system_alarm" \
  --state-value ALARM \
  --state-reason "simulate an ec2 system failure"

Comment: This doesn't provide a way to break the system reachability status check, only the instance reachability status check, but is nonetheless useful; +1. (It's not obvious to me whether there even *is* a way to make the system reachability status check fail.)
Comment: System status checks are checks for the underlying hardware. To test that you would need physical access to the AWS data centre.


How can I use Migrate Extras to get custom media fields to migrate?

Question: I'm a bit at the end of my rope in trying to get file fields to show up as possible destinations for my Media module migration.  I have Media 7.1.x installed because as best I can tell, that must be the version that Migrate Extras was supporting.  I'm trying to import files into the Other file type, so I have the following:
$this->destination = new MigrateDestinationMedia('other');
$this->map = new MigrateSQLMap($this->machineName,
      array(
        'id' => array(
          'type'        => 'int',
          'length'      => 11,
          'not null'    => TRUE,
          'description' => 'File ID',
          'alias'       => 'f',
        ),
      ),
      MigrateDestinationMedia::getKeySchema()
    );

Unfortunately I cannot get the field I added to the Other file type to show up as an available destination field in Migrate UI.  Any help on what I'm doing wrong here, or even a code snippet where someone has successfully done a media migration (for files, not youtube or anything fancy like that), would be greatly appreciated!
Update: I'm most of the way there, but my fields still aren't coming in.  Here is the array I created:
I create a $row->fields_array that looks like:
[fields_array] => Array
    (
        [0] => Array
            (
                [field_doc_public] => 1
                [field_testing_testing_testing] => UE2_3009.pdf
            )

        [1] => Array
            (
                [field_doc_public] => 0
                [field_testing_testing_testing] => UE2_3009.doc
            )

    )

I really only need the field_doc_public field to be filled in, but I added field_testing_testing_testing to test as you might guess from the name.  The field machine names are field_doc_public and field_testing_testing_testing.
The code in the actual migration looks like:
    $this->addFieldMapping('field_doc_pub_files', 'file_source_file');
    $this->addFieldMapping('field_doc_pub_files:file_class')
        ->defaultValue('MigrateEntityFileUri');
    $this->addFieldMapping('field_doc_pub_files:fields', 'fields_array')
        ->description(t('Populate the fields.'));
    $this->addFieldMapping('field_doc_pub_files:destination_dir')
        ->defaultValue('private://pub_docs');
    $this->addFieldMapping('field_doc_pub_files:destination_file', 'file_dest_filename');
    $this->addFieldMapping('field_doc_pub_files:file_replace')
        ->defaultValue(MigrateFileBase::FILE_EXISTS_REUSE);
    $this->addFieldMapping('field_doc_pub_files:preserve_files')
        ->defaultValue(FALSE);
    $this->addFieldMapping('field_doc_pub_files:display', file_public);

Any help on that last little push over the finish line would be greatly appreciated.  (Note: no destination for the fields shows up in Migrate UI either)
Answer: The following will allow you to use Migrate to import files as File Entities (used for Media 2.x) and populate the File Entity fields when importing Nodes (MigrateDestinationNode). No Migrate Extras needed.
Add the following to your custom migrate module's .info file:
files[] = includes/MigrateEntityFileUri.inc

Download/save the following code in an "includes" subfolder of your migrate module. (Strip the .php extension)
https://gist.github.com/dmsmidt/6f0f498a9dbaea8602fb
Then in your Migration class you can use 'MigrateEntityFileUri' as file_class.
Example code:
$this->addFieldMapping('field_media', 'your_file_uri_source_array');
$this->addFieldMapping('field_media:file_class')
  ->defaultValue('MigrateEntityFileUri');
$this->addFieldMapping('field_media:fields', 'fields_array')
  ->description(t('Populate the fields.'));
$this->addFieldMapping('field_media:destination_dir')
  ->defaultValue('public://your_file_sub_dir');
$this->addFieldMapping('field_media:file_replace')
  ->defaultValue(MigrateFileBase::FILE_EXISTS_REUSE);
$this->addFieldMapping('field_media:preserve_files')
  ->defaultValue(TRUE);

Note the sources: 'your_file_uri_source_array' and 'fields_array'.
You may need to do some processing in prepareRow() depending on your source to get your data organized like this (pseudocode):
public function prepareRow($row) {
    $row->fields_array = array(
      array(
        'field_one' => 'value_field_file_one',
        'field_two' => 'value_field_file_one'
      ),
      array(
        'field_one' => 'value_field_file_two',
        'field_two' => 'value_field_file_two'
      ),
    );
    $row->your_file_uri_source_array = array('file_one_uri', 'file_two_uri');
  }

Comment: Thanks!  I'lll work on implementing this now, and come back and accept the answer if I manage to get it working.
Comment: I'm mostly there, but the fields still aren't coming across.  I updated my question.  Could you please have a look?
Comment: Have you confirmed this code works for you?  When I run through the migration it looks up a schema that doesn't include my custom files and then walks through the fields in that schema determining what to write.  The values from my array are carried along through the entire process, but seem never to get used anywhere.
Comment: doesn't include my custom fields, not custom files
Comment: OK, this answer doesn't quite do it.  It is the best answer so far, but that file class is not causing the fields to be written.  I'm not sure at what stage or in what method that would normally occur, so I haven't been able to track down what is going wrong.  Going through the debugger it does walk through the custom field array a number of times setting up like it is going to go something.  Once it even checks for the availability of *fieldtype*_field_insert methods, but that is in the file handling section.  I'm probably going to give up and have two file fields one for public, one for not.
Comment: I'm sorry to hear that it didn't work for you. And yes it worked for me. All code was based on a working migration. It may be outdated now, due to some module updates.
Comment: I don't remember the details anymore, but I got it working one way or another.


Expo - Package 'com.xxx.native.xxx' from AndroidManifest.xml is not a valid Java package name as 'native' is a Java keyword

Question: I have used the pattern 'com.mycompanyname.native.appname' to name the bundle Ids for my apps since years and have created many apps using the keyword "native" in the package name. I didn't get this error when using classic expo builds until I switched to EAS builds.
Now, I have to upgrade a few of the live apps, can there be a workaround to overcome this error?
Answer: Yes, there is a workaround, which is a two step progress:

Adjust the package name in your config to be a valid Java name
Use a config plugin to set the applicationId in your build.gradle to your old package name

That way, your applicationId for Play Console stays the same, and the package name used in Java is valid for building.
Here is a gist with an example config plugin, and how to add it to your app.json:
https://gist.github.com/kbrandwijk/cef9e3b01cff91f8dfad8f47f02cb880


What does it mean when two notes are stuck together?

Question: I mean something like this:

I'm guessing it means they're played together but I'm not sure.
Also, does the sharp apply to both pitches or just the G?
Comment: I don't think that this is big enough for a full answer, but I would like to add that on woodwind instruments and possibly instruments which can only play one note at a time (my experience is with flute), it can mean in an orchestral/band context that the note with the staff going up is played by the first instruments (e.g first flutes), and vice versa.
Comment: That's some weird engraving.
Comment: An accidental sharp applies to the staff line on which it appears, for the remainder of the measure. Here, it is on the G (assuming E-G-B-D-F treble clef staff).  It cannot apply to the F.
Answer: Noteheads take up one full space on a staff. (The corollary to this is that noteheads placed on a line take up half of the space on either side of the line.)
When notes are at least a third apart (as in the first measure of the example below), there is plenty of space for two noteheads of standard size to fit on top of each other.

But when notes are less than a third apart (as in the second measure of the above example), there's not enough space to notate the pitches directly on top of each other; doing so just confuses the notation.
So we settle on the solution shown in the final measure, where the noteheads are offset slightly. But in all cases, this notation indicates that the given pitches occur at the same time.
Lastly, accidentals only apply to the staff line or staff space on which they are placed. Since the ♯ here is on the second staff line from the bottom (G, assuming this is treble clef), it only applies to that G, not to the F. If the composer wanted an F♯ in addition to the G♯, s/he would have indicated a second ♯ in the score.
Comment: @AduyummY It would have to be offset from the G♯, yes. Typically, the F♯ would be written as the very first thing in the measure.
Comment: Very well explained.  :)
Comment: I have a question about that last sentence. If the composer added a second sharp to the `F`, would that sharp *also* have to be offset slightly?
Answer: Here are two different screen shots of the same bit of music, from the beginning of the coda in Chopin's second Ballade.  You can see clearly that the passage has groups of doubled 16th notes.  If you look at the last 16th note of the first barred group in the second measure (a D with a natural mark and an E) it will probably be obvious from the context that these notes are to be played together.
I showed you this example because it has an interesting additional problem of notation.  If you look at the fourth and fifth 16th notes in the last group of barred 16th notes in the second measure, you will see that a simultaneous D natural and D sharp need to be played.  Here we go one step further with the problem: two different notes that are on the same line or space of the staff and need to be played together.  The problem is that you can't fit both notes on a single stem as you can two notes right next to each other.  There are different ways to handle this.
This example (which is more common, and is the way that Chopin notates it in his manuscript) has two separate bars on the double notes.  You'll notice that this isn't done with any other group of 16th notes, so the only reason that it's done is to accommodate the D/D# notes.

This example forks a single stem in two so the notes can be written next to one another and still be understood to be played simultaneously.

There is no difference in the way these are to be played.  I personally prefer the second way of writing this, even though it is less common, because I find the intention more immediately obvious.  You'll notice that the two D natural/E double notes before it look exactly the same, whereas they look a bit different in the first example.  So all in all, I find the second example a bit easier to read.
Comment: Fantastic example. This also makes clear that regardless of what choice the engraver makes, the **stems** of the simultaneous notes should approximately line up (though of course, in the first way of notating it, the stems are offset by the width of the natural sign).
Comment: amazing example!
Comment: I wonder if using either Dnat and Eb, or D# and C##, would have made things cleaner, giving up a little "theoretical" precision in exchange a cleaner page and easier performance?
Comment: @supercat For me, that would be harder to read than the way it's written.
Comment: @BobRodes: Look at e.g. page 5 of My Grandmother's Watch at https://www.loc.gov/resource/sm1878.09874.0/?q=my+grandmother%27s+watch&sp=5 for an example of what I have in mind.  The Cdoublesharp in the second measure is hardly wonderful, but I think it's better than alternating sharps and naturals on every note.
Comment: @supercat I entirely agree with you there, but that's a different situation. In that case, the notes aren't played together, and all the grace notes are a half step. So, for consistency's sake, it's best to make each of them a minor second -- you see a few, you get the idea. In this case, Chopin is emphasizing the fact that these notes are clashing and he intends them to. Also, the interval of a second in the measure is a major second, so the augmented unison better differentiates the two. For those reasons I find the augmented unison easier to process.
Comment: @supercat One more thing occurs to me as I look at it. If you separate out the top voice, it seems pretty clear to me that writing E-F-F-D#-D(#)-E is the cleaner way to do it. E-F-F-Eb-E(b)-Enat adds another accidental, and doesn't show the stepwise voice movement as clearly. As for using Cx in the lower voice, that complicates the line. It goes D-D-G#-G#-D-D, etc. which is pretty straightforward to process. If you throw a Cx in there it requires more mental processing to see that it's the same note as the D's.
Comment: @KyleStrand, yes it is all about the stems lining up. In the 2nd example, the  fork of the end of the stem shows that the two notes do in fact share a stem.  Normally, when a second in the same voice shares a stem, the lower note will be pushed to the left. But in the example you gave, since there are two voices and the lower voice needs a stem pointing down, the lower note needs to be pushed to the right, as it is in the 3rd measure, in order for the stems to line up.
Answer: Yes, play them together. They are only placed slightly next to each other, and not one above the other, because they are adjacent pitches and would overlap slightly otherwise. The # is just for the G. So the pair of notes are F and G#. (Unless of course the tied note is an F# anyway...)
Answer: On fretted instruments (like guitar or mandolin), it is possible to play a unison, such as (for mandolin) an open E string and the B string fretted at 7 to make another E; both are played simultaneously. This is fairly common in Bluegrass.
The Notation for this sometimes shows two of the same notes immediately adjacent to each other and on the same line (or space).
Here is an example from part of "Jerusalem Ridge":
Comment: another amazing example!  :)


Dependence of complexity of graph algorithms on weight of edges?

Question: This might be a silly question, but why doesn't the complexity depend on weight of the edges present in the graph?
Comment: Another example of where complexities depend on edge weights is with algorithms for special cases of computationally difficult graph problems (ie NP-hard/NP-complete). Though those are generally only practical if some metric such as max edge weight or total edge weight is sufficiently small.
Answer: There are many different graph algorithms and in some cases the complexities do depend on the edge weights. For example, the Ford-Fulkerson max-flow algorithm has runtime O(mF), where F is the maximum possible flow, which depends on the maximum capacity of the edges. Other algorithms like Dijkstra's algorithm have runtimes that are independent of the edge lengths because it's assumed in the computational model that operations on those weights always take time O(1).
Generally speaking, algorithms with runtimes that depend on the weights/capacities/lengths of the edges in the graph gain their dependency by iterating a number of times based on the capacities/weights/lengths of those edges. If the algorithm only does numeric computations on the weights etc., there typically isn't a dependency because arithmetic operations typically are only considered to take time O(1) unless there's a reason to believe otherwise.
Hope this helps!


How can I calculate $24^{33} \bmod 80$

Question: How can I calculate $24^{33} \mod 80$. I don't see how to start. I only know that $\phi (80) = 32$. A hint would suffice, thanks!
Comment: See https://math.stackexchange.com/questions/607829/get-the-last-two-digits-of-16100-and-17100 OR   https://math.stackexchange.com/questions/1844558/how-to-find-last-two-digits-of-22016
Answer: Hint 1: $80=2^4\cdot 5$ and $24^{33}=2^{99}\cdot 3^{33}$.
Hint 2: Chinese Remainder Theorem.
$\text{ }$
$\text{ }$
$\text{ }$
$\text{ }$
$\text{ }$
$\text{ }$
$\text{ }$
$\text{ }$
$\text{ }$

Solution: $24^{33}\equiv (-1)^{33}\equiv -1\bmod{5}$ and $24^{33}\equiv 0\pmod{16}$, hence by Chinese Remainder Theorem $24^{33}\equiv 64\bmod{80}$.
Comment: Thanks! That's really helpful.
Comment: We can eliminate CRT by using the **mod Distributive Law** -- see my answer.
Answer: Applying MDL $ =\, $ mod Distributive Law $ $ to factor out $\,\color{#c00}{c=16}\,$ below yields
$$ \begin{align} \color{#c00}c\:\!a\ \bmod\ \color{#c00}c\cdot n\ &=\ \  \color{#c00}c\ \ (a\bmod n)\qquad\quad\  {\rm [MDL]}\\[.2em]
{\rm so}\ \ \ 16\mid  24^{33}\Rightarrow\, 24^{\large 33}\!\bmod {16\cdot 5}\, &=\, \color{#c00}{16}\:(\ 24^{\large 33}/16\ \bmod 5)\\[.2em]
&=\, 16\,({(-1)^{\large 33}}\!/1\, \bmod 5)\\[.2em]
&=\, \bbox[5px,border:1px solid #0a0]{\!\!\!16\,(4)}
\end{align}$$
Note how much simpler this is than using CRT - it can be done purely mentally. As explained in the prior linked answer, MDL is an equivalent operational form of CRT, which proves much more convenient for calculations due to its operational form.

How can I calculate $24^{33} \bmod 80$


A question about how to take a -1 out of mutiple-valued analytic function $z^{\alpha } $ $0<\alpha<1 $

Question: I encountered a question about multiple-valued analytic functions.
Under some circumstance I have to take a -1 out of a power function $z^{\alpha } $          $0<\alpha<1$
suppose $\alpha=\frac{1}{2}$, let the branch cut be $[0,\infty ]$, choose the analytic branch $z^{\frac{1}{2}}(1^{\frac{1}{2}}=1)$, and I get two following result they are $$z^{\frac{1}{2}}=((-1)(-z))^{\frac{1}{2}}=(-1)^{\frac{1}{2}}(-z)^{\frac{1}{2}}=i(-z)^{\frac{1}{2}}$$
and
$$z^{\frac{1}{2}}=(\frac{1}{-1}(-z))^{\frac{1}{2}}=(\frac{1}{-1})^{\frac{1}{2}}(-z)^{\frac{1}{2}}=\frac{1^{\frac{1}{2}}}{(-1)^{\frac{1}{2}}}(-z)^{\frac{1}{2}}=\frac{1}{i}(-z)^{\frac{1}{2}}=-i(-z)^{\frac{1}{2}}$$
Which manipulation is right, why? How about $z^{-\frac{1}{2}}$? Is it the same?
Comment: I think what you are asking is this: is $\sqrt{zw}=\sqrt{z}\sqrt{w}$?
Answer: The definition of $z^\alpha$ is $e^{\alpha \log z}$, so let's look at
$\log(-z)$.  If your branch cut for the logarithm (and thus also for the $\alpha$ power) is on the positive real axis,
with real limits as you approach that axis from above, i.e. you're using the branch where $0 \le \text{Im} \log(z) < 2 \pi$, then
$\log(-z) = \log(z) + \pi i$ if $0 \le \text{Im} \log(z) < \pi$ (i.e. $z$ is on  the positive real axis or in the upper half plane),
$\log(z) - \pi i$ if $z$ is on the negative real axis or in the lower half plane.
And so
$ (-z)^\alpha = e^{i\alpha \pi + \alpha \log z} = e^{i\alpha \pi} z^\alpha$ if
$z$ is on the positive real axis or in the upper half plane,
$e^{-i \alpha \pi} z^\alpha$ if $z$ is on the negative real axis or in the lower half plane.
Comment: So when consider a value of the logarithm or power, it's better to return to the definition and examine the argument change?