Unable to access tm.corpus.Reuter21578

Question: i am working on a project that has to connect tweets with news. any ideas how that is possible? I am trying to access tm.corpus.Reuters21578 package in R. but when i execute the following code i get an error.
library(tm)
corpus <- Corpus(DirSource("Data/reuters"), list(reader = readReut21578XML))

Error received:
     Error in DirSource("Data/reuters") : empty directory
Answer: Try this instead:
corpus <- Corpus(DirSource(reut21578),
    readerControl = list(reader = readReut21578XML))

Unable to access tm.corpus.Reuter21578


Formal expression for $A^{-1}$, given $A=1+B$

Question: I have a 2x2 real matrix $A$, with $\det A\not=0$ and I define it as
 $$A=1+B$$ where 1 is the identity and B another regular and real matrix.
I need to express the inverse $A^{-1}$ in terms of B: I have used $A^{-1}A=1$ in order to derive a recurrence relation that yelds
$$A^{-1}=1-B+B^{2}-B^{3}+B^{4}-...$$
which formally is a geometric series in B.
My questions are:

"When this series is properly defined?"
"Does exist a constraint on $B$ in order to deal with a convergent series?"
"If for some $B$ the series diverge, what is the expression for $A^{-1}$ in terms of $B$?"
Answer: You have conditions on the spectral radius $\rho$ :

if $\rho(B) < 1$ then your serie converge
if $\rho(B) > 1$ then your serie diverge

And if $\rho(B) = 1$ it can converge or diverge
The convergence is proved by knowing that $\rho(B) = \inf_N N(B)$ over all the operator norms
The divergence is simple : just take an engeinvector with eigenvalue $\lambda > \rho(B) > 1$ and apply this to the partial sum
Comment: OP might want to know that spectral radius can be calculated by formula $\rho(B) =\lim_n\|B^n\|^{1/n}$ for any matrix norm.
Comment: nice ${}{}{}{}{}$
Answer: Let
$$B=\begin{pmatrix}a & b \\ c & d\end{pmatrix}$$
Then
$$A^{-1}\ =\ \begin{pmatrix}1+a & b \\ c & 1+d\end{pmatrix}^{-1}$$
$$=\ \frac1{(1+a)(1+d)-bc} \begin{pmatrix}1+d & -b \\ -c & 1+a\end{pmatrix}$$
$$=\ \frac1{1+(a+d)+(ad-bc)}\left[\begin{pmatrix}1 & 0 \\ 0 & 1\end{pmatrix}\,+\,\begin{pmatrix}d & -b \\ -c & a\end{pmatrix}\right]$$
$$=\ \frac1{1+\mathrm{trace}(B)+\det(B)} \left[I+\det(B)\cdot B^{-1}\right]$$
Comment: I am trying to generalize your result to a nxn matrix which is real and symmetric: using $AA^{-1}=1$, I get  $$B^{2}-BTr(b)+det(B)1=0$$ which is verified only for n=2. Do you think it's possible to extend your result?
Answer: If you introduce a norm $\| \cdot \|$ on the space of matrices such that the addition and multiplication of matrices become continuous in that norm, then a sufficient condition for that series to be convergent is $\| B \| < 1$.
One such norm is the operator norm: if $A : \Bbb R^n \to \Bbb R^n$ is a matrix, then one defines
$$\| A \| = \sup _{\| v \| = 1} \| Av \|$$
which is perfect for your needs.
Comment: @Jorge Based on $(1+B)(1-B+B^2-B^3+B^4-\cdots +(-1)^kB^k)=1+(-1)^kB^{k+1}$, $\|B\|>1$ should imply the series diverges, assuming $1+B$ is invertible. I'm not sure what to expect if $1+B$ is singular, or if $\|B\|=1$.
Comment: Can we say something strong about necessary conditions?
Comment: I wonder how to express $A^{-1}$ in terms of $B$ when $||B||>1$. Does exist any analytic continuation of the geometric series that I can use when the $||B||>1$?
Comment: @Yildiz: Notice that, if $z \in \Bbb C$ and $|z|<1$ then $\sum _{n \ge 0} z^n = \frac 1 {1-z}$, so the natural analytic continuation to $\Bbb C \setminus \{1\}$ is $\frac 1 {1-z}$. By the identity theorem for analytic functions, this one is also unique. If you try to apply this to your problem, though, you will see that it doesn't help you a bit, because it keeps you moving in circles.


How to close fancybox at facebook canvas application?

Question: I have a facebook application and i use fancybox. I want to close fancybox with following code but when user clicks the Close link, fancybox opens again. This code works at a non-facebook page.
Close

Does anyone have idea how can i close the fancybox at a facebook canvas application?
Comment: Are the link and the parent page on the same domain?
Comment: What is the code that attaches fancybox look like?
Answer: I am guessing fancybox is tied to anchor tags, so your code closes it, but the event listener attached picks up the click and fires the open. Try using another tag to fire your close script:
Close

If that works you can add styles to your span to give it the pointer cursor and otherwise make it look like a link if you want to.


How to change cell color of datatables?

Question: I am using Datatables and I want to update my table colors.(all cell colors including headers).
I found some solutions but problem is I have nearly 200 tables and I don't want to update my tables colors one by one. Is there any way to change color of all tables?
EDIT: I am using simple Datatables like;
$(document).ready(function() {
   $('#myDt').DataTable( {
       "paging":   false,
       "ordering": false,
       "info":     false
   } );
} );

Comment: Please post your code...
Answer: This is how I do it.
Apply a class (DT in this case) to each Datatable.
Then use css to overwrite the colours.
HTML

//Code here ...

CSS
For the header:
.DT thead th,
.DT tfoot td {
  background-color:#111;
}

For rows and alternate rows:
.DT tbody tr.even,
.DT tbody tr.odd{
  background-color: #eaeaea;
}

How to change cell color of datatables?


How to react with iOS Data Protection if a user disables their passcode?

Question: I have an iOS 9 app and I have directory of sensitive files in it I am trying to protect (they are proprietary video files). I need to be able to protect these files even from a malicious user who has jailbroken their device and is trying to read the file. Ideally, I would like to use Data Protection to encrypt the file like so:
<code>NSError *protectionError;
NSDictionary *protection = @{ NSFileProtectionKey : NSFileProtectionCompleteUnlessOpen };
BOOL result = [[NSFileManager defaultManager] setAttributes:protection ofItemAtPath:contentDirectory error:&protectionError];
</code>
However, it looks like all a jailbroken user would have to do to gain access to this file is remove the passcode on their device, which renders data protection useless. Is there a way to mark a file as needing to be deleted by the OS in the case where the passcode is removed? I would think this would be similar to how the iPhone and Apple Watch delete Apple Pay cards when a passcode is removed from the device.
Comment: why not encrypt these files on your own using a a key and AES256 Encryption
Comment: Well, I was thinking if I do that I will need to store the decryption key in the app sandbox (our app needs to work offline). If I store the decryption key in a file a malicious user with a jailbroken device could potentially read the key and decrypt the files themselves, since once a device is jailbroken they have full directory access.
Comment: I also know I could embed the key in my binary, but I am hoping to find a different way of doing this, since if the key was ever leaked it couldn't be changed without invalidating any existing downloading files for all of my users.
Comment: Actually, data protection might be useless against a jailbroken device anyways, since it seems that as soon as the device is unlocked the files are accessible (even if there is a passcode).
Answer: I am posting this as answer now..
why not encrypt these files on your own using a a key and AES256 Encryption.
you don't have to hardcode the key in your code, neither you have to store it in sandbox.
You can generate it using the method describe in this question I asked.
Random 256bit key using SecRandomCopyBytes( ) in iOS
Use iOS keychain to store the key.
If you are worried that key can be obtained from the keychain (which is highly secure by the way), then the best bet for you is to decrypt the files using a password as a key which the user will have to enter and you keep your video in memory. You never store this password anywhere, only when the user wants to see this video, he will have to enter it in order to decrypt it.
Comment: The only problem with this is we are trying to protect the content from a malicious user who has a valid account to access our data. Basically I guess it's like DRM. We want to allow them access to the data if they use our app, but not if they are trying to steal the data files. A jail broken device that is owned by a user with a valid account makes passwords useless (because the user knows them!). Similarly, they have access to keychain because they are the user.
Comment: Then you can stream this data from the server. Anything can be done on a jail broken device.


Forecasting a time series $(x_t,{\bf Y_t})$ where all we care about is forecasting $x_t$

Question: Consider a multivariate time series $(x_t,{\bf Y}_t)$ $1\le t \le n$ taking values in $\mathbb{R}^{d+1}$, and suppose that we wish to forecast $x_t$ using its own path as well as the "exogenous" series ${\bf Y}_t$, for instance using a linear time series model. For the sake of simplicity assume all series are (jointly) stationary. One approach that seems clear is to fit a VAR model, and then use the corresponding forecasts for $x_t$, but this seems sub-optimal, since the VAR model fit using ordinary least squares would not optimize the parameters to forecast $x_t$ alone.
Transfer function models also do not seem useful here, since, when forecasting $x_{n+h}$, they presume the corresponding "covariates" ${\bf Y}_s,\;\;s\le n+h$ are known when making the forecast, when we would only have observed ${\bf Y}_s,\;\;s\le n$. I guess one might forecast the ${\bf Y}_t$ series to input into the transfer function model, but again this doesn't seem optimal. Having done a fair bit of googling on the topic, I could not find any real guidance on what seems like a very standard problem.
Can anyone point me in the right direction? Or perhaps some of these simple ideas (VAR, transfer function model with forecasted covariates) is more optimal than I think?
In response to IrishStat's comment, I'll post a simple example using a transfer function model (at least a simple version of one using simple linear regression with ARIMA errors as implemented in auto.arima). Suppose that we wish to forecast the cardiovascular mortality in Los Angeles county, and we also have access to the daily temperature and particulate matter pollution concentration (data from the astsa package in R). I can do this in R as follows:
<code>#Begin R code#
library(astsa)
library(forecast)
library(TSA)

\#taking data at monthly resolution (every four weeks, so that the approximate
\#seasonality/frequency is 13

cmort2=ts(lap[seq(1,508,by=4),3],frequency = 13)
temp2=ts(lap[seq(1,508,by=4),4],frequency = 13)
part2=ts(lap[seq(1,508,by=4),11],frequency = 13)
dat.mat=cbind(as.numeric(temp2),as.numeric(part2))

\#producing forecasts for temp2 and part2 using auto.arima to be
\#fed into the arimax model

temp.mod=auto.arima(temp2)
part.mod=auto.arima(part2)

temp.for=forecast(temp.mod,h=12)
plot(temp.for)
part.for=forecast(part.mod,h=12)
plot(part.for)

temp.for=ts(temp.for\\\$mean,frequency = 13)
part.for=ts(part.for\\\$mean,frequency = 13)
dat.mat.for=cbind(temp.for,part.for)

ar.regf=auto.arima(cmort2, xreg=dat.mat)
x=forecast(ar.regf,xreg=dat.mat.for,h=12)
autoplot(x)

\#for comparison, a simple SARIMA model excluding the covariates

ar.noregf=auto.arima(cmort2)
x.noreg=forecast(ar.noregf,h=12)
autoplot(x.noreg)

##end R code##
</code>
I guess my questions about this are:

Is this really the best/a reasonable thing to do to forecast $x_t$=LA cardiac mortality? The sub-optimal part seems to be that we must input forecasts for the covariates, which rely on modeling the covariates separately from the response.
I assume that the confidence bands produced in forecasting $x_t$ are not accurate since they do not account for the uncertainty in the forecast of the covariates. Does anybody know if this is the case? I could imagine fixing this myself by producing confidence bands via simulation, but one wonders how to automatically incorporate the forecast uncertainty into the confidence bands for the transfer function model.
Comment: You say "they presume the corresponding "covariates" are known" . I say  "they can be forecasted using their history AND the uncertainty in those forecasts can be propagated to get a composite/collective uncertainty in the output series." Post your representative data and I might be able to help further. One caveat the causal variable is ASSUMED to be not dependent on the output series
Comment: Thanks for the comment IrishStat! I added an example, and have asked a more specific question.
Answer: Does anybody know if this is the case?
Yes your are right it regrettably does not incorporate the uncertainty in the predictors .
You say "  I could imagine fixing this myself by producing confidence bands via simulation, but one wonders how to automatically incorporate the forecast uncertainty into the confidence bands  for the transfer function model.
I say "Not only did I wonder I actually implemented this feature into AUTOBOX , which I have helped to develop using multi-variable monte carlo techniques allowing for the inclusion of possible future anomalies . I used some innovative convolution procedures to accomplish this tour de force  . I refrained from publishing these major advancements due to understandable exclusivity concerns.
I am sure that with enough time and perseverance you will be able to follow my guidance here.
There is an R version available if you are interested.
Comment: I hate to say it, but it deserves being made explicit: "refrained from publishing" along with marketing-speak is a classic snake-oil recipe.  Maybe it works, maybe it doesn't, and the only bits of evidence we have are (1) your claims and (2) any public applications of your work.  There are some memorable applications of your software that [produced measurably inferior results,](https://stats.stackexchange.com/a/10514/919) so what is left?  *Publish and let your peers validate your "innovative ... tour de force."*
Comment: That is about as anti-scientific and anti-statistical as one can get.  If you want to support your approach through results, then at the least you should publish your forecasts and then, later, analyze their accuracy.  The standards applicable to software should be no less stringent than those we apply to fortune tellers and seers. Please note that I am *not* asserting your procedures are bad or even inferior: I am only saying that they cannot be trusted until such evidence is produced *and* the scope of their applicability is clearly delimited.
Comment: That would be telling .The proof is in the pudding .
Comment: Hi: There's a paper by Richard Baillie ( econometrician ) whose title escapes me that is related to your question. If it doesn't give the direct answer, it will atleast point to some other good references.  I'll try to find a list of his papers and get the title. I can't do that right now but probably tonight. Also, feel free to look for it yourself. I'm pretty sure that I spelled his name correctly.
Comment: Hi: It was easier to find than I expected. I was referring to the first one right at the very top but, based on the titles,  it could be that the second or third one are more relevant. I hope it helps in some way. As I said, one of them should atleast lead to other useful references if nothing else. https://msu.edu/user/baillie/articles.htm


call save function from another form

Question: does anyone knows why this code is not working? On main form I have save function but whenever i click Save button message "nothing to save appears".
    public void spremiIzmjene()
    {
        try
        {
            this.bindingNavigator1.BindingSource.EndEdit();
            DataSet imaPromjene = this.dimproDataSet.GetChanges();
            if (imaPromjene != null)
            {
                int brojRedova = this.op_kontaktTableAdapter.Update(dimproDataSet.op_kontakt);
                MessageBox.Show("Izmjene spremljene: " + brojRedova + " red dodan.", "Uspjeh");
                this.dimproDataSet.AcceptChanges();
                this.dimproDataSet.Clear();
                this.op_kontaktTableAdapter.Fill(dimproDataSet.op_kontakt);
            }
            else
            {
                MessageBox.Show("Nothing to save", "No changes");
            }
        }
        catch (Exception ex)
        {
            // msg
            this.dimproDataSet.RejectChanges();
        }

    }

I call this function from my insert form.
Problem: I need to open insert form, enter data into fields, close form (but not to write to db, only keep dataset changes) and then on form closing event call spremiIzmjene() on main form. But whenever i call that function dataset.HasChanges return false

thanks
Comment: `If no changed rows are found, the method returns null.` http://msdn.microsoft.com/en-us/library/a4ey25we(v=vs.110).aspx Sounds like nothing changed.
Comment: I just updated my question with problem description.
Comment: when i put this code into insert form save button click event data is saved
Answer: Yeah, because nothing has changed. In other words, if you had data bound controls, none of the values changed. If you were updating rows by hand, you probably called AcceptChanges when you shouldn't have. In short, when modifying data in a DataTable, which resides in a DataSet, you want to make those modifications but don't call AcceptChanges because that changes the RowState back to Unchanged.
Comment: @CarloŠtefanac, that's fine. As stated, *if you were modifying rows by hand.* In other words, in another method. In your case, leave the `AcceptChanges` where it was and fix your binding. You need to bind your controls to a `DataRow` in the `DataTable` so that the changes can be recognized; your binding isn't correct.
Comment: @CarloŠtefanac, have a look at this post here. http://www.codeproject.com/Articles/24656/A-Detailed-Data-Binding-Tutorial

call save function from another form


How many number of paths are there

Question: How many number of paths are there from (0, 0) to (4, 4) using the moves
R : (x, y) → (x + 1, y),  U : (x, y) → (x, y + 1), D : (x, y) → (x + 1, y + 1) ;
where a path can never rise above the line y = x.  Solve this problem by using Catalan Numbers.
I know the n-th Catalan Number formula $$C_n = \left(\frac{1}{n+1}\right) {2n \choose n}$$but I don't understand the connection between Catalan numbers and to getting (4,4) from (0,0)

Answer: HINT: Catalan numbers, when you are allowed only the R and U steps; the green entry is the sum of the two red entries, because you can reach $\langle 3,2\rangle$ from below and from the left.
$$\begin{array}{c|cc}
4&*&*&*&*&?\\
3&*&*&*&?&?\\
2&*&*&\color{red}2&\color{green}5&9\\
1&*&1&2&\color{red}3&4\\
0&1&1&1&1&1\\\hline
&0&1&2&3&4
\end{array}$$
Your problem, with R, U, and D steps allowed:
$$\begin{array}{c|cc}
4&*&*&*&*&?\\
3&*&*&*&?&?\\
2&*&*&\color{red}6&\color{green}{16}&30\\
1&*&2&\color{red}4&\color{red}6&8\\
0&1&1&1&1&1\\\hline
&0&1&2&3&4
\end{array}$$
Since you need only the number in the upper righthand corner, you don't need to develop a general formula: just complete the array.
Answer: Hint: The Catalan numbers are the number of ways to go from $(0,0)$ to $(n,n)$ with steps just $R$ and $U$ without going above $y=x.$(These are called Dyck paths) For your problem, notice that by adding the step $D$ you will never affect the condition, so what if you pick first how many diagonal steps (i.e., D) you want to take (lets say $i$) and then, for the remainder, you choose a Dyck path of lenght $n-i$?  To distribute the diagonals in between the Dyck path, notice that you have $n-i+1$ blanks to place the $i$ $ D$ steps.

How many number of paths are there


Duplicate all outgoing IP packets

Question: We're having an issue with our ISP where 75% of our outgoing IP packets are lost to the ether. Incoming packets are totally unaffected, and we assume we're not being throttled because we can send massive bursts of UDP packets without seeing an increase in the dropped packet ratio.
The ISP has been exceptionally slow (weeks) in fixing the issue, and we need to implement a workaround on our end until they can fix the issue. One solution that seems promising would be to duplicate all outgoing IP packets. I realize this might not be ideal for a host of reasons, but we'd still like to give a try.
Is it possible to duplicate all outgoing IP packets and if so, how?
We're mainly using Ubuntu Server 20.04 LTS, but also have some Windows 10 Pro desktops.
Comment: I dont see this as a viable solution. On the receiving end there is no mechanism for discarding duplicate packets that do get through. I would escalate the problem with the isp. Your business is essentially "down" with this kind of issue.
Comment: take a lawyer and screw the isp.
Comment: Or get an offer from another ISP if this one can't do their job properly.
Comment: Who told you this is a "solution"? It seems to be missing some important steps.
Comment: @Greg Askew "One solution that seems promising would be to duplicate all outgoing IP packets. "
Comment: "I realize this might not be ideal for a host of reasons, but we'd still like to give a try."
Answer: iptables -j TEE target is designed exactly to clone matched packets:
man iptables-extensions
TEE
The TEE target will clone a packet and redirect this clone to
another machine on the local network segment. In other words,
the nexthop must be the target, or you will have to configure
the nexthop to forward it further if so desired.

--gateway ipaddr
    Send the cloned packet to the host reachable at the given
IP address. Use of 0.0.0.0 (for IPv4 packets) or :: (IPv6) is
invalid.

To forward all incoming traffic on eth0 to an Network Layer
logging box:

-t mangle -A PREROUTING -i eth0 -j TEE --gateway 2001:db8::1

Comment: No, I don't suggest leaving the origin issue. Actually I *had* problem like the described myself, and nobody went duplicating packets — we routed everything via other ISP for the time being while pressured the problematic one to fix their service, which they did, after several months of denial. (This wasn't the only thing screwed in that case.) However, this question was, "is it possible to duplicate packets, and how"; here's how.
Comment: but would spamming all packets a real solution instead of fixing the origin issue?

Duplicate all outgoing IP packets


.NET Core 3.1 Windows Forms Designer Bug?

Question: I've created a .NET Core 3.1 Windows Forms app and am trying to add a RadioButton inside a Panel inside a TabPage using the designer but it won't let me. Am I doing something wrong, or is this a bug?
In addition, I cannot reposition the Panel using the mouse, only cursor keys.
I can do this just fine in a .NET 4.7.2 app.
Answer: You can double click to user control on components panel.
It will be added to 0,0 coordinate on Windows form.
Comment: That seems to work, but I cannot reposition the Panel or RadioButton with the mouse.


How to add module libraries to the page through an admin page?

Question: Looking for some guidance on how to create a custom module, mymodule, that will pull all the libraries from the custom module and display it in an admin screen. Once the libraries are displayed, I want to be able to set Add to Pages (checkbox) for each library to determine if it should be added to the nodes. It would be ideal if the setting became a configuration.
The goal is to be able to add any libraries I need to the custom module, but selectively add them to nodes using hook_page_attachments. How would I do this?
I initially tried this, but couldn't find a way to get all the libraries.
mymodule.libraries.yml
library1:
  version: 1.x
  header: true
  js:
    path/to/library/file1.js

library2:
  version: 1.x
  js:
    /path/to/library/file2.js

mymodule.module
/**
 * Implements hook_page_attachments().
 */
function mymodule_page_attachments(array &$attachments) {
  $libraries = [
    'mymodule/library1',
    'mymodule/library2',
  ];

  foreach($libraries as $library) {
    $attachments['#attached']['library'][] = $library;
  }
}

Comment: If you only want to add the libraries to nodes, then rather than using `hook_page_attachments()` which will affect all pages, you could use [`hook_ENTITY_TYPE_view()`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_ENTITY_TYPE_view).
Answer: Your module is referencing the library names wrong. It should be "mymodule/library_name" instead of just the library name.
As long as you get that right, it wouldn't be hard to loop node field values or a config object and add them like that.
Comment: Depends on how you want to offer the option, but as long as the names are correct, you can loop and attach them all the same.
Comment: If you store whether to add the libraries in a config/content entity, don't forget to add it as a cacheable dependency to the page to ensure pages get flushed when the entity is changed. (IIUC you should add the dependency even if you're not attaching a library - that way when you later configure it to add the library the cache will be flushed appropriately.)
Comment: @usernameabc yup - that page gives the theory, and you can find an example [here](https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays#concrete-example).
Comment: updated the code to have proper library names. Are you considering a config object one option, but another one could be to have a field on a particular content type that would add the libraries?
Comment: @Andy is this what you are referring to [CacheableDependencyInterface & friends](https://www.drupal.org/docs/8/api/cache-api/cacheabledependencyinterface-friends)?
Answer: Replace:
js:
    path/to/library/file1.js

With
js:
    path/to/library/file1.js: {}


Adding sata disk w/o controller to IBM X3400 M3

Question: We have IBM X3400 M3 with SAS controller and and two disk with raid 1. We need extra space without protection. I try to add standart SATA disk to server. It has two SATA port on mainboard. When I connect SATA disk, it can't boot from SAS controller, try to boot from sata. I can't find any option in boot order for SAS controller. I try to adding SAS controller as boot device in bios but no solution.
I try to another option: buying PCIE 2.0 1x sata controller (IO-PCE9215-4I). This card hasn't got rom, only working in operation system. Amber light on near PCIE slot. I try to disable rom boot option and legacy mode for PCIE slot but no solution. System auto restart while detecting booteable adapter step.
I can't find detail about third party PCI Express sata controller or any PCI Express card working or not with IBM server.
I will making plan to test with PCI sata controller.
Is there any way to adding sata disk to this server without new IBM sas/sata controller?
Answer: You should use second RAID controller for SATA. And this mean also second backplane because you can't split backplane to serve SAS and SATA disk. And you can't mix SATA and SAS in the same bus
EDIT: My practice show me most of the time you can't use third party controllers in branded machines. You should stay with certified controllers for particular machine.
Comment: This info already in manuals. Missing informations are: "You cannot use onboard sata controller with PCI-E SAS/SATA controller.", "You cannot use third party sata controller", "You cannot use third party PCI-E devices." etc. I am not sure we can do these or not.
Comment: @mkysoft, my practice show me most of the time you can't use third party controllers in branded machines. You should stay with certified controllers for particular machine.


Investigate why user has access to a folder

Question: How can I understand why a particular user has access to a particular shared folder?
Security tab of the folder contains a long list of groups groups and the user is not a direct member of any of those groups so there must be some intermediary groups involved.
Answer: Well you didn't give any details about your environment, but assuming a Windows domain, why not Powershell?
<code>Get-ADPrincipalGroupMembership someUser | Select Name
</code>
Now you have a list of all groups of which that user is a member. Of course that only applies to your AD domain, so it will not tell you if that user is a member of any local groups on a computer.
Also I notice you listed network-share as a tag of this question. If this a network share in question, be aware that there are two different kinds of permissions on a network share - share permissions and NTFS permissions. NTFS permissions have the final say, so configuring a network share as "Everyone - Full Control" on the network share permissions is pretty common, and then relying on NTFS permissions to actually grant or deny access appropriately.
Comment: I do get list of groups for which user is a member but none of those groups is granted access to my folder still I have the access. As I mentioned in the question there must be intermediary groups involved. I.e. `User`-->`Group1`-->`Group2`-->`Group3` and `Group3` has access to the folder.


Rules Fetch entity by property using fixed User Role

Question: Versions
Drupal 7
Rules 2.9
Problem
I am trying to loop through all users with a given role. I am trying to pull the users using the action "Fetch entity by property" with property "User Roles" But the value does not allow me to enter a static role. It forces me to select some available variable using tokens. If I enter a static value and save it returns a validation error.
How do I set the property to a static role?
Note the role is not the same as the user creating the node.
Rule
I would include a serialized copy of the rule but frankly none of the rest of the rule matters. Roughly:
Trigger: node create.
Condition: node is published.
Action: Grab all users with editor role.
Action: loop through all users and send e-mail or add to a nodequeue (havn't decided which yet).
More info
The documentation seems to indicate I should use "direct" input mode. However that option does not appear to be available on this form. Am I missing something? is this maybe a bug?
Answer: Answering my own quesiton. I guess I should have found this sooner. But writing it down here helped me process the vocabulary I needed to search for.
I do indeed need to switch to direct input mode. In fact if you switch to direct input mode it will give you a list of roles to select. However direct input mode is not available on initial creation.
To fix simply save as some value (I used site:user:role). Then edit the rule again and direct input will be available. It appears to be a bug listed here: https://www.drupal.org/node/2168961
Thanks and hope this helps someone else.


Assinatura Digital de Lote de RPS (NFS-e) erro: Elemento de referência mal formado

Question: Temos um sistema que envia lotes de RPS para prefeituras de várias cidades do Brasil. O sistema estava enviando os lotes de RPS sem problemas, mas na sexta-feira passada (11/03/2016) parou de funcionar e apresentou a mensagem: Elemento de referência mal formado. Identificamos que este erro ocorre no momento da assinatura do arquivo XML (signedXml.ComputeSignature()).
Para resolver este problema, desinstalamos todas as atualizações do Windows do dia anterior (10/03/2016) referente a: Atualização de Segurança para Microsoft Windows - KB3140735, KB3140410; KB3139940; KB3139929; KB3139914; KB3139852; KB3139398; KB3138962; KB3138910; KB3135988; KB3135983 e Atualização para Microsoft Windows - KB3138612; KB3121255; KB3118401; KB2952664. (Nota: Não identificamos qual dessas atualizações gerou este problema)

Espero que esta dica ajude quem estiver com este problema.
Configurações que estou usando:
SO: Windows 7 32 bits
Plataforma de Desenvolvimento: VB.Net - Visual Studio 2010 (Framework 3.5)
Se alguém souber resolver este problema, sem precisar desinstalar as atualizações do windows, eu agradeço.
Abraço.
Alexandre Melo
Comment: No caso do Windows 10, "resolvi" o problemas removendo a atualização: KB-3140768.Mas isso não é uma solução! Assim como o Alexandre, também gostaria uma solução. Não consegui implementar a solução descrita neste tópico: [Possível solução](http://pt.stackoverflow.com/questions/117568/assinar-nfs-e-em-c-gera-erro-elemento-reference-mal-formado) Abraço
Comment: no windows server 2008 instale o certificado da MS que resolve, no 2012 ainda estou testando uma solução prática. Certificado:
http://go.microsoft.com/fwlink/?LinkID=747875&clcid=0x409 Flayner
Answer: Problema corrigido.
Após atualização do framework, foi feita uma correção de vulnerabilidade nas assinaturas.
Junto com essa correção, algumas regras para formar o Id de um XML que será assinado.
1o. O Id precisa começar com letras, não pode iniciar com numeros;
2o. O caracter / não é mais aceito no conteúdo do Id. Imagino que outros   caracteres especiais tambem não sejam aceitos, como :;^~, etc
Comment: Você é o mesmo que criou a pergunta?
Answer: O suporte da Microsoft que trata desse tema está no seguinte endereço:
https://support.microsoft.com/en-us/kb/3148821
Mesmo após instalar a nova chave no registro da máquina, a solução só apareceu com a desinstalação do KB3140745, no meu caso.
Na documentacao da MS, tem as atualizações para cada versao de sistema e framework


Work around to make table-cell CSS render properly in IE6/7?

Question: My site is showing up fine in IE8/Firefox/Chrome but I can't figure out how to make it function with IE.
The relevant CSS:
#maincontent {
  display: table;
}

#content {
  display: table-cell;
  width: 620px;
  padding-left:4%;
  padding-right: 22px;
  padding-bottom:15px;
}

#sidebar {
  display: table-cell;
  width: 300px;
}

#content and #sidebar are in #maincontent. On IE6/7 #sidebar will be under #content. I've tried setting the sidebar to display:block with a float, and it will then render fine in IE6/7 but all the other browsers get screwed up. How can I get this setup?
Answer: From W3Schools:

No versions of Internet Explorer
  (including IE8) support the property
  values "inline-table", "run-in",
  "table", "table-caption",
  "table-cell", "table-column",
  "table-column-group", "table-row", or
  "table-row-group".

The best solution is probably to build a real table.
Comment: Provided that whatever it contains is semantically tabular data. If your intent was merely to provide table-like layout for non-tabular elements, then you'll want to continue to explore non-table-based methods.
Comment: Good point. I shouldn't have made the assumption it was a data table.
Comment: W3Schools is not affiliated with the W3C and has a reputation for incorrect or poorly explained information. See http://reference.sitepoint.com/css/display#compatibilitysection for accurate information
Answer: CSS tables aren't supported in IE, so you'll probably want to try working with just floats and margins.  I'd recommend taking a look at the positioning on one of these templates and working from there.


Replacement Tokens in View Template

Question: I have several fields in my view:

Path (excluded from display)
Image
Body
Button (rewritten to use [path])

I need to output the image like so (this is a requirement):
TITLE

I cannot do this using rewrite rules because of  https://www.drupal.org/node/417956 which explains that views runs all rewrites through filter_xss_admin(). This function strips out the style attribute on the a tag.
I am attempting to implement this in a view template, specifically the Field Content: Image (ID: Image) template:
<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<a href='/' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?>

I have tried this, [path] remains unchanged:
<a href='[path]' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?>

and this, [path] remains unchanged:
<a href='<?php print token_replace("[path]", array('node' => $row->_field_data['nid']['entity'])); ?>' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?>

I cannot find the value of the path anywhere in any of the variables. How can I output the value of [path] in my view template?
Comment: Which template views template file are you overriding? field or fields?
Comment: I think it's because you excluded it, try un-excluding your path from display.
Comment: including the path (not excluding it) has no effect
Answer: Can you get the node id you are aiming for? If so, try using drupal_get_path_alias()
$linknid = $fields['field_link_to_content']->content;

$alias = drupal_get_path_alias('node/' . $linknid);

<a href='<?php print $alias; ?>' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?>

UPDATE - this is how I did it, based on this answer:
<a href='<?php print drupal_get_path_alias('node/' . $row->nid); ?>' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?>

Comment: I'm sure I could. I was hoping to avoid another db call...but I will give it a shot

Replacement Tokens in View Template


What does "Flag." mean in orchestra score?

Question: At the very beginning of Mahler's Symphony No. 1, where the strings drone an A in seven octaves, what does "Flag." mean in the orchestral notation?

Also, The Wikipedia page mentions

...with the upper octaves being played on harmonics in the violins.

Is this related to whatever "Flag." means?  If not, then what does the Wiki article mean by "playing on harmonics"?
Answer: Flageolet.  Which means playing harmonics by lightly touching the string at some fraction of its total length.
Comment: Thank you for a quick and concise answer.  I just now learned that one can play string instruments like that - I was always under the impression that violinists (and other orchestral string players) always pressed the strings down hard onto the fret board (like a guitar)... Learned something new today!


Lemma 2.8 - Elements of integration by Bartle

Question: I'm self studying Measure Theory by Bartle's book and I have a doubt in the proof of a lemma. Before I say what is the lemma and what is my doubt, I would like to say that the book is available here if anyone wants to see and I would like to introduce some notation according to the Bartle's book that I believe it's necessary to understand the proof of the lemma.
$\textbf{Notation:}$
(i) $\overline{\mathbb{R}} := \mathbb{R} \cup \{ -\infty, +\infty \} $ is the extended real number system and the function with codomain $\overline{\mathbb{R}}$ are said to be extended real valued functions.
(ii) $\textbf{X}$ in bold is the $\sigma-$algebra of a set $X$.
(iii) The collection of all extended real valued $\textbf{X}-$measurable function on $X$ is denoted by $M(X, \textbf{X})$.

$\textbf{Lemma 2.8}$ An extended real valued function $f$ is measurable if and only if the sets
$$A := \{ x \in X \ ; \ f(x) = +\infty \} \hspace{0.5cm} \text{and} \hspace{0.5cm} B := \{ x \in X \ ; \ f(x) = - \infty \}$$ belong to $\textbf{X}$ and the real-valued function $f_1$ defined by
$$f_1(x) := f(x), x \notin A \cup B$$
$$f_1(x) := 0, x \in A \cup B$$
is measurable.
$\textbf{Proof:}$
If $f \in M(X, \textbf{X})$, it has already been noted that $A$ and $B$ belong to $\textbf{X}$. Let $\alpha \in \mathbb{R}$ and $\alpha \geq 0$, then
$$\{ x \in X \ ; \ f_1(x) > \alpha \} = \{ x \in X \ ; \ f(x) > \alpha \} \ \backslash \ A$$
If $\alpha < 0$, then
$$\{ x \in X \ ; \ f_1(x) > \alpha \} = \{ x \in X \ ; \ f(x) > \alpha \} \cup B$$

The proof continues, but my doubt emerges here. I would like to know why $\{ x \in X \ ; \ f_1(x) > \alpha \} = \{ x \in X \ ; \ f(x) > \alpha \} \cup B$? I don't know why $\{ x \in X \ ; \ f_1(x) > \alpha \}$ have points of $B$ since $\alpha$ is fixed.
Thanks in advance!
Answer: This equality is valid for $\alpha <0$, so
\begin{align}\{ x \in X \ ; \ f_1(x) > \alpha \}&=\{ x \in X \ ; \ f(x) > \alpha \}\cup\{ x \in X \ ; \ f_1(x) =0 \}\\[1ex]
&=\{ x \in X \ ; \ f(x) > \alpha \}\cup (A\cup B)\\[1ex]
&=\{ x \in X \ ; \ f(x) > \alpha \}\cup B
\end{align}
since   $\;A\subset \{ x \in X \ ; \ f(x) > \alpha \}$.
Comment: I understood now, thanks a lot!
Comment: I was struggling here too. Thanks!


Verification in Big O notation

Question: Suppose $f(x)$ is sum of the series whose terms are $f_n(x)$ and series converging uniformly and absolutely. It's also given that $|f_n(x)|=O(g(x) a_n)$ as $n$ tends to infinity and series with terms $a_n$ also converges. Then can we conclude that $f(x)=O(g(x))$ as x tends to infinity?
My guess: If $f(x)= \sum_{n=1}^{\infty} f_n(x)$ and $|f_n(x)|=O(g(x) a_n)$ then after certain $n$ we have $f_n$ is bounded by $g(x)a_n$ and since  $\sum_{n=1}^{\infty} a_n $ converges $g(x)$ will come out of series and give  $f(x)=O(g(x)) $ as x tends to infinity.
Please verify whether this argument is correct.
Comment: I guess $$|f_n(x)|=O(g(x) a_n)\text{ as } n \to \infty$$ means for each fixed $x$ we have that estimate, and the constants may vary with $x$ in an arbitrary manner??  Then the conclusion $$f(x) = O(g(x))\text{ as }n\to \infty$$ is meaningless.  Do you want a different "as" clause for this $O$ ??  Please clarify the statement.
Comment: I want $f(x)=O(g(x)) $ as x tends to infinity given $|f_n(x)|=O(g(x)a_n) $ as n tends to infinity. And for each fixed x we have that estimate.
Comment: Well, fix the question to show what these $O$ statements mean.
Comment: Yes fixed that! Thanks for pointing it out.
Answer: If the O-constant depends on neither $x$ nor $n$ then the following proof works (this is basically what you get after elaborating your guess):
It is known that there exists $K_1>0$ such that
$$
|f_n(x)|\le K_1g(x)a_n
$$
This means if we set $K_2=K_1\sum_na_n$ then
$$
\sum_n|f_n(x)|\le K_2g(x)
$$
Now, by triangle inequality we get
$$
|f(x)|=\left|\sum_nf_n(x)\right|\le\sum_n|f_n(x)|
$$
Therefore, we see that $f(x)=\mathcal O(g(x))$.

Verification in Big O notation


Surface Area Multivariable Calculus

Question: Find the surface area of the portion of the sphere $x^2$ + $y^2$ + $z^2$ = 25 that lies inside the cylinder $x^2$ + $y^2$ = 9.
My attempt at a solution: $z^2$ = 25 - $x^2$ - $y^2$, so z = $\sqrt{25 - x^2 - y^2}$. Then, partials of z: $\frac{-x}{\sqrt{25 - x^2 - y^2}}$ and $\frac{-y}{\sqrt{25 - x^2 - y^2}}$.
So, SA = $\int$$\int$ $\sqrt{1 + \frac{x^2}{25 - x^2 - y^2} + \frac{y^2}{25 - x^2 - y^2}}$dydx. Converting to polar:
$\int$$\int$ $\sqrt{1 + \frac{r^2cos^2\theta}{{25 - r^2}} + \frac{r^2sin^2\theta}{{25 - r^2}}}rdrd\theta$, and simplifying and adding limits of integration gives $$\int_0^{2\pi} \int_0^3 \sqrt{1 + \frac{r^2}{25-r^2}} rdrd\theta$$.
I'm stuck as to where to go from here. I guess I could've made a mistake earlier in the problem but I'm confident with what I have so far.
Comment: @Crazy how exactly did you get there?
Comment: $$ \sqrt{\frac{25-r^2}{25-r^2}+\frac{r^2}{25-r^2}}$$ That is the trick! Now it is just basic integration which you are able to see!
Comment: Continue from your work we have $$\sqrt{\frac{25}{25-r^2}}$$, I think you can move on!
Comment: @Crazy Thanks... I ended up getting $10\pi$ when the answer is double that. Not sure what went wrong.
Comment: Your forgot the lower half of the sphere inside the cone! What you got is just the upper part of the sphere! We know that they are same in surface area! So no need to do work. Just double the answer you got for the upper part and we will got the total surface area as desired!
Comment: @Crazy So my limits of integration should've gone from 0 to $4\pi$? If not, where did my work go wrong? I guess maybe the issue was I only had the positive square root of z, giving me the top half of the sphere inside the cylinder...
Comment: No need to integrate until $4 \pi$ $x^2+y^2+z^2=25$. Know that square root will product plus minus sign. You just take the positive one which is the upper part of the sphere!
Comment: Glad to help!!! Try to answer your own question!
Answer: Let us consider the spherical coordinates:
$$x = r \sin(\theta) \cos(\varphi)\\
y = r \sin(\theta) \sin(\varphi)\\
z = r \cos(\theta)\\
$$
$$
r \in [0, + \infty) \\
\theta \in [0, \pi] \\
\varphi \in [0, 2 \pi)
$$
Here $(r, \theta, \varphi)$ stand for the radius, inclination, azimuth correspondingly.
Note that the region you are looking for is the union of two hemispheres of the same surface area.
The spherical volume form is $$dV = r^{2} \sin\theta \, dr \, d \theta \, d \varphi$$
Finally, the problem reduces to the following computation:
$$V = 2 \int_{R} {d V} = 2 \int_{0}^{\arccos(\frac{3}{5})} \int_{0}^{2 \pi} {25 \sin \theta \, d \theta \, d \varphi} = 50 \cdot 2 \pi \cdot (-(\frac{3}{5}-1)) = 40 \pi$$
(if i'm not mistaken, of course)
Comment: Answer should be $20\pi$, not exactly sure what went wrong.

Surface Area Multivariable Calculus


Ajuda para importar dado SQL e usar na data

Question: O título está muito baralhado mas não sei o que quero fazer.
Dentro de uma tabela com dados que veem do  banco de dados
Tenho a seguinte estrutura:
echo '
 '.$row["data"].'
';

Até aqui tudo bem, aparece as varias datas  na tabela. Agora
Preciso de usar o valor que vem da data para usar outro código ex:
$dataextenco = '.$row["data"].';

// Transformar a data que vem do BD em dia da semana

// Tabela

echo '
 '.$row["data"].'
';

Desculpem por estar muito baralhado, mas não consigo explicar melhor e aqui não tenho o código completo.
Comment: Bem vindo Vitor! Meu caro colega, você disse que não sabe o que quer fazer, não consegue explicar e não tem o código! Se nem você está sabendo e possui nada, imagine nós!? rs Precisa melhor a pergunta, se não é impossível ajudarmos algo que nem mesmo você sabe nos passar.
Comment: Sem informação eu sei que e difícil.
Comment: Obrigado vou tentar colocar aqui um printscren
Comment: Vitor, não é por nada não, mas sem condições de andar com sua pergunta dessa forma. Se eu continuar ajudando estarei aprovando a "má qualidade" e isso está errado. Peço que leia ao menos o [Como criar um exemplo Mínimo, Completo e Verificável](https://pt.stackoverflow.com/help/mcve). Assim podemos continuar.
Comment: Se você tem o código, simplesmente copie e cole aqui, era até mais fácil que tirar foto! Além de estar atropelando tudo. Não adianta pegar um código e ir alterando sem ao menos entender o que ele faz. É complicado para ambos. Aqui ajudamos com dúvidas, não a fazer códigos. Tomara que entenda o que eu quis dizer... ✌
Answer: Imprimindo o dia da semana:
 // Array com os dias da semana
 $diasemana = array('Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sabado');

 // Aqui define a data no formato Ano-mês-dia (2018-09-11)
 $data = $row["data"];

 // Varivel que recebe o dia da semana (0 = Domingo, 1 = Segunda ...)
 $diasemana_numero = date('w', strtotime($data));

 // Exibe o dia da semana
 echo $diasemana[$diasemana_numero];

Referência
Dia da Semana em PHP


Drawing a line with a gradient color in OpenCV

Question: I found this question for different technologies but not using OpenCV in c++. I need to draw a line that changes its color in order to represent direction One color where it starts and another where it finishes, so visually I can see the direction of several trajectories I have. each trajectory has several points, but not the same amount.
Comment: Can't you just use an [arrow](http://docs.opencv.org/master/d6/d6e/group__imgproc__draw.html#ga0a165a3ca093fd488ac709fdf10c05b2)?
Comment: @Miki that's pretty cool, didn't even know that existed in OpenCV.
Comment: @miki there is too many trajectories, that it will not provide much help in the visualization.
Comment: Maybe you can show a few images so we can get a better idea
Comment: Here's how to draw a line, so you could draw it and calculate the percentage of your distance from line start to line end at each point and use that to determine the appropriate colour for the point... https://en.m.wikipedia.org/wiki/Bresenham%27s_line_algorithm
Comment: Or, create a simple straight, horizontal line of varying colour on a piece of spare canvas (i.e. a Mat) at the start of your program. Then, each time you want to plot a line, clone your original line, resize it to the correct length, rotate it and copy it to the origin of your desired line.
Answer: I assume you want different colors for each direction? What i would do is i would pick a reference line like horizontal one. And calculate angle between each line and the horizontal line. Then i would map 255 value to 360 degree for example color=255/360*angleFound. Then put this value to cv::line function. cv::line(  ,  ,  RGB(color,color,color)). This is an example. You can put this color value in different ways. In this way each direction would have its own color.


For $N,M\in \mathbb{N}\gt\gt 1$ can we have $N$ consecutive natural numbers of which $M$ are prime?

Question: We know that for an arbitrarily large $N \in \mathbb{N}$ we can have $N$ consecutive natural numbers of which none is prime. A construction that verifies this is the set $B(n)=\{n!+2, n!+3,\cdots,n!+n\}$ since the first term is divisible by $2$, the second by $3$ and so on. So we have gaps between primes which are as large as we want them to be.
I was wondering-as part of a cryptography application I was working on-whether

For a given $M\in \mathbb{N}$ can we choose an $N$ such that $N$ consecutive natural numbers are not primes but there exists a set of $N$ consecutive natural numbers of which $M$ are prime?

Or, for $S_N=\{s+1,s+2,\cdots,s+N\}$ such that no $s+i, i\in\{1,2,\cdots,N\}$ is prime can we have $A_n=\{a+1,a+2,\cdots,a+N\}$ such that $A_N\supset Q=\{a+j_1,a+j_2,\cdots,a+j_M\}$ is a set of $M$ primes?
The two sets can differ in terms of how large the numbers are and no other similarities except of their cardinality are required.
I think it is obvious that $M\lt\lt N$ given the "scarcity" of primes the larger the $N$ is.
Answer: For any $M$ there will be infinitely many solutions. Here is how we can generate them. What we need is given $N$ and $M$ find an $x$ such that
$$
\pi(x + N) - \pi(x) \ge M.
$$
where $\pi(x)$ is the prime counting funciton. The following approximation by Dusart is known
$$
\frac{x}{\log x - 1} \le \pi(x) \le \frac{x}{\log x -1.1}
$$
where the lower bound holds for $x \ge 5353$ and the upper bound holds for $x \ge 60184$. Note that there are sharper bounds on $\pi(x)$ which are valid for bigger $x$, but for us the above inequality is good enough get an approximation of $x$. Thus we have
$$
\pi(x + N) - \pi(x) \ge \frac{x+N}{\log (x+N) - 1}  - \frac{x}{\log x - 1.1}
$$
for $x \ge 60184$. So all we need to do is solve the weaker inequality
$$
\frac{x+N}{\log (x+N) - 1}  - \frac{x}{\log x - 1.1} \ge M.
$$
For any given $N$ and $M$ this can easily be solved to obtain the lower bound on $x$. Thus the $N$ consecutive natural numbers $x+1, x+2,..., x+N$ will contain at least $M$ primes.
I leave the algebraic manipulation/simplification to the OP. If you want a better on $x$ all you need to do is use sharper bounds on $\pi(x)$.
Comment: Thanks you for this answer. I will try to put it to use!
Answer: This is actually an open problem, but conjecturally it is fairly well-understood.  See my answer here to a related question: the relationship between the two problems is in fact surprisingly close!
As Ross Millikan has pointed out, obviously it is possible for $M$ to be as large as $\pi(N)$, but in fact Hensley and Richards showed there are admissible tuples which are even denser, about $\pi(N) + c N/(\log N)^2$ in size for some $c>0$.  It appears to be an open problem (as of 1985) whether $c$ can be arbitrarily large.
One catch is that just because we have an admissible tuple, doesn't mean we have the computational resources to find an actual suite of primes corresponding to those offsets.  The prime $k$-tuples conjecture predicts that there are infinitely many examples, but at this scale (thousands of primes!) they are expected to be so exceedingly rare that it would take an enormously long time to find a concrete example.
Comment: Thank you for this. It is somewhat discouraging that the existence of the said tuple doesn't match the ability to find it but I guess answering the more general question has just became infinitely more intriguing!
Answer: The longest string of primes is two, composed of $2$ and $3$.  All even numbers other than $2$ are composite, so there is no other string longer than one.  Similarly, the shortest run of naturals with three primes is four, composed of $2,3,5$.  I suspect the smallest $N$ such that there are $M$ primes in a run of $N$ is the run from $2$ to $p_M$, the run that includes the first $M$ primes.  For five primes you would argue that unless you can include $2$ the run has to be longer than ten numbers.  Among ten numbers only five are odd and at least one of them has to be a multiple of $3$, so only four of the odd numbers can be prime.
Comment: I have shown the run including the first $M$ primes is optimal up to five.  I suspect it is always true but do not see how to cover all the cases together.  It looks to me like the argument for five will generalize.
Comment: @ErickWong:thanks.  That is quite interesting.  I found the relevant section in Prime Numbers: A Computational Perspective by Richard Crandall, Carl B. Pomerance
Comment: But I am not looking for consecutive primes. Perhaps my initial phrasing of the problem is not as clear as it ought to be. Given $N$ (say $\gt 10^{4}$) and $M$ say equal to $50$, just to have an order of magnitude, can we have $N$ consecutive numbers of which $M$ (obviously not consecutive) that are primes? The two sets need not have any common element.
Comment: Ok, so this establishes a lower bound for $N$ and thank you for this input. What I am looking for essentially is this generalization but I have no idea how to find an argument. Intuitively-for what that is worth-it seems to hold.
Comment: @RossMillikan The initial segment of primes is *not* optimal (at least assuming prime $k$-tuples conjecture: explicitly we can find denser configurations that should be prime infinitely often, it's just impractical to locate such a tuple of actual primes).  This is a pretty famous result of Hensley and Richards from the 1970s.
Comment: Slight notation error: $\pi(M)$ should be $p_M$.


How do I actually get a field value using field_view_value()?

Question: I simply want to get the value of a field and have been told I should use field_view_value.
To this affect I have created:
$field_text_items = field_get_items('node', $node_context->data, 'field_text');

$field_text_items_value = field_view_value('node', $node_context->data, 'field_text', $field_text_items[0]['value']);

But running dpm($field_text_items_value); just returns an array with:
#markup (String, 1 characters ) h
#access (Boolean) TRUE

I'm assuming, because my field's value begins with a 'h', the #markup is only returning the first character for some reason.
Running dpm($field_fcc_text_items[0]['value']); returns the correct result so I know thing field is fine.
I've looked at the documentation linked above, but to be honest a lot of it doesnt make sense.
Would anyone be able to point me in the right direction here?
Thanks
As a side question, why is field_view_value() preferable to just using something like $field_text_items[0]['value'] anyway?
Answer: You may have the field_view_value parameters wrong. Instead of the entity_type-> delta try loading the field first using field_get_items. Use the return value as the second parameter in field_get_items.
$node = node_load($nid);
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

I took that answer from the blog: https://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way


save array of object in file in python

Question: I want to save array of my object in file in python and I test pickle, numpy,..but it doesn't work.
my class that I want to save instance of it in file is:
class pesrson():
def __init__(self,name,centralwidget):
    self.name=name
    self.centralwidget=centralwidget
def config(self):
    self.frame_eployee = QFrame(self.centralwidget)
    self.frame_eployee.setObjectName(u"frame_eployee")
    self.frame_eployee.setGeometry(QRect(20, 590, 321, 51))
    self.frame_eployee.setStyleSheet(u"color:rgb(85, 170, 255)")
    self.frame_eployee.setFrameShape(QFrame.StyledPanel)
    self.frame_eployee.setFrameShadow(QFrame.Raised)
    self.label_fix_logo_user = QLabel(self.frame_eployee)
    self.label_fix_logo_user.setObjectName(u"label_fix_logo_user")
    self.label_fix_logo_user.setGeometry(QRect(10, 0, 41, 41))
    self.label_fix_logo_user.setPixmap(QPixmap(u"D:/V2.0.0/Programme/qt/UI design/picture/user.svg"))
    self.label_name_employee = QLabel(self.frame_eployee)
    self.label_name_employee.setObjectName(u"label_name_employee")
    self.label_name_employee.setGeometry(QRect(60, 10, 101, 21))
    self.label_name_employee.setStyleSheet(u"color: rgb(255, 255, 255);\n"
                                           "font: 25 10pt \"Segoe UI Light\";")
    self.label_tim_login = QLabel(self.frame_eployee)
    self.label_tim_login.setObjectName(u"label_tim_login")
    self.label_tim_login.setGeometry(QRect(190, 10, 61, 21))
    self.label_tim_login.setStyleSheet(u"color: rgb(255, 255, 255);\n"
                                       "font: 25 10pt \"Segoe UI Light\";")
    self.label_time_logOut = QLabel(self.frame_eployee)
    self.label_time_logOut.setObjectName(u"label_time_logOut")
    self.label_time_logOut.setGeometry(QRect(250, 10, 61, 21))
    self.label_time_logOut.setStyleSheet(u"color: rgb(255, 255, 255);\n"
                                         "font: 25 10pt \"Segoe UI Light\";")
    self.label_name_employee.setText(QCoreApplication.translate("MainWindow", self.name, None))
    self.label_tim_login.setText(
        QCoreApplication.translate("MainWindow", u"
08:34
",
                                   None))
    self.label_time_logOut.setText(
        QCoreApplication.translate("MainWindow", u"
08:34
",
                                   None))
    return self.frame_eployee

I create this object with this code:
 p=pesrson("faezeh",self.ui.centralwidget)
    self.ui.verticalLayout.addWidget(p.config())
    self.tree.append(p)

now I want to save this array then read them and can use all attributes.
this error is when I use json :
TypeError: Object of type person is not JSON serializable
<employee.pesrson object at 0x000001DD17C7B7F0>

this error when I use pickle:
Possibly unsupported): cannot pickle 'PySide2.QtWidgets.QFrame' object

Answer: you could use the pickle module in the standard library and also you could use a database instead of a file. I think it would fit your problem.
Comment: thanks for your response. I use SQLite DB then my problem was solved

save array of object in file in python


Problemas ao preencher campos no PDF em asp.net MVC

Question: Estou com problemas ao renderizar alguns campos da minha tabela no arquivo PDF. Estava funcionando direitinho, mas não sei o que aconteceu que esses campos não estão mais renderizando. Na minha tela Meus Cursos, o aluno tem um botão que ele emite uma Declaração de Conclusão de Curso, mas quando o aluno clica no botão e gera o PDF os campos vem sem dados.
Obs.: Os dados que devem renderizar no PDF são: Nome do Aluno, Matricula, Nome do Curso, Período e Carga Horária.

View PDF
@model MeuProjeto.Models.AlunoCurso
@{
    Layout = null;
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <link href="~/Content/PDF.css" rel="stylesheet" type="text/css" />
    <title>GeraPDF</title>

        Declaração de Conclusão de Curso

<text style="font-family: 'Times New Roman'; font-size: 20px">
    Declaramos que o Sr(a). @Html.DisplayFor(model => model.Aluno.Nome), matrícula de Nº @Html.DisplayFor(model => model.Aluno.Matricula),
    inscrito no curso de @Html.DisplayFor(model => model.Curso.Nome_Curso), na XXXXX,
    no período de @Html.DisplayFor(model => model.Curso.Dt_Inicio) a @Html.DisplayFor(model => model.Curso.Dt_Fim),
    cumprindo uma carga horária de @Html.DisplayFor(model => model.Curso.Carga_Horaria), com total comprometimento e dedicação todos os requisitos para a conclusão deste curso,
    estamos encaminhando esta via de Declaração para que seja emitido junta a XXXXXX, o
    Certificado de conclusão de Curso.
</text>

    _________________________ em ___/___/_____

    Assinatura do Responsável

Action PDF
public ActionResult GerarPDF(int id)
    {
        var alunoCurso = db.AlunoCursos.FirstOrDefault(ac => ac.Aluno.Usuario == User.Identity.Name);
        if (alunoCurso != null)
        {
            AlunoCurso aluno =
                db.AlunoCursos.Include(a => a.Aluno).AsNoTracking().FirstOrDefault(al => al.AlunoId == id);

            var pdf = new ViewAsPdf
            {
                ViewName = "GeraPDF",
                FileName = "Declaração.pdf",
                Model = aluno,
                PageSize = Size.A4,
                PageMargins = new Margins {Bottom = 2, Left = 2, Right = 2, Top = 2}
            };

            return pdf;
        }

        return View();
    }

Trecho da minha View com o botão que Chama o PDF
@model IEnumerable<MeuProjeto.Models.AlunoCurso>

 @if (item.Aprovado == false)
  {
   <input type="submit" value="Pendente de Aprovação" name="meusCursos" class="cursos btn btn-primary btn-sm" disabled="disabled" data-id="@item.Id" />
  }
  else
  {

  }

@section Scripts {
            @Scripts.Render("~/bundles/jqueryval")

Comment: Já tentou colocar *breakpoints* na *View* pra verificar o estado das variáveis de *Model*?
Comment: Coloquei @CiganoMorrisonMendez, não tá trazendo nada. O engraçado é que estava funcionando, e agora não sei o que houve. Pode me ajudar?
Answer: Não tenho certeza se é isso, mas não use @Html.DisplayFor() com o Rotativa. O Rotativa é um pacote esquisito e cheio de problemas. Troque pela menção direta da variável, conforme abaixo:
<text style="font-family: 'Times New Roman'; font-size: 20px">
    Declaramos que o Sr(a). @Model.Aluno.Nome, matrícula de Nº @Model.Aluno.Matricula,
    inscrito no curso de @Model.Curso.Nome_Curso, na XXXXX,
    no período de @Model.Curso.Dt_Inicio a @Model.Curso.Dt_Fim,
    cumprindo uma carga horária de @Model.Curso.Carga_Horaria, com total comprometimento e dedicação todos os requisitos para a conclusão deste curso,
    estamos encaminhando esta via de Declaração para que seja emitido junta a XXXXXX, o
    Certificado de conclusão de Curso.
</text>

EDIT
Acho que você está usando a chave errada pra selecionar. Modifique o código abaixo:
AlunoCurso aluno =
            db.AlunoCursos.Include(a => a.Aluno).AsNoTracking().FirstOrDefault(al => al.AlunoId == id);

Para:
var alunoCurso =
            db.AlunoCursos.Include(a => a.Aluno).FirstOrDefault(ac => ac.AlunoCursoId == id);

Comment: Eu acho que o problema é aqui `AlunoCurso aluno = db.AlunoCursos.Include(a => a.Aluno).AsNoTracking().FirstOrDefault(al => al.AlunoId == id);` por que o **aluno** tá vindo `null`. Mas não consegui arrumar.
Comment: @Novato Por favor, poderia escrever uma resposta, esclarecendo como foi feito, pelo benefício da comunidade?
Comment: Ainda não consegui arrumar o erro @CiganoMorrisonMendez, só descobri ao `debugar` que o **aluno** desse trecho de código `AlunoCurso aluno = db.AlunoCursos.Include(a => a.Aluno).AsNoTracking().FirstOrDefault(al => al.AlunoId == id);` está vindo **nulo**, mas ainda não sei o porque.
Comment: @Novato Atualizei a resposta. Veja se te atende.
Comment: Não dei certo @CiganoMorrisonMendez, porque a declaração deve ser emitida pelo usuário que está logado, igual eu fiz aqui `var alunoCurso = db.AlunoCursos.FirstOrDefault(ac => ac.Aluno.Usuario == User.Identity.Name);
        if (alunoCurso != null)`. Ai dentro do `if` ele não aceitou esse seu trecho.
Comment: Como assim, "não aceitou esse seu trecho"? Seja mais claro. Não responda com "não deu certo". Diga exatamente o que aconteceu, com a mensagem de erro. Eu não vejo sua tela. Ler "não deu certo" não vai fazer eu te ajudar com qualidade.
Comment: Continua vindo `nulo` @CiganoMorrisonMendez.
Answer: Conseguir resolver da seguinte forma: Na minha Action não alterei nada
public ActionResult GerarPDF(int id)
    {
        //Aqui eu pego o usuário logado
        var alunoCurso = db.AlunoCursos.FirstOrDefault(ac => ac.Aluno.Usuario == User.Identity.Name);
        if (alunoCurso != null)
        {
            //Aqui eu faço o include do aluno e pego o AlunoID
            AlunoCurso aluno =
                db.AlunoCursos.Include(a => a.Aluno).AsNoTracking().FirstOrDefault(al => al.AlunoId == id);

            var pdf = new ViewAsPdf
            {
                ViewName = "GeraPDF",
                FileName = "Declaração.pdf",
                Model = aluno,
                PageSize = Size.A4,
                PageMargins = new Margins {Bottom = 2, Left = 2, Right = 2, Top = 2}
            };

            return pdf;
        }

        return View();
    }

Aqui o código do botão que chama a Action PDF

   @if (item.Aprovado == false)
    {
      <input type="submit" value="Pendente de Aprovação" name="meusCursos" class="cursos btn btn-primary btn-sm" disabled="disabled" data-id="@item.Id" />
              }
              else
              {

               Emitir Declaração
              }

A alteração deve ser feita no @item.Id, como precisava pegar o ID do aluno o correto é passar o AlunoId.

     @if (item.Aprovado == false)
     {
      <input type="submit" value="Pendente de Aprovação" name="meusCursos" class="cursos btn btn-primary btn-sm" disabled="disabled" data-id="@item.Id" />
              }
              else
              {

               Emitir Declaração
              }

Desta forma os campos no PDF serão preenchidos.


font awesome in android list view not working

Question: So I have created this custom array adapter:
        View row = convertView;
        ViewHolder holder;
        iconFont = Typeface.createFromAsset(activity.getAssets(), "fontawesome-webfont.ttf" );

        if (row == null)
        {
            LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.event_type_list_row, null);
            holder = new ViewHolder();
            holder.icon = (TextView) row.findViewById(R.id.EventTypeListRow_icon_EditText);
            holder.name = (TextView) row.findViewById(R.id.EventTypeListRow_name_EditText);
            row.setTag(holder);
        }
        else
        {
            holder = (ViewHolder) row.getTag();
        }
        final EventTypeDataObj eventType = data.get(position);
        if (eventType != null)
        {
            //holder.icon.setText(eventType.getIconCode()); f02c;
            holder.icon.setText("");
            holder.icon.setTypeface(iconFont);
            holder.name.setText("");
            holder.name.setTypeface(iconFont);
        }

        return row;

I don't see the I cons, I see the code in the list view like here:

Note: other fonts (which works on letters not icons). are working.
Is there amy reason it is not working?
Comment: or shouldn't your string be `"\uf001"`?
Comment: use HTML.fromHtml or somthing?
Comment: can you give an example?
Answer: 

is apparently an XML entity. I have no reason to believe android should treat the as such, and not as a plain string of characters. Which apparently it does, given your screenshot.
If you want to specify characters by giving their unicode value, the correct usage in java is \u, like so :
holder.name.setText("\uf001");

Edit
It is also possible, if your input is "&#f001;" and cannot be replaced by "\uf001" to use Html.fromHtml to decode the XML entities in the String:
holder.name.setText(Html.fromHtml("&#f001;"));

Comment: a priori, `setText(Html.fromHtml("&#f001;"));` could work, although I haven't tested it.
Comment: I have `` and when I do this `holder.icon.setText(activity.getResources().getString(R.string.list_icon));` it is working great! Maybe I need to format the string to utf-8
Comment: yes, because string.xml is an xml file, and xml parsing parses the xml entities, which textView does not.
Comment: utf-8 has nothing to do with this, these are unicode values, utf-8 is a representation.
Comment: Simply use the java `\u` notation like the example I posted when using these characters in Java code.
Comment: do you think this will work? `URLEncoder.encode(str, "UTF-8");`
Answer: Place the font-awesome strings in your strings.xml and reference them using getString(R.string.whatever). Android will then handle the Unicode formatting for you.
Comment: I is working like this when I add the strings manually in static views which are not listview rows, but I am getting this icon codes from database...


Minimum value of $|z+1|+|z-1|+|z-i|$

Question: How to find the minimum value of $|z+1|+|z-1|+|z-i|$.
I have tried geometrically etc but failed.
Comment: See http://en.wikipedia.org/wiki/Geometric_median. It's the geometric median of the points $1$, $-1$ and $i$. According to the page, it is unique, so since the points form an isoceles triangle, $z$ must lie on the imaginary axis. Use calculus to figure out where...?
Comment: See also http://en.wikipedia.org/wiki/Fermat_point
Comment: This is quite interesting comment ! Thank you.
Answer: this is called Fermat(?) problem. the minimum occur at a point where every vertex make $120^\circ.$ this is true for any three vertices of a triangle. here we have nicer isosceles triangle of sides $\sqrt 2, \sqrt 2$ and $2.$  the Fermat point is at $\sqrt 3/3.$ the sum of segments is $$2\sqrt 3 /3 + 2\sqrt 3 /3 + 1 - \sqrt 3/3  = 1 + \sqrt 3$$
here is a quick of the proof why Fermat point is where the minimum occurs.
Given three non collinear points $A, B, C$ the $$min_{P}\left(|AP| + |BP| + |CP|\right) = |AF|+|BF|+|CF| \mbox{ where } F \mbox{ is such that} \angle AFB = \angle BFC = 120^\circ $$
the proof uses the Ptolemy's theorem that says that in any quadrilateral, the sum of the products of the opposite sides is greater or equal to the product of the diagonals. the equality occurs if and only if the quadrilateral is cyclic.
Proof: Construct exterior equilateral triangles $ABC^\prime, BCA^\prime$ and $CAB^\prime.$ Let the circumcircles of the equilateral triangles meet at the Fermat point $F.$ Let $G$ be any point other than $F.$ Applying Ptolemy's theorem to the cyclic quadrilateral $AFBC^\prime$ and the quadrilateral $AGBC^\prime$ we get $$AF + BF = C^\prime F \mbox{ and } AG + BG \ge C^\prime F$$
adding two similar equations proves the claim.
Comment: I am always fascinated by geometric proofs (in particular because I am so ignorant). Excluding calculus based approaches, the answers to this post are beautiful. I thank you for your contribution. Cheers :-)
Comment: You could consider adding your proof to http://en.wikipedia.org/wiki/Fermat_point :)
Answer: Given that it was some sort of quiz, you can guess that:

It is on the imaginary axis (because the triangle formed by $1,-1,i$ is isoceles, and see uniqueness of Geometric median on Wikipedia).
The point lies inside the isoceles triangle.

Let $f(y)=2\sqrt{1+y^2}+1-y$.
$f'(y)=\frac{2y}{\sqrt{1+y^2}}-1=0\implies4y^2=1+y^2\implies y=\frac{1}{\sqrt3}$.
Comment: Good, simple and elegant ! $+1$
Comment: @ClaudeLeibovici, simple, elegant; true. but... uses calculus when you can use geometry.
Answer: The post has received good and simple answers based on triangles.
However, if you really want to see the calculus based problem, let me start using Dr. Sonnhard Graubner's approach to the solution. Writing $$f(a,b)=\sqrt{(a+1)^2+b^2}+\sqrt{(a-1)^2+b^2}+\sqrt{a^2+(b-1)^2}$$ Computing the partial derivatives lead to the equations $$\frac{df(a,b)}{da}=\frac{a}{\sqrt{a^2+(b-1)^2}}+\frac{a-1}{\sqrt{(a-1)^2+b^2}}+\frac{a+1}{\sqrt{(a+1)^2+
   b^2}}=0$$ $$\frac{df(a,b)}{db}=\frac{b-1}{\sqrt{a^2+(b-1)^2}}+\frac{b}{\sqrt{(a-1)^2+b^2}}+\frac{b}{\sqrt{(a+1)^2+b^
   2}}=0$$ which are extremely complex to solve except if you know (or are able to identify) that one solution corresponds to $a=0$. In such a case, the first partial is effectively equal to $0$ and the second one becomes $$\frac{df(0,b)}{db}=\frac{2 b}{\sqrt{b^2+1}}+\frac{b-1}{\sqrt{(b-1)^2}}=\frac{2 b}{\sqrt{b^2+1}}\pm 1=0$$ for which the solutions are $\mp \frac{1}{\sqrt{3}}$. To these solutions correspond $$f(0,-\frac{1}{\sqrt{3}})=1+\frac{5}{\sqrt{3}}$$ $$f(0,\frac{1}{\sqrt{3}})=1+\sqrt{3}$$ and then the result ($a=0,b=\frac{1}{\sqrt{3}},f=1+\sqrt{3}$).
You can notice that, for $b=\pm \frac{1}{\sqrt{3}}$, $$\frac{d^2f(0,b)}{db^2}=\frac{3 \sqrt{3}}{4} \gt 0$$
Please, notice that the problem with $|z+\alpha|+|z+\beta|+|z-i|$ will be extremely difficult to solve as soon as $\alpha+\beta \neq 0$.
Answer: let $z=a+bi$ then we have$$f(a,b)=\sqrt{(a+1)^2+b^2}+\sqrt{(a-1)^2+b^2}+\sqrt{a^2+(b-1)^2}$$ with the help of calculus we get
$$f(a,b)\geq 1+\sqrt{3}$$ the equal sign holds if $a=0$ and $b=\frac{\sqrt{3}}{3}$
Comment: I did the same but it turned out to be a nightmare ? If you used a CAS, could you provide the syntax you used ? Thanks.
Comment: You solved it, therefore the calculations were not lengthy? That is not logical.
Comment: I agree with the OP. You give an answer but could you describe the calculations, please ?
Comment: Did u use critical points etc? Maxima minima!
Comment: yes with the help of calculus
Comment: But calculations very lengthy right?
Comment: hm why? i solved it
Comment: Why is [WolframAlpha][1] not able to solve it?

  [1]: http://www.wolframalpha.com/input/?i=minimize%20f%28a%2Cb%29%3D%5Csqrt%7B%28a%2B1%29%5E2%2Bb%5E2%7D%2B%5Csqrt%7B%28a-1%29%5E2%2Bb%5E2%7D%2B%5Csqrt%7Ba%5E2%2B%28b-1%29%5E2%7D
Comment: i differentated the function $f(a,b)$ with respect to $a$ and $b$

Minimum value of $|z+1|+|z-1|+|z-i|$


Potential leak on a retain

Question: I'm developing an iPhone application. I have the following method:
- (void)generateTokenWithUserId: (NSString *)uniqueId {

    NSLog(@"TokenGenerator - generateTokenWithUserId: '%@'", uniqueId);

    NSString *myMD5String = [Utilities returnMD5Hash:uniqueId];

    // Create the request.
    NSMutableString *authURL = [[NSMutableString alloc] initWithString:CLOUDMADE_AUTH];
    [authURL appendString: localApiKey];
    [authURL appendString: USER_ID];
    [authURL appendString: myMD5String];

    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:authURL]
                                                            cachePolicy: NSURLRequestUseProtocolCachePolicy
                                                        timeoutInterval: 60.0];
    [theRequest setHTTPMethod: @"POST"];

    NSLog(@"TokenGenerator URL - '%@'", authURL);

    // create the connection with the request
    // and start loading the data
    //NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if (connection) {
        // Create the NSMutableData to hold the received data.
        // receivedData is an instance variable declared elsewhere.
        responseData = [[NSMutableData data] retain];
    } else {
        // Inform the user that the connection failed.
    }

    [authURL release];
}

I'm getting a: potential leak on an object allocated on line 52 and stored into 'connection'.
Dealloc method for this class is:
- (void) dealloc {

    NSLog(@"TokenGenerator - dealloc");

    [responseData release];
    [localApiKey release];

    [super dealloc];
}

And interface declaration is:
@class TokenGenerator;

@protocol TokenGeneratorDelegate <NSObject>

- (void)tokenGeneratorDidFinishGeneration:(TokenGenerator *)tokenGenerator token:(NSString *)tokenGenerated;

@end

@interface TokenGenerator : NSObject {

    NSString *localApiKey;
    id<TokenGeneratorDelegate> delegate;
    NSMutableData *responseData;
}

@property (nonatomic, assign) id<TokenGeneratorDelegate>delegate;

- (id) initWithApikey:(NSString*) apiKey delegate:(id)anObject;
- (void)generateTokenWithUserId: (NSString *)uniqueId;

@end

How can I fix this problem? May I create a copy to that object, and then assign it to responseData?
Answer:  NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

Where is [connection release]; ?
Put this line after [authURL release]; for example.
Answer: Your code starts an asynchronous request, but you try to access the returned data and then intend to release the connection immediately.  You need to implement the delegate methods, which you presumably have in order to be able to read the returned data, and release the connection in the finished and failed delegate methods.  The code you have will work with fast network connections (possibly), but will fail in the real world.
Comment: See the delegate section of the NSURLConnection documentation, and also the SimpleURLConnections or LazyTableImages sample code linked in the documentation.
Comment: Thank you for your answer. Could you share with me an example about doing this? I'm very new in Objective-C programming (as you can see), and I don't know how to do that.

Potential leak on a retain


Weird issue with rails link_to button

Question: I have a rails link I'm trying to add into a dropdown and it is acting weird and I can't figure out why.
I have pasted the code block below:
<%= link_to edit_profile_post_path(article.profile, article.post), :class => "dropdown-item" if article.post.present? do %>

    Edit Post

<% end %>

When I preview the dropdown I see the link path instead of the words "Edit Post":

Buts what stumps me even more is that when I hover over the link, it is actually:
http://localhost:3000/profiles/gerard-donnelly?class=dropdown-item
The original code that works fine is:
<%= link_to 'Edit Post', edit_profile_post_path(article.profile, article.post), class: 'dropdown-item' if article.post.present? %>

Would really appreciate any help on fixing this.
Answer: You are putting the condition on the wrong side of the call. If it was pure ruby, this would look like
link_to(path, class: 'klass') if article.post.present? do
  'content'
end

The do/end block is passed to the present? method, which is not what you want. Instead:
link_to(path, class: 'klass') do
  'content'
end if article.post.present?

will work. Translating back to ERB:
<%= link_to edit_profile_post_path(article.profile, article.post), :class => "dropdown-item" do %>

    Edit Post

<% end if article.post.present? %>

Comment: Thanks so much for this method. It worked perfectly. I had solved it a few minutes ago by removing the the if statement and wrapping the entire link to in a separate if block. This way is a lot cleaner. Cheers

Weird issue with rails link_to button


A subgroup $B$ of an finitely generated group $A$ such that $|A/B| = n$

Question: Let $A$ be a finitely generated, infinite abelian group, and $n$ a positive integer.  Show there exists a subgroup $B$ such that $|A/B| = n$.
I'm trying to use induction on the number of generators of $A$, but I don't know if this is a good approach.  Any hints are greatly appreciated.
Comment: @Conifold This is for an arbitrary group $A$, not just an example of a group.
Answer: Hint: The $k = 1$ case is when $A \cong \mathbb{Z}$. Can you describe the desired subgroup $B$ in this case? Can you modify your argument for the $k$ generator case?
Comment: The subgroup $B$ is certainly $n\mathbb Z$, but for a general $A = gen(a_1, a_2, \ldots, a_k)$, I don't think $B = gen(na_1, na_2, \ldots, na_k)$ would work, right?  Unless I'm missing something.
Comment: @gravitybeatle: That wouldn't work; it would give you $(\mathbb{Z}/n\mathbb{Z})^k$. But you are close...
Comment: I've changed the $n$ to a $k$ here, as $n$ has a different meaning in the question.
Answer: By the fundamental theorem of finite abelian groups, $A$ is isomorphic to a group $\mathbb{Z}\times A'$, where $A'$ is some abelian group. Hence, $A$ surjects onto $\mathbb{Z}$. As $\mathbb{Z}$ surjects onto $\mathbb{Z}_n$, the cyclic group of order $n$, it follows that $A$ also surjects onto $\mathbb{Z}_n$. The result then follows by the first isomorphism theorem.
You can actually find the subgroup $B$ if you want, although the question doesn't ask for this: Using the integers in the obvious way to denote the elements of the $\mathbb{Z}$ factor in $\mathbb{Z}\times A'$, so $A=\langle 1, A\rangle$, then $B=\langle n, A'\rangle$.

[The last paragraph is potentially ambiguous as there may be lots of $\mathbb{Z}$-factors of $A$. I wrote it like this because I wanted to use additive notation. Multiplicatively, and unambiguously, let $z$ be the generator of the $\mathbb{Z}$-factor in $\mathbb{Z}\times A'$, so $A=\langle z, A\rangle$, and then $B=\langle z^n, A'\rangle$.]


Loop Index Is Being Ignored in R?

Question: I have this dataset in R:
set.seed(123)

myFun <- function(n = 5000) {
  a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
  paste0(a, sprintf("%04d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}

col1 = myFun(100)
col2 = myFun(100)
col3 = myFun(100)
col4 = myFun(100)
group <- c("A","B","C","D")
group = sample(group, 100, replace=TRUE)

example = data.frame(col1, col2, col3, col4, group)

       col1       col2       col3       col4 group
1 SKZDZ9876D BTAMF8110T LIBFV6882H ZFIPL4295E     A
2 NXJRX7189Y AIZGY5809C HSMIH4556D YJGJP8022H     C
3 XPTZB2035P EEKXK0873A PCPNW1021S NMROS4134O     A
4 LJMCM3436S KGADK2847O SRMUI5723N RDIXI7301N     B
5 ADITC6567L HUOCT5660P AQCNE3753K FUMGY1428B     D
6 BAEDP8491P IAGQG4816B TXXQH6337M SDACH5752D     C

I am now trying to run the following double loop:
library(stringdist)
method = c("osa", "lv", "dl", "hamming", "lcs", "qgram", "cosine", "jaccard", "jw","soundex")

results = list()

l = length(unique(example$group))

 for (j in 1:l) {
for (i in 1:length(method)) {

        g = unique(example$group)

        groups_j = g[j]

        my_data_i = example[which(example$group == groups_j  ), ]

        method_i = method[i]
        name_1_i = paste0("col1_col_2", method_i)
        name_2_i = paste0("col3_col_4", method_i)

        p1_i = stringdistmatrix(my_data_i$col1, my_data_i$col2, method =  method_i, useNames = "string") %>%
            as_tibble(rownames = "a") %>%
            pivot_longer(-1, names_to = "b", values_to = name_1_i)

        p2_i = stringdistmatrix(my_data_i$col3, my_data_i$col4, method =  method_i, useNames = "string") %>%
            as_tibble(rownames = "a") %>%
            pivot_longer(-1, names_to = "b", values_to = name_2_i)

        p1_i = p1_i[,3]
        p2_i = p2_i[,3]

        final_i = cbind(p1_i, p2_i, groups_j)
        results[[i]] = final_i

    }

}

final = do.call(cbind.data.frame, results)

The loop seems to run - but when I inspect the final results, I noticed that the other indices in the "j" loop seem to have been ignored:
> table(final$groups_j)

  A
441

As we can see the original data, there appears to be 4 groups:
> table(example$group)

 A  B  C  D
21 28 19 32

Can someone please help me figure out why the other 3 groups are not being processed by my loop?
Thank you!
Comment: `my_data_i` does not become `my_data_1`, `my_data_2`, etc and the same goes for the others, `groups_j` on index `j` and `method_i`, `name_1_i` and `name_2_i` on index `i`. You are repeatedly creating data sets `groups_j` and `*_i`.
Comment: @ Rui: thank you for this suggestion! If you have time, can you please help me fix this? Thank you so much!
Answer: This is not supposed to be a proper answer. I was just playing around with your code a bit. Nevertheless, it might help you debug it.
library(stringdist)
library(tidyverse)

results = list()
res_j <- list()

l = length(unique(example$group))
g = unique(example$group)

for (j in 1:l) {

  groups_j = g[j]

  for (i in 1:length(method)) {

    my_data_i = example[which(example$group == groups_j  ), ]

    method_i = method[i]
    name_1_i = paste0("col1_col_2", method_i)
    name_2_i = paste0("col3_col_4", method_i)

    p1_i = stringdistmatrix(my_data_i$col1, my_data_i$col2, method =  method_i, useNames = "string") %>%
      as_tibble(rownames = "a") %>%
      pivot_longer(-1, names_to = "b", values_to = name_1_i)

    p2_i = stringdistmatrix(my_data_i$col3, my_data_i$col4, method =  method_i, useNames = "string") %>%
      as_tibble(rownames = "a") %>%
      pivot_longer(-1, names_to = "b", values_to = name_2_i)

    p1_i = p1_i[,3]
    p2_i = p2_i[,3]

    final_i = cbind(p1_i, p2_i)
    results[[i]] = final_i

  }
  res_j[[j]] <- flatten(results)
  res_j[[j]]$group <- groups_j
}

test <- map_dfr(res_j, as.tibble)

# here's a summary table of the result set.
library(gtExtras)
gt_plt_summary(test)

Answer: Here is a way.
Instead of unique(example$group) and looping through the data set using this values, split by group and lapply the inner for loop to the sub-data sets.
set.seed(123)

myFun <- function(n = 5000) {
  a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
  paste0(a, sprintf("%04d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}

col1 = myFun(100)
col2 = myFun(100)
col3 = myFun(100)
col4 = myFun(100)
group <- c("A","B","C","D")
group = sample(group, 100, replace=TRUE)

example = data.frame(col1, col2, col3, col4, group)
head(example)
#>         col1       col2       col3       col4 group
#> 1 OOPBR0319H XFNIX1029D UFTLD7446Q LLRTH2385Q     C
#> 2 SUWML2894Y JWGSU4238I HRGIF0793H MTHSV3221Z     B
#> 3 NEAXO7570I OQWCR4065E EQVSJ7607Y PTIGN4766W     D
#> 4 CHHQS1666T ONOBS9571P EMLSS6601V JEFZH0164K     D
#> 5 JSHCU8312A TGWWI3712K SLKFF4079K EXKGJ1406W     A
#> 6 RJJRF2760C LMWLS5552P LORMI7587V OYPGF5046D     C

suppressPackageStartupMessages({
  library(stringdist)
  library(magrittr)
  library(tidyr)
})

method = c("osa", "lv", "dl", "hamming", "lcs", "qgram", "cosine", "jaccard", "jw","soundex")

ex_split <- split(example, example$group)
temp <- vector("list", length = length(method))

results <- lapply(ex_split, \(x) {
  group <- x$group[1]
  for (i in seq_along(method)) {
    name_1 <- paste0("col1_col_2_", method[i])
    name_2 <- paste0("col3_col_4_", method[i])

    p1 <- stringdistmatrix(x$col1, x$col2, method = method[i], useNames = "string") %>%
      as_tibble(rownames = "a") %>%
      pivot_longer(-1, names_to = "b", values_to = name_1)

    p2 <- stringdistmatrix(x$col3, x$col4, method = method[i], useNames = "string") %>%
      as_tibble(rownames = "a") %>%
      pivot_longer(-1, names_to = "b", values_to = name_2)

    temp[[i]] <- cbind(p1[3], p2[3])
  }
  y <- do.call(cbind.data.frame, temp)
  y$group <- group
  y
})

final <- do.call(rbind.data.frame, results)
row.names(final) <- NULL
str(final)
#> 'data.frame':    2610 obs. of  21 variables:
#>  $ col1_col_2_osa    : num  8 10 10 9 10 7 9 9 9 10 ...
#>  $ col3_col_4_osa    : num  8 9 9 10 10 9 10 10 9 8 ...
#>  $ col1_col_2_lv     : num  8 10 10 9 10 7 9 9 9 10 ...
#>  $ col3_col_4_lv     : num  8 9 9 10 10 9 10 10 9 9 ...
#>  $ col1_col_2_dl     : num  8 10 10 9 10 7 9 9 9 10 ...
#>  $ col3_col_4_dl     : num  8 9 9 10 10 9 10 10 9 8 ...
#>  $ col1_col_2_hamming: num  8 10 10 9 10 9 9 9 9 10 ...
#>  $ col3_col_4_hamming: num  9 9 9 10 10 9 10 10 9 9 ...
#>  $ col1_col_2_lcs    : num  14 18 16 18 18 12 16 16 14 18 ...
#>  $ col3_col_4_lcs    : num  14 18 16 16 18 14 16 18 18 16 ...
#>  $ col1_col_2_qgram  : num  14 18 16 14 18 12 16 14 14 16 ...
#>  $ col3_col_4_qgram  : num  14 18 16 16 18 12 16 18 18 14 ...
#>  $ col1_col_2_cosine : num  0.726 0.817 0.8 0.763 0.915 ...
#>  $ col3_col_4_cosine : num  0.662 0.923 0.831 0.746 0.923 ...
#>  $ col1_col_2_jaccard: num  0.812 0.944 0.889 0.8 0.941 ...
#>  $ col3_col_4_jaccard: num  0.8 0.938 0.875 0.875 0.938 ...
#>  $ col1_col_2_jw     : num  0.467 0.6 0.533 0.578 0.6 ...
#>  $ col3_col_4_jw     : num  0.467 0.6 0.533 0.533 0.6 ...
#>  $ col1_col_2_soundex: num  1 1 1 1 1 1 1 1 1 1 ...
#>  $ col3_col_4_soundex: num  1 1 1 1 1 1 1 1 1 1 ...
#>  $ group             : chr  "A" "A" "A" "A" ...

Created on 2022-11-27 with reprex v2.0.2

Loop Index Is Being Ignored in R?


After disabling folder redirection My Documents still redirected

Question: like title says.  I disabled my folder redirection after it became too much of a hassle.  I had been experiencing reorganization of my start menu, links intermittently disabled and then reappearing, and long logon times so I disabled redirected folders.  The start menu and desktop both worked fine and are showing that they are local but when I open My Documents from the start menu it still goes to the redirected folder's copy.  I have restarted twice since then and checked the server and enabled and disabled folder redirection again to to ensure that it enforces that its disabled.  Any ideas what I can do or why this is happening?
Answer: The folder redirection GPO settings include an option to remove the redirection or not when the group policy setting no longer applies. By default, this setting is set to leave the redirection in place after the GPO is removed.  So that's probably what happened here.  You removed the GPO, but it was set to keep the redirection in place anyway.
You'll need to go back to your folder redirection GPO and set it redirect back to you local user profile location, instead of just setting folder redirection back to Not Configured.  See Image below.
Comment: Thank you, that saved my day! Same problem 8 years later.


Explanation of Joint Probability and Independence

Question:
Can anyone explain further to me the solution for the second instance where $f(x,y) = 24xy$. Specifically, I don't really understand the part "because the region in which the joint density is nonzero cannot be expressed in the form $x ∈ A, y ∈ B$".
I don't really understand how illustration with $I(x,y)$ are doing in terms of proving dependency between the variables?
Answer: Informally, independence mean that knowing the value of one random variable gives you no extra information about the other
But if $0 \lt X+Y \lt 1$, then knowing $X=\frac34$ tells you $Y < \frac14$.  Meanwhile  knowing $X=\frac13$ tells you $Y$ can take values up to $\frac23$.  So the value of $X$ is affecting the distribution of possible values of $Y$ and thus they are not independent.  The indicator function has this effect, because it cannot be seperated into an $X$ part and a $Y$ part
Comment: Whenever you pull two things a part, there is "a rate" at which they "separate".
Comment: @Acccumulation I understand that because 0 < x+y< 1 it will cause the value of each variable to affect each other leading to some correlation right? I just don't understand why the author used a function like I(x,y). Edit: If we don't have the condition 0 < x+y < 1 then will the variables become independent?
Comment: @user277416 In your first example you have $f(x,y)=6e^{-2x}e^{-3y}I(0 \lt x, 0 \lt y)$  This can be rewritten as $\left(2e^{-2x}I(0 \lt x) \right) \left(3e^{-3y}I(0 \lt y) \right)$ as the  $I(0 \lt x, 0 \lt y)$ can be separated into $I(0 \lt x)I(0 \lt y)$.  You cannot do this with your second example
Answer: The necessary (not sufficient) condition for independence is that $f(x,y)$ should be factored into something like $g(x)h(y)$. For that to happen, $I(x,y)$ should be factored like $I_A(x)I_B(y)$, but the author says that there is no way to do it, basically because of the line $0<x+y<1$.
Assume $I(x,y)=I_A(x)I_B(y)$, where $A=(0,1)$, $B=(0,1)$ (it's $(0,1)$ because there is density for $x,y$ everywhere in $(0,1)$). So, $I_A(x)$ and $I_B(y)$ should be non-zero, if for example $x=0.3,y=0.8$, but $I(x,y)$ is zero.
Comment: Right--but the question seeks an explanation of author's assertion rather than a restatement of it.  Can you show why "clearly" the indicator function does not factor?
Comment: right @whuber, I should've made it clearer
Comment: I think that it is sufficient. The issue is that the factoring fails, because the apparent factoring only holds given restrictions on the values.
Comment: So the problem is that x = 0.3 and y = 0.8 satisfy the condition of 0 < x < 1 and 0 <y < 1 but not 0 < x + y < 1 right? I thought that was the problem why these variables are not independent as the value of x will have some effect on the value of y. But I don't really get why the author used I (x,y) = 1. I see that I (x,y) will add a function where you can't separate x and y but I guess I don't understand the logic leading up to that approach, it's seem random to me and I don't see a link to the problem
Comment: @user277416 yes, that is the exact reason. I think the author chooses the harder way to explain a simple concept. The logic is probably being more algebraic rather than intuitive arguments.
Comment: @gunes so how is the I(x,y) relevant to this? I understand that it's will create a situation where you can't separate x and y but I don't see how I can do this when 0 < x+y < 1 and when we don't have that condition?
Comment: @user277416 Assume you don't have that condition, i.e. it's only $0<x<1$ and $0<y<1$, then: $$I(x,y)=I_A(x)I_B(y)$$ where $I_A(x)=1$ only when $0<x<1$ and $I_B(y)=1$ only when $0<y<1$.
Answer: A sufficient test for detecting non-independence of random variables is the eyeball test (described briefly in this answer of mine on stats.SE and in more detail in an answer on math.SE) which says that if the support of the joint density is not a rectangle with sides parallel to the coordinate axes, then the random variables are dependent. Here, the support of $f_{X,Y}(x,y)$ is a triangle and so we can assert that the random variables are dependent without the need for laboriously calculating $f_X(x)$ and $f_Y(y)$ and then checking whether $f_{X,Y}(x,y)$ equals the product $f_X(x)f_Y(y)$ for all real numbers $x$ and $y$ as the definition of independence says (or should say). That $f_{X,Y}(x,y)$ can be expressed as $g(x)h(y)$ for some real numbers $x$ and $y$ (as it does in this instance) is not enough to claim independence.
Comment: it can be a combination of rectangles as well:$$\mathcal{S}=[0,1]\cup[2,3]$$
Comment: @gunes Yes, of course, but I was trying to keep it as simple as possible.
Comment: i got downvoted or warned whenever i tried to keep it simple :)
Answer: I don't know if this makes it any easier to understand, but consider a function that's equal to $x^2y^3$ when $x<y$ and $0$ otherwise. Now consider the function $x^2y^3 (|y-x|+y-x)/(2y-2x)$. If you plot out the second function, you'll find that it's the same as the first function. It's in more complicated form, but it's in closed form rather than having a conditional definition.
While the first function appears to factor, the second one doesn't. If you want to factor out the $y^3$, you still have the $(|y-x|+y-x)/(2y-2x)$ to deal with.


Alternative way convert int ? to double?

Question: Is there any way to convert this ?
public int? intVal ;
public double? dblVal ;

How I am working now
if(dblVal==null)
    intVal =null;
else
    intVal = Convert.ToInt32(dblVal);

Any alternative way  ? Thanks in advance .
Comment: @T.S.: Why would you want to do that? It wouldn't even work without some effort, as you can't parse non-integer values with `int.Parse` (e.g. `int.Parse("5.5")` will throw an exception)
Comment: @IanP: That won't compile, because the compiler won't be able to figure out the type of the conditional expression. You'd need to cast either the second or third operand to `int?`, or use `default(int?)` or something similar.
Comment: If the behavior of Convert.ToInt32 is doing what you want, then this is an acceptable way. Alternatively you could inline everything like this: `intval = (dblVal == null) ? null : Convert.ToInt32(dblVal);`
Comment: You can go to string first and then parse int from string
Comment: @JonSkeet Correct. I don't say it is THE way, but as question implies, it is an "Alternative way..."
Comment: @T.S.: Well you *could* send it to a web service to do the conversion - but it wouldn't in any way be a *useful* way. I think the OP is really asking for *sensible* alternatives, and I don't view unnecessary string conversions as falling in that category.
Comment: @JonSkeet Web service would probably do one of those anyways, right? And while sending it, wouldn't you sometimes serialize values to strings (XML) and deserialize them back? There we go - to string and back, used all over the place
Comment: @T.S.: Uh, yes - when string conversions are *necessary*, that's fine. My point is that it's the wrong approach here.
Answer: Just cast:
intVal = (int?) dblVal;

This will already result in a null value if dblVal is null. Note that unlike Convert.ToInt32(double), this does not result in an exception if dblVal is outside the range of int. If that's a concern, you should work out exactly what you want to achieve.
From the C# 5 spec, section 6.2.3:

Explicit nullable conversions permit predefined explicit conversions that operate on non-nullable value types to also be used with nullable forms of those types. For each of the predefined explicit conversions that convert from a non-nullable value type S to a non-nullable value type T (§6.1.1, §6.1.2, §6.1.3, §6.2.1, and §6.2.2), the following nullable conversions exist:

An explicit conversion from S? to T?.
An explicit conversion from S to T?.
An explicit conversion from S? to T.

Evaluation of a nullable conversion based on an underlying conversion from S to T proceeds as follows:

If the nullable conversion is from S? to T?:

If the source value is null (HasValue property is false), the result is the null value of type T?.
Otherwise, the conversion is evaluated as an unwrapping from S? to S, followed by the underlying conversion from S to T, followed by a wrapping from T to T?.

...
Answer: Here's a way:
intVal = dblVal.HasValue ? Convert.ToInt32(dblVal.Value) : (int?)null;