Spring data JPA initialize load_file

Question: Estou usando um data.sql para inicializar o banco de dados com alguns inserts, no entanto estou tentando inserindo no banco um campo com imagem da seguinte forma:
insert into usuario(nome, imagem) values("Irineu", LOAD_FILE('classpath:images/foto.jpg'));
Banco de Dados MySQL.
A imagem esta na pasta resources/static/images.
A partir da aplicação está inserindo normalmente, o problema persiste apenas no arquivo data.sql.
Alguma sugestão de como resolver?
Comment: Este problema eh interessante, eu nao tenho a solucao mas eu entendo o problema. O classpath eh um conceito do java e apenas a JVM entende este conceito, contudo LOAD_FILE eh um commando do MySQL e portanto nao entende classpah este command pede por um file path.
Comment: Na verdade o uso do classpath foi sugestão do GPT
Comment: Se você inserir o caminho do arquivo manualmente no data.sql, acho que vai funcionar; no entanto, é uma prática ruim deixar o caminho do arquivo hard-coded. Não vejo uma solução fácil usando data.sql; talvez você tenha que utilizar outras estratégias. Por exemplo, o Flyway ou escrever código manualmente para inicializar o seu banco de dados.
Answer: O comando LOAD_FILE é usado para carregar um arquivo do sistema de arquivos do servidor MySQL. No entanto, o caminho especificado em LOAD_FILE deve ser o caminho absoluto no sistema de arquivos do servidor MySQL, e não o caminho relativo ao seu projeto.
O problema pode ocorrer porque o MySQL pode não ter permissões para acessar o arquivo utilizando um caminho relativo ou o classpath. O LOAD_FILE pode ser mais adequado para uso interno, e, por questões de segurança, pode estar desabilitado em alguns ambientes.
Uma alternativa para inserir a imagem em uma tabela MySQL a partir do arquivo data.sql seria converter a imagem para um formato de dados binários e usá-lo diretamente. Para isso, você pode usar a função HEX para converter a imagem para uma representação hexadecimal. Por exemplo:
INSERT INTO usuario (nome, imagem) VALUES ('Irineu', LOAD_FILE('path/para/imagem/foto.jpg'));

-- Converta a imagem para hexadecimal e insira no banco de dados
INSERT INTO usuario (nome, imagem) VALUES ('Irineu', 0x<hexadecimal_representation>);

Então, você precisará converter a imagem para uma representação hexadecimal antes de inseri-la no banco de dados. Existem várias ferramentas online ou utilitários que podem ajudar a fazer essa conversão. Certifique-se de inserir o conteúdo hexadecimal correto no lugar de <hexadecimal_representation>.
Além disso, lembre-se de que o armazenamento de imagens diretamente no banco de dados pode não ser a prática mais eficiente em termos de desempenho, especialmente para grandes volumes de dados. Em muitos casos, armazenar o caminho da imagem no sistema de arquivos e carregá-la conforme necessário pode ser uma abordagem mais escalável.
Comment: Show irmão, resolveu lindamente o meu problema.
usei https://tomeko.net/online_tools/file_to_hex.php?lang=en
para converter as imagens para Hexadecimal, só precisei desmarcar as duas opções da ferramenta e seguir suas instruções.
Muito obrigado.

Spring data JPA initialize load_file


how do I loop something in the form for(a!:b){loop}

Question: I am trying to loop into an arrayList of Users a user which is not already in the loop and adding to the list. is it possible to loop with a for each loop?
<code>public boolean addUser(User u)
    {
        boolean valid=false;
        for (u not in : users )
        {
            users.add(u);
            valid = true;
        }
               return valid;
    }
</code>
Comment: `if(!users.contains(u)) { users.add(u) }` not sure why you need to do a for loop when the array list provides the functionality
Comment: first of all, this code will not compile. second, it does not make much sense - if you are adding inside the loop, it means you are performing add as many times as there are items in the loop
Comment: Do you only want to add the user if the user isn't in the list already?
Comment: @SharonBenAsher you are right the code does not compile I was trying to add user to the list if it is not already in the list already
Comment: oh I will give it a try thank you
Answer: I figured out that I dont need a for Loop...instead I can use
<code> public boolean addUser(User u)
{
    boolean valid=false;
    if(!users.contains(u))
    {
        users.add(u);
        valid = true;
    }
           return valid;
}
</code>


I made two programs, one C++ console and one C#/WPF windows desktop. How can I integrate them?

Question: The C++ program reads a file, processes the content  and safes the result in another file.The filenames have to be typed in the console. The program works fine, but typing the filenames can be pretty unpleasant if the file and the program are not in the same directory.
Therefore I made the C#/WPF windows desktop program.You can open a file browsing your computer. The program puts the filename in a textbox so you can copy it. The same with the output file.
I start both programs, and when the C++ program asks the filename I use the other program to find the filename,copy it and paste it in the console. The same with the output file.
This works fine, but how can I merge the two programs?
Here is the second program:
Layout in xaml:
<Window x:Class="Cx_desktop_for_tracebitmap.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Cx_desktop_for_tracebitmap"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <StackPanel DockPanel.Dock="Top">

        <Button Click="input_Click" Content="input file" Name="Button_Input" Width="60" Margin="10" HorizontalAlignment="Left"/>
        <Button Click="output_Click" Content="output file" Name="Button_Output" Width="60" Margin="10" HorizontalAlignment="Left"/>

        <TextBox Name="inputname" Text="" Margin="10"  Width="500" DockPanel.Dock="Top" HorizontalAlignment="Center"></TextBox>

        <TextBox Name="outputname" Text="" Margin="10" Width="500"  DockPanel.Dock="Top" HorizontalAlignment="Center"></TextBox>
        Button Click="Go_Click" Content="GO" Name="Button_Go "Width="60" Height="60" Margin="10" HorizontalAlignment="Left" Visibility="Hidden"/>
    </StackPanel>
</Window>

C# in Mainwindow:
using System.Diagnostics;
using System.Windows;
using Microsoft.Win32;

namespace Cx_desktop_for_tracebitmap
{
    ///
    /// find filenames
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private string file_in = "";
        private string file_out = "";

        private bool BoolIn = false;
        private bool BoolOut = false;
        private void input_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            if (openFileDialog.ShowDialog() == true)
            {
                file_in = fix_filename(openFileDialog.FileName);
                inputname.Text = file_in;

                BoolIn = true;
                if (BoolOut) Button_Go.Visibility = Visibility.Visible;
            }
        }
        private void output_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            if (saveFileDialog.ShowDialog() == true)
            {
                file_out = fix_filename(saveFileDialog.FileName);
                outputname.Text = file_out;
                BoolOut = true;
                if (BoolIn) Button_Go.Visibility = Visibility.Visible;
            }
        }
        private  string fix_filename(string fixme)
        {
            char quote = (char)34;
            string fixed_filename = quote+fixme+quote;
            return fixed_filename;
        }
        private void Go_Click(object sender, RoutedEventArgs e)
        {
            string arguments = file_in + " " + file_out;

            Process pBPM_reader; pBPM_reader = new Process();
            pBPM_reader.StartInfo.FileName = @"BMP READER versie 4.exe";
            pBPM_reader.StartInfo.Arguments = arguments;
            pBPM_reader.Start();
        }
    }
}

I edited the program to show how I did it:

I added a new button (GO) to start the C++ program.
It is hidden at startup and apears when both files are chozen.
The filenames can contain spaces.
They must be wrapped between quotationmarks.That happens in the fix_filename method
The click on the GO button starts a new Process that runs the C++ program.
The Arguments take only one string, and the arguments are separated bij spaces.

Here is the heather and the first line od the C++ file. It shows how to extract the arguments

    int main(int argc, char *argv[])
    {
        std::vector<std::string> argList(argv, argv + argc);
    .
    .
    .
    }

Comment: In the simplest way, your C# program can directly [run](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.start) your other program
Comment: I used Igor's advice to let the C# program run the other program, and that works. Thank you Igor!
Comment: I think you can run anything from C#.
Here is something to study: https://www.codeproject.com/Questions/641053/calling-C-API-from-Csharp. Your C would manifest itself to c# as any c# method.
Answer: You have to either create a CLI-Intermediate code wrapper assembly that bridges between safe to unsafe code and converts (marshalls) types, etc. This allows you to represent a property C# interface to your C++ code. This blog has some more detailed information.
Or you can try to use P-Invoke to call C++ code from C# directly (see the docs here).
See this stackoverflow question for decision help.
For more information see the CLI documentation, P-Invoke documentation, this blog and this Microsoft forum.


How to create view of taxonomy terms and then once clicked on taxonomy term another view will be opened displaying all content having that term?

Question: I have a taxonomy called "Destination Type". There are 4 terms in it (Historical, Leisure, Wildlife,Cultural).
I have created one content type called "Destination" with taxonomy field "destination_type".
Now I want to create a view of taxonomy "destination type" which is I am able to create. Once user click on any of the term in that view say Historical, then the next view should open displaying the list of all destinations with destination type as historical.
This is how I want the result same as "Jump right in, Things to do" in http://www.gotobermuda.com/
I am stuck here. Please help me out with this
Thank you
Answer: I get it working. It was not that hard :)
First I create the view of taxonomy term. In that view I add contextual filter "Taxonomy term : term ID".
And in the next view I add contextual filter "Content: content_type_name"
Thats it. Got the desired result.


Value_counts not returning the desired output

Question: I'm trying to get the most common value of a column based on another column.
Specifically, I'm using this code:
data.beds[data.bedrooms== 1].value_counts()

This has worked before but now the output I get is
Series([], Name: beds, dtype: int64)

The data looks like this:
bedrooms     beds
0             1
1             1
1             1
0             1
2             2
...          ...

Can anyone tell me why this is happening and how can I fix it in order to get the actual value? This worked a few days ago, so I have really no idea what's wrong!
Thank you for your time!!
Comment: I can't reproduce that. Can you add a [mcve]?
Comment: I managed to fix it! Apparently I had forgotten to run the line of code that converts it to numeric (as this line was of object type because it had strings). Without converting it to numeric, the solution was to do data.beds[data.bedrooms== ''1''].value_counts()
Answer: I managed to fix it! After looking at here for so long my brain stopped working.
Apparently I had forgotten to run the line of code that converts it to numeric (as this line was of object type because it had strings). Without converting it to numeric, the solution was to do data.beds[data.bedrooms== ''1''].value_counts()
Thank you for your input!
Answer: Try data[data.bedrooms==1].beds.value_counts() or even data[data.bedrooms==1].beds.mode() since you want the values that appear most often.
Comment: It still doesn't work... doesn't return the actual value...
Comment: please share an example of the dataframe you're using.
Comment: Ended up realising that I had to convert everything to numeric first, as this column still had strings!! It works now!! Obrigada na mesma :)
Answer: You are making a filter before applying the value_counts() (all rows with bedroom value = 1 [data.bedrooms== 1])
That first filter is returning no values, that is why you get the shown output:
Series([], Name: beds, dtype: int64)
You cannot obtain the value counts on an empty dataset.
regards!


Java library search order

Question: Background / example (but question is probably broader than this):
I'm trying to write a Java application that accesses a Google AppEngine server. To set up the project for this, I followed the steps outlined in the accepted answer here:
Developing a Java Application that uses an AppEngine database
I am now running into a problem where I'm trying to execute an HttpURLConnection-request in the Java client application (i.e. not in the AppEngine server code), but Google's AppEngine library seems to have replaced the Java version of this connection with its own urlFetch()-implementation. This leads to me getting the following error: "The API package 'urlfetch' or call 'Fetch()' was not found.".
Actual question:
What determines the order in which Java looks through libraries to find needed class-implementations? Is there a way to modify this order (specifically in Eclipse), so that the actual JRE-functions take precedence over a third-party-library that is also needed. Or is there maybe something special going on with the implementation of Url in the example given above, that cannot be resolved by specifying a library order?
Update:
Turns out the problem I was seeing had nothing to do with the order in which classes were loaded. The AppEngine server code explicitly calls setContentHandlerFactory(...) to register its own handler during execution rather than at library load time (see here for a fix to this specific issue). So, while my "actual question" might still stand, I haven't actually yet come across a scenario where it matters...
Comment: Possible duplicate :http://stackoverflow.com/questions/5474765/order-of-loading-jar-files-from-lib-directory
Comment: @kocko Since the client-code is not running in Tomcat, this question is different from the one you linked...
Answer: You might have to define a custom ClassLoader.
Also, take a look at this answer.
Answer: Inside Eclipse, you can adjust the classpath order. Right click your project, choose Properties, Java Build Path, then click the "Order and Export" tab. However, of course, this won't affect your program when running outside Eclipse.

Java library search order


Transaction scope rollback in Entity Framework 6.1

Question: I have a problem with TransactionScope rollback.
When rolling back the TransactionScope state of objects in context (changetracker) changes from add to modify
private xType _x
{
    get;
    set
}

public void add(x: xtype)
{
    context.xlist.add(x);
}

public xclass: object
{
    public xclass()
    {
        _x = new xtype();
        add(_x);
    }

    public void savechanges;
    {
        using(transactionscope = new transactionscope())
        {
            try
            {
                context.savechanges();
                x = 0;
                x = x / x;
                transcope.complete();
            } catch
            {
                transcope.rollback();
            }
        }
    }

Project uses .net 4.0, vs 2013, ef 6.1, SQL Server 2008 Express, and uses UnitOfWork, Repository patterns
Comment: it's not a c#, please correct your question
Comment: its just a sample code my real code is in C#
Answer: Please do not use transactionscope this way. Transaction scope is a scope. You should do something with your database withing the using clause where your create the transaction scope. What people do a lot is, after applying changes, commit them on them by calling the commit method. If there is a crash, nothing is committed and transaction scope knows that the changes so far require a rollback. Transaction scope can be used to implement the "unit of work" design pattern. Things within the using clause are considered to be one unit of work. They should be done all (or not at all). Therefore, some kind of rollback is needed when there is a crash before calling commit. Doing things almost completely is not accepted, since it is one unit of work.
Here is some code example that explains the basic concept.
https://msdn.microsoft.com/en-us/library/system.transactions.transactionscope(v=vs.110).aspx
Here are more examples:
http://www.codeproject.com/Articles/690136/All-About-TransactionScope
Answer: You are modifying your objects after having saved them. That makes them modified.
EF does nothing special when a transaction rolls back. None of its internal state changes. Entity objects are not reverted back. The best pattern is to abandon the EF context after a rollback.
You do not need to explicitly rollback. Delete the catch. Right now all that it accomplishes is to swallow all errors.


Choosing C# with WPF for Ultra-Long-Term Project?

Question: I'm involved in a project where a team of developers is building a very long term infrastructure project to replace an existing 10 year old system. By "very long term" I mean it must be operating, supported and maintained for at least 10 years into the future from the point of release. Taking into account ~2 years of development, this means we should at this point choose a technology/language/framework to last at least 12 years. We have full control over the computers running the project, their operating systems, etc. I was the developer of the to-be-replaced 10 year old system, and I'm helping the team build the new one right.
The application has a very complex user interface. The UI is built dynamically from configuration files at start-up, each UI component has dependencies on logic and other UI components, which it must receive in run-time. UI elements themselves are very complex, imagine custom gauges, graphs, knobs etc.
Two choices have already been made in the project, that I do not judge or try to change:

It will be a desktop application
It will be developed in C#

Now we are at a point of choosing the right framework to make our very flexible UI system "easy to develop", i.e. reduce the number of developer bugs by relying on a debugged, already-made framework.
The team examined Microsoft's CAB (Composite UI), which suited its purposes extremely well, however the fact Microsoft discontinued it in 2007 is a huge problem taking into account the long-term aspects of the project (think of a framework bug being discovered in 6 years - who will provide support? - and I know we could fix the code in the CAB itself, but that's something we would like to avoid).
One thing that obviously pops to mind is relying Microsoft's WPF. It seems to be "the future" of UI development, however it frightens me when thinking about it long term. My main concern is that the market will not accept it, that 3 years from now Microsoft will discontinue it, and that 6 years from now I will not be able to receive proper support for it.
However I don't really see an alternative, besides writing our own framework. I don't want disrespect any 3rd party framework developers, but for such a long term project I can only use products/frameworks/etc from very well-established vendor.
I would appreciate thoughts on whether choosing WPF is the right call given the above context (and if not - what is the right "complex UI framework" for such a long term desktop application project using C# ?).
Thanks (and sorry for the long question)
Answer: Ultra-long-term? 10 years? COBOL is STILL being used!
Joking aside, I believe WPF is your best bet. Microsoft has invested heavily in WPF and XAML over the past few years and using the same core infrastructure on Silverlight (which Microsoft really cares about) is a strong point for sticking to it for enough time. I don't think WPF is going to be thrown away anytime soon.
Comment: Thanks for the informative answer. About your joke - I really think in our days planning 10 years ahead is almost impossible with the pace in which software and hardware vendors are pushing us to upgrade every 2-3 years...
Comment: "Silverlight (which Microsoft really cares about)" five years later, this quote is funny...
Answer: The fact that the Visual Studio 2010 UI has been rewritten in WPF is quite strong evidence that they'll support it for some time to some.
Answer:
Smart Client Contrib
Prism

May be of help if you've not already looked at them.
Answer: The WPF adoption rate is still pretty low although it seems to me that Microsoft will be getting more and more oriented in that direction over the next years.
You may not be extraordinary happy about it, but it's the only solid option that comes to mind.
Comment: "Maybe it's not the best option, but it's the only one you have." so it's the best ;)


Geometrical interpretation of $\operatorname{Spec}(\mathbb{R}[x,y]/(x^2+y^2))$

Question: $\def\Spec{\operatorname{Spec}}$If am not mistaken, the prime spectrum of $\Spec(\mathbb{R}[x,y]/(x^2+y^2))$ consists of the points $(\overline{x},\overline{y})$, $(\overline{x}-a)$, $(\overline{y}-b)$, where $a,b\in\mathbb{R}\setminus\{0\}$ (I think one can prove this by using the description of $\Spec k[x,y]$ explained here).
However, I wonder: why is this spectrum? Does it bear some geometric interpretation? I heard that its points are to be interpreted as "two lines that intersect at the origin." I guess reflecting somehow the fact that over the complex numbers we can factor $x^2+y^2=(x+iy)(x-iy)$, and that $\Spec(\mathbb{C}[x,y]/(x^2+y^2))$ is effectively the classical complex affine variety equal to $V(x+iy)\cup V(x-iy)\subset\mathbb{A}_\mathbb{C}^2\ (=\mathbb{C}^2)$.
My questions are:

Is this interpretation of $\Spec(\mathbb{R}[x,y]/(x^2+y^2))$ correct?
Is any of this pointing out to any general phenomenon/a going on behind the scenes? If I'm not being precise is because I don't know what I'm looking for. I guess I would be happy with (a) knowing about some relation between a $k$-variety (in the scheme-theoretic sense) and its base change to $\overline{k}$ (whenever the later is still a variety), (b) some explanation or indications of literature about how schemes extend geometry to polynomials that don't have solutions or don't have that many solutions over non-algebraically closed fields (I am not talking about the usage of nilpotents in modern algebraic geometry, everything I would like to find out more about is in the reduced case).

(The most general definition of "scheme-theoretic $k$-(pre)variety" I know is that of a reduced (separated) $k$-scheme of finite type.)
Comment: Your first sentence seems potentially incomplete - "... where $a,b\in\Bbb R\setminus\{0\}$, and $(\overline{x},\overline{y})$" doesn't really make sense (what is the condition you're imposing on $(\overline{x},\overline{y})$?).
Comment: $(\overline x,\overline y)$ is the ideal generated by $\overline x$ and $\overline y,$ but that confused me too, at first. @KReiser
Comment: I reordered the ideal enumeration to avoid confusion.
Answer: There are further ideals, even maximal ideals.
The maximal ideals must have quotient fields that are extensions of $\mathbb R.$ Consider the cases when the quotient field is $\mathbb R$ or $\mathbb C.$ So the image of $f:\mathbb R[x,y]\to\mathbb C$ must send $x,y$ to elements of $\mathbb C$ such that $f(x)=\pm i f(y).$
You've covered the cases when one of $f(x)$ or $f(y)$ is real.
So, given $f(x)=u+vi$ with $uv\neq 0,$ we can take the ideal:
$$I_{u,v}=\left\langle \overline x^2-2u \overline x+(u^2+v^2), \overline y^2-2v \overline y +(u^2+v^2)\right\rangle$$
Adding the two generators and multiplying by $-\frac12,$ we can also write this ideal as:
$$I_{u,v}=\left\langle\overline x^2-2u \overline x+(u^2+v^2), u \overline x +v\overline y -(u^2+v^2)\right\rangle$$
Note that when $u\neq 0, v=0,$ this ideal becomes:
$$I_{u,0}=\langle (\overline x-u)^2,u(\overline x-u)\rangle =\langle \overline x-u\rangle,$$ and similarly. $I_{0,v}=\langle \overline y-v\rangle,$ so this pattern contains your cases, too.
You also left out the obvious zero ideal, $\langle 0\rangle,$ which is prime but not maximal.
It should be possible to prove these are all the primes.
Idea for how to start: First, consider the maps $\mathbb R[x],\mathbb R[y]\to \mathbb R[x,y].$ The image of these maps in the quotient by your prime ideal must be integral domains, so the ideals in $\mathbb R[x]$ and $\mathbb R[y]$ must be either zero or generated by prime polynomials. The prime polynomials are the linear polynomials and the quadratic polynomials with complex roots.
If $p(x)\in \mathbb R[x]$ is a prime in the ideal, then show $p(iy)p(-iy)$ is in $\mathbb R[y]$ and must be in the ideal, too. If $p$ is linear and not $x,$ then $p(iy)p(-iy)$ is prime, but if $p$ is quadratic, then $p(iy)p(-iy)$ must factor.
So the prime ideals are:
$$I_{u,v},(u,v)\neq 0,\\
\langle \overline x,\overline y\rangle,\\
\langle 0\rangle $$
Comment: I think equation $f(x)=\pm if(y)$ would correspond to the ideal $I^\pm_{u,v}=\left\langle \overline x^2-2u \overline x+(u^2+v^2), \overline y^2\pm 2v \overline y +(u^2+v^2)\right\rangle$, (the first generator corresponds to the polynomial $(x-c)(x-\overline{c})$, and the second one, to $(x\mp ic)(x\mp\overline{ic})$, where $c=u+iv$), with your notation, $I^-_{u,v}=I_{u,v}$. I haven't checked the details but wouldn't both $I^-_{u,v}$ and $I^+_{u,v}$ be prime? (So they would be correspond somehow to the points in $V(x+iy)$ and in $V(x-iy)$, respectively.)
Comment: @ElíasGuisadoVillalgordo but the first polynomial, in $x,$ only depends on $|v|,$ so I just took one case of the $\pm.$ Basically, my $I_{u,v}$ covers all cases. But I did gloss over that in my answer.
Comment: Right. My mind is currently more focused on finding out about the geometric justification of the space and that slipped


OG, IMCE, CKEditor, and Private files: 404 Images not found

Question: I use Organic Groups, alongside IMCE and CKEditor.
In one content type, I have a text-field that the client will use to add some text and an image. Lets call this content type "Team Match Analysis" -> which is a group content type for the group type of "Teams." Thus, we have a team named Arsenal, with a page of their most recent match analysis.
However whenever I try to add an image via the CKEditor from the OG content type (Team Match Analysis), the image is uploaded correctly (but to the users' private area) and then a blank box is shown on the preview.
If I try going to the link it provides (direct link), then it is always a 404 NOT FOUND page error.
I don't know why it's not working, the private Drupal files are in another folder away from /var/www/ and I have chmod set to 775 for the private_drupal folder.
I know the private files work fine, since I have a File field for uploading PDFs which is set as "private files" but that uses the Multi-upload widget and not CKEditor to upload. That works fine, as the PDF files can only be accessed for people that are in the group.
Ideally what I need is to either set the image uploader/browser for CKEditor to use the "public profile" or find a way so that all the images that are uploaded are shared with the people in the same group and ensure that they can be displayed as an inline image with the  tag for the multi-line text field.
UPDATE: 26/06/13
I can upload images (using CKEditor) but I can't preview or view them directly. It seems that CKEditor always uses the "private" profile which I've just set to be /private directory (and /public for public directory). All uploaded images are shown as "Not Found" when you try to go to the link, so it's something to do with Drupal not understanding that it needs to load/map the private files directory?
Strange since the "File" fields for PDF work fine.
UPDATE: 28/06/13
I assume it must be something to do with the database not being correctly updated when the image is uploaded in the IMCE widget (which is a pop-up when you click on the Add Image icon in the WYSIWYG - CKEditor toolbar for the text area field).
I have the images uploaded to "system/files/groups/group name/". If I browse to that directory, I get the Access Denied page from Drupal. However if I go to the direct link for the image which would be: "system/files/groups/group name/image.png" - then I get the "404 Not Found" page (which I assume is from the fast_404 module I have installed).
UPDATE: 1/7/13
Here's a list of all the modules:
http://pastebin.com/vt2g1aPB
My private folder is:
/var/private_drupal
My IMCE profile is set to the default one, with rules to see /main as well as /groups/ - those folders were created correctly and I get the Access Denied if I try to view the directory at: /system/files/groups/ - if I try an invalid group name (i.e. something that doesn't exist) then it gives me the page not found error which is Drupal Themed suggesting it's not provided by the fast 404 module.
I have just tried to upload images to where I would normally upload PDF files and all images show up as the 404 Not Found page (blank, no Drupal Theme), however all the .pdf files work fine still. For my "PDF" field (which accepts images, pdf, docs, etc.) these files get uploaded directly to the private directory and not in any sub-folder. However since none of the images work there it seems to be something wrong with the image/media modules for image files?
I decided to use the WYSIWYG Image uploader button to upload a PDF file, obviously I won't be able to see anything but going to the direct link of the pdf file results in an Access Denied page by Drupal... which is strange since I am in the group and should have access to view that PDF file.
It seems even worse now, the JSON Feeds parser which was working fine and would import the images from the URL for the feed items but no longer works... I've tried removing all image related modules and starting again but no luck, and still no errors in the database log.
EDIT: Fixed the JSON Feeds parser, it now imports the images fine again and uses the Large image style (overridden), all those images are uploaded to the public folder.
I'm wondering if I can maybe "force" WYSIWYG to use the public folder instead of private but to not break the file fields that I use for PDF that need to be private?
Answer: If you are using Image Styles, you might be having a problem with core 7.20. To test this, try setting the variable image_allow_insecure_derivatives to true, either with Drush or settings.php.
Comment: I've added `$conf['image_allow_insecure_derivatives'] = TRUE` to the settings file and cleared the cache, then tried to re-upload a new image using the IMCE browser via WYSIWYG (w/ CKEditor) and it still doesn't work, same 404 page.
Comment: Have you checked your logs?
Comment: With the "database logging" module on, I didn't notice any errors in the logs, and going directly to the image link then refreshing a few times, then checking the log doesn't add anything into the logs.
Answer: So I've decided to set the default download method to Public (it was Private), and now I can insert images just fine.
...and the PDFs still seem to be set to use the Private directory so that's not broken either.


Is there any accordion for JQuery

Question: I need to use a panel with a summarize text in it and a button below it. When I click the button the panel expand and more text appear and the button change it appearance and located below the text.
You can see the image:

I found some threads about JQuery and accordion like: thread or maybe other website, but it doesn't have the functionality I'm looking for.
Is there any other known pattern to do it or I need to write it?
Comment: Actually you right... and that's why I didn't find the answer I was looking for. I looked at only 1 panel while I should look about multiple panels...
Comment: FYI - this is **expand/collapse**, not `accordion`.  An [accordion](https://jqueryui.com/accordion/) works by expanding one area and collapsing all others... like.. well... how can I put this... an [accordion](https://en.wikipedia.org/wiki/Accordion)!
Answer: You can do that simply using a small script right?

$(function () {
  $(".see-more").hide();
  $(".see-more-trigger").click(function () {
    $this = $(this);
    $this.prev(".see-more").slideToggle(function () {
      if ($this.prev(".see-more").is(":visible"))
        $this.html("▲");
      else
        $this.html("▼");
    });

    return false;
  });
});
* {font-family: 'Segoe UI'; text-decoration: none; margin: 0 0 10px;}

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi hic perspiciatis corporis explicabo, aperiam veritatis impedit natus et voluptatum quas facere dolores nam enim illo harum dolore recusandae tenetur reiciendis!

Ad, facere illo, minima ipsa facilis voluptatibus provident expedita quos in, dignissimos earum vitae consequuntur blanditiis optio sed porro nostrum a soluta corporis. Culpa, non, ipsa. Deserunt, vitae, magni! Alias. Esse cum inventore amet enim odio deleniti, saepe, cumque quasi ducimus sunt consequuntur obcaecati consequatur sequi hic ut maiores eius quae vel nemo aut atque similique, nobis eligendi labore. Praesentium.▼

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officia unde, laborum cum asperiores minima sed modi laboriosam architecto nam sapiente. Voluptate commodi, accusantium explicabo vitae, ex dolore quia minima esse.

Eum facilis repudiandae qui dolor voluptatum itaque amet, fuga ducimus velit dolorem, animi eaque quia officiis fugit officia saepe ea, dolore. Itaque molestias vitae, velit, hic impedit ipsa quaerat illum! Ut consequatur fugiat voluptatem libero quis sequi voluptas architecto fuga dolor voluptates nihil minus quidem distinctio natus nam quam totam tenetur eius ullam, necessitatibus harum, quod corporis perferendis enim. Culpa.▼

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error est amet iure aliquam iste autem quod ipsa ab harum illo, saepe fugit possimus obcaecati accusantium cumque optio repudiandae itaque facilis.

Enim illo ad, tenetur, ipsum id corporis minima, voluptatum fugit, nihil explicabo maiores unde! Id eveniet, pariatur, quis qui beatae ipsa. Vel recusandae numquam reiciendis, dolorem ipsam tempora dolorum perspiciatis! Rerum, explicabo dicta quos, optio pariatur, cum expedita cumque et ratione recusandae voluptatum quis fuga veniam fugit nemo! Cupiditate error omnis fugit ipsa, vero architecto corrupti. Provident ab, consequatur voluptate.▼

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Impedit sed vero praesentium cumque libero inventore id optio eaque, totam vel at repellat. Dignissimos, in. Accusantium atque tempore, cupiditate earum quidem!

Omnis numquam quod veniam ratione explicabo, sequi iusto quibusdam ex, sunt tempora voluptatem nam inventore minima! Omnis, esse, impedit. Nobis debitis harum sed atque. Eveniet voluptate commodi quaerat velit aut! Quae quaerat dolorum quam optio vitae delectus, eligendi mollitia non inventore autem. Voluptate aperiam, natus necessitatibus optio iure! Neque fuga suscipit, maxime illo itaque ratione facere laboriosam ipsum delectus? Voluptatum.▼

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora, ea! Veniam cum unde quia, aspernatur dolorum, mollitia fuga nisi debitis vitae eaque sapiente deserunt, eligendi maiores tempora magnam a reiciendis.

Id praesentium ea sit quae, sequi veritatis alias mollitia aspernatur animi atque eaque nesciunt aut ducimus sunt maxime non numquam magni dignissimos! Ducimus consequatur facere delectus adipisci saepe dolorum corporis. Iure inventore blanditiis sit ab maxime, fuga repellat dignissimos velit, quaerat cupiditate consequuntur iste mollitia ut alias non. Veritatis perspiciatis sint optio modi, esse perferendis culpa velit nostrum commodi maxime.▼

Comment: Yes, you are absolutely right... I'll do it. Thank you!
Comment: Thank you for the fast answer. I saw an answer with "slideToggle" but it's not good because the image changes on the same location and I want it to be on bottom (where the text end).
Comment: @Dror Don't say you are a programmer if you comment like this. It took me a second to change the position. `:P`
Comment: @Dror Yes buddy. I changed it long back. `:)`

Is there any accordion for JQuery


Let $n$ be a positive integer. Prove that $n(n + 1)(n + 2)(n + 3)$ cannot be a square or a cube.

Question: For the expression cannot be a square, there is an answer here. Prove that $ \sqrt{n(n+1)(n+2)(n+3)+1} $ is always a natural number
I am trying to prove it cannot be a cube.
There is a conclusion that every cube could be written as the difference of two squared, i.e.
$r^3$ = $p^2$ - $q^2$, where $p = r(r+1)/2$ and $q = r(r-1)/2$.
Therefore I think the conclusion holds if $n(n + 1)(n + 2)(n + 3)$ could not be expressed as the difference of two squared but I don't know how to continue.
Comment: Well, by the Catalan conjecture, now [Mihăilescu's theorem](https://en.wikipedia.org/wiki/Catalan%27s_conjecture), there can't be any positive consecutive cubes and squares other than $8,9$ so the old argument works here as well.  Of course there may well be a simpler argument in this particular case.
Comment: @lulu Thanks for point.I read the question as $n(n+1)(n+2)(n+3)+1$ cannot be a perfect cube. I thought about editing the answer, but there are a lot of articles online for the solution of $m^3-n^2=1$.  So basically the asker can read it himself.  Regardless of NN2's answer, there are different proofs for $m^3-n^2=1.$
Comment: Thank you all for the answers.
Answer: 1/ $n(n+1)(n+2)(n+3)$ can't be a square number
Denote $x = \sqrt{n(n+1)(n+2)(n+3)}$, we have
$$
\begin{align}
x^2 &= n(n+3)(n+1)(n+2) \\
&= (n^2+3n)(n^2+3n+2)\\
&= (n^2+3n+1)^2 -1
\end{align}
$$
It's easy to notice that
$$(n^2+3n)^2 <(n^2+3n+1)^2 -1 <(n^2+3n+1)^2$$
$$\implies n^2+3n < x <n^2+3n+1 \tag{1}$$
From $(1)$ we deduce that $x$ can't be a natural number so $n(n+1)(n+2)(n+3)$ can't be a square number.
2/ $n(n+1)(n+2)(n+3)$  can't be a cube number
Denote $x = \sqrt[3]{n(n+1)(n+2)(n+3)}$ and $y = n^2 +3n+1$ suppose $x \in \Bbb N+$. We have
$$x^3 = (n^2+3n+1)^2 -1 \implies x^3= y^2-1 \tag{2}$$
This diophantine equation $(2)$ is not trivial. An elementary proof of the problem can be found in the paper THE DIOPHANTINE EQUATIONS x3=Ny2±1 of (J. H. E. Cohn, 1991) (or this link) according to this answer and the unique solution of $(2)$ is $(x,y) =(2,3)$.
However, there doesn't exist $n \in \Bbb N^+$ such that $n^3+3n+1 = 3$.
Hence, $n(n+1)(n+2)(n+3)$  can't be a cube number.
Comment: Thank you for the answer. I may need to read the proof of the equation having unique solution of (2,3)
Comment: @RunzeLi I added a second link for the paper so you could read it freely. If you can't access it, use TOR as browser.


Where to instantiate class in rails

Question: I need to use the aws-sdk-comprehend gem in my model Metric, but I'm not sure if it's ok (accordingly to rails convention) to instantiate outside of the class, e.g:
comprehend = Aws::Comprehend::Client.new

class Metric < ApplicationRecord
  def key_phrases
    # Use comprehend object here.
  end
end

Is there a rule of thumb to in regard to this situation? I don't want to instantiate in the key_phrases because it will instantiate every time I call it.
Comment: It's perfectly fine to instantiate another object inside of an AR class. In fact AR does this already with it's relationships (has_many/belongs_to/has_one). If there's overhead for initializing `Aws::Comprehend::Client` though, and its instance can be used throughout your application with just one config, you may want to consider memoizing it in an initializer and a global, or in `application.rb`
Comment: @AmandaFerrari `def comprehend_client; @comprehend_client ||=  Aws::Comprehend::Client.new; end`
Comment: @JoshBrody I thought about memoizing it. Is there a Gem that you recommend?
Comment: What's wrong with an instance method `comprehend_client` that memoizes the client? Then call the object from `key_phrases` with `comprehend_client`?
Answer: The answer was already posted in the comments. Here a full example of how it might look in idiomatic Ruby:
class Metric < ApplicationRecord
  def key_phrases
    # Use comprehend object here.
    comprehend_client
  end

  private

  def comprehend_client
    @comprehend_client ||= Aws::Comprehend::Client.new
  end
end

Comment: One big reason you want to do this instead of referencing a local variable in the outer scope is that it lets you use setter injection to mock the dependency in tests.

Where to instantiate class in rails


Display list of object's child arrays containing dupes with 1 bullet per index using ng-repeat

Question: I have an object (searchedMenu) containing 3 arrays of equal lengths (name, short_name, and description).
for(var i=0;i<description.length;i++){
    searchedMenu.name[i] = description[i].name;
    searchedMenu.short_name[i] = description[i].short_name;
    searchedMenu.description[i] = description[i].description;
}
menu.searchedMenu = searchedMenu;

I want to display each name, short_name, and description as an unordered list item like this:

name1, short_name1, description1
name2, short_name2, description2

I'm struggling to do this. I've declared my controller in the relevant div as

If I do this:

 {{item}}

I get 3 bullet points containing all elements of each array like this:

name1, name2,...
short_name1, short_name2, ...
description1, description2, ...

If I do this:

 {{item.name}}, {{item.short_name}}, {{item.description}}

I get:

, ,
, ,
, ,

As an experiment I also tried this:

 {{item}}

and it gave me nothing in the browser with a console error of:

Error: [ngRepeat:dupes]
  http://errors.angularjs.org/1.5.8/ngRepeat/dupes?p0=item%20in%20narrow.searchedMenu.name&p1=string%3AOrange%20Chicken&p2=Orange%20Chicken

The console.log("Searched menu: ", menu.searchedMenu); is:
Searched menu:  Object {name: Array[219], short_name: Array[219], description: Array[219]}

The full controller code is (this is a dirty work in progress):
NarrowItDownController.$inject = ['MenuSearchService'];
function NarrowItDownController(MenuSearchService) {
  var menu = this;

  var promise = MenuSearchService.getMatchedMenuItems();
  var item_name = ["",""];
  var description;

  var searchValue = "ton";
  function containsFilter(value) {
    return value.indexOf(searchValue) !== -1;
  }

  promise.then(function (response) {
    menu.results = response.data;
    menu.results = menu.results.menu_items;

    description = response.data;
    description = description.menu_items;
    console.log(description);

    var searchedMenu = {};
    searchedMenu.name = [];
    searchedMenu.short_name = [];
    searchedMenu.description = [];

    for(var i=0;i<description.length;i++){
        searchedMenu.name[i] = description[i].name;
        searchedMenu.short_name[i] = description[i].short_name;
        searchedMenu.description[i] = description[i].description;
    }

    console.log(searchedMenu);
    menu.searchedMenu = searchedMenu;//description.filter(containsFilter);
    console.log("Searched menu: ", menu.searchedMenu);

  })
  .catch(function (error) {
    console.log("Something went terribly wrong.");
  });

  menu.logMenuItems = function (searchTerm) {
    var promise = MenuSearchService.getMatchedMenuItems(searchTerm);

    promise.then(function (response) {
      console.log(response.data);
    })
    .catch(function (error) {
      console.log(error);
    })
  };

}

Note that I hard coded the search term in the example above because it's a work in progress.
Comment: Why do you need to transform the `description` array in 3 arrays. You could use `ng-repeat="item in description"` and bind with `item.name`, `item.short_name` and `item.description`
Comment: where is your angular controller code?
Comment: also maybe show us the console.log of narrow.searchedMenu
Comment: @FerasSalim The first code block is the key part of the Controller code but I can add more of the code, no problem. Just give me 10 seconds.
Comment: @defaultcheckbox Sure it says `Object {name: Array[219], short_name: Array[219], description: Array[219]}`
Comment: @Troopers That's a good idea, but I tried it and couldn't get it to work. Maybe if we solve this then doing that will work as well?
Answer: Try this:

 {{ item }}, {{ narrow.searchedMenu.short_name[$index] }}, {{ narrow.searchedMenu.description[$index] }}

The searchedMenu object contains three arrays, therefore you can loop through one of the arrays and in each step of the loop, extract the elements from the other arrays with the $index.
AngularJS does not allow duplicates in a ng-repeat directive therefore you must add track by $index to your repeater
Comment: It worked!!!! :-) Thank you, that's super awesome. I never knew about `track by`.
Answer: If you don't need to split it out, you should just do this

 {{item.name}}, {{item.shortName}},{{item.description}},

Comment: That doesn't result in anything being displayed in my browser
Comment: What is your data structure? Could you give an example
Comment: Sure, so the object has those 3 arrays you have in your answer. If you want to see the raw data it's here: https://davids-restaurant.herokuapp.com/menu_items.json
Answer: In your controller:
menu.searchedMenu = description;

In your template:

 {{item.name}}, {{item.shortName}},{{item.description}},

Comment: That looks good in the console but nothing is coming up in the browser. Maybe because of the controller as syntax (i.e. `narrow`?)
Answer: First of all i think that for isla not necesary because the key values is the same in both part data and the menú so i recomend that only do the last part, that is menu.searchedMenu = searchedMenu; and change the searchedmenu in the right to your description and second ir the left part is inside of a controller change menú to this variable and in the ng repeat put:

 {{item.name}}, {{item.short_name}}, {{item.description}}

It should work


Azure: How to ssh to a vm in a resource group with several ubuntu vms

Question: I've created a resource group with several ubuntu vms. I've used the preconfigured vm provided on azure. The group is up. I can see it's tile with vm scale set, load balancer and public ip address. Yet, I don't know how to shh to individual machines in the group? I can only see the ip address of the group (cannot ssh to it).
Answer: To ssh to individual machines one needs to specify a port which can be found in the "Inbound NAT rules" under Settings. For example if the port for one of the VMs is 50001 then:
<code>ssh -p 50001 -l username IPofVMset
</code>
The IP address of the VM set is dynamic (after each restart of the VM set it is different), but there should also be a static DNS name in the azure domain.
PS. Note that for scp the switch for providing port number is -P (capital) rather -p.


Create an array of Rectangles : Opencv , Android

Question: I have contours which are extracted from findcontours() , Now I want to create an array of all the boundingrects of contours.
int area,total=0;

for(int i=0; i<contours.size(); i++)
{
    area = (int) Imgproc.contourArea(contours.get(i));

    if(area>4600 && area<5100)
    {
        Rect abc = Imgproc.boundingRect(contours.get(i));
    }
}

Here it is saving only 1 contour in Rect , I want an array of Rect of all contours.
Answer: That should be better:
int area,total=0;
List<Rect> contourRects = new ArrayList();

for(int i=0; i<contours.size(); i++)
{
    area = (int) Imgproc.contourArea(contours.get(i));

    if(area>4600 && area<5100)
    {
        contourRects.add(Imgproc.boundingRect(contours.get(i)));
    }
}

Comment: Your answer is correct (+1), but you should explain to OP what he was getting wrong.


JCache with Redisson, how serialization / deserialization works?

Question: I am using JCache with Redisson, it's not clear to me how serialization/deserialization works while using the cache.
When I setup the Cache via configuration I didn't setup anything about this. Is this done transparently?
The objects I am storing in cache are lists, objects from java.time for example, but I require all of objects of the classes I am storing in the cache implement Serializable, is this enough?
Looking at the data on redis it seems it is storing data serialized via java default serialization, am I wrong?
Can I control this behaviour? or it's better to leave it as it is ?
Thanks for help
Comment: from [redisson doc](https://github.com/redisson/redisson/wiki/4.-data-serialization) it seems that `Redisson` uses [Kryo](https://github.com/EsotericSoftware/kryo) as default data serializer/deserializer. I suppose this is the same when used with `JCache`.
Answer: As my comment, from redisson documentation Redisson use Kryo as default data serializer/deserializer.


Why shouldn't commas be included in sql field names?

Question: People keep telling me that spaces shouldn't be included in column names. I was just wondering, why is that? It is an issue I am having with a few database tables I am creating for school. The field names include Preble and Darke.
Instead, they need to be "Preble County (OH)" and "Darke County (OH)". If they were row names, I would just create an ID # column, and natural join that with a table displaying names that I want them to be ("Darke County (OH)" instead of "Darke").
However, I have no idea how I can go about changing these names since they are my field names. Can anyone help me out? Any help would be greatly appreciated.
Comment: Do you want to know *why* you shouldn't include commas (or spaces it seems) in field names or the `ALTER TABLE` syntax to remove the spaces?
Comment: Because having to use backquotes (or double quotes) around every column and table name just clutters up the query, making it harder to understand and type.
Comment: For instance, why shouldn't a field name be `Darke County (OH)`?
Comment: Okay, so is there any way I could natural join two tables, so when I print a column name, I can print `Darke County (OH)` instead of `Darke`?
Comment: Things like spaces and commas in table names create more work for you to do.  You have to do something to escape the non-standard characters every single time you reference the table in a query.  The same goes for using sql keywords as table names.  In some database engines, it is also true for datatypes.
Comment: Do you have a column named \`Darke County (OH)\`, or a value in a column \`Something\` containing "Darke County (OH)"?  If the former, you definitely need to normalize your database.
Comment: So, basically I am screwed then? I am using php to build a website, and instead of printing `Darke` on the page, I would like it if it printed `Darke County (OH)`.
Comment: In real applications, column and table names are something the end user will never see. So they can and should bear more programmer/computer friendly names. This is obviously not true for school projects, where you basically access the database output directly, as you wouldn't in real life.
Comment: I think you are confusing field names with data. The field (or column) name in this case seems like it could just be `county`.
Answer: tldr; Trying to included commas (or other special characters) generally indicates a fundamental flaw with the column name2.
This is a bad database design. It is bad because it tries to encode information into a column name1. This is not the point of a column name! A column name is merely a friendly moniker for an element of a record/tuple - nothing more. Under Relational Algebra (RA), and thus SQL, it is the record/tuple that contains the information.
Besides just leading to a schema that is hard to deal with (extra quoting syntax) that requires hard-coding queries based on changing information (column names and multiplicity), it is also impossible to use with a number of RA techniques in a flexible manner. RA can only generally handle multiplicity across records - and, as discovered, this includes joins.
Instead, the schema should look similar to, say:
County    State   Other Columns
=======   =====   =============
Darke     OH      ..
Prebel    OH      ..

Where the Key is, say, <code>(State,County)</code> and "Other Columns" are dependent upon the key. Of course the model should be correctly normalized in relation to all the other information that is captured.
Note that there is no information stored in the column names presented above: the names are merely friendly monikers representing the information stored in each column.

1 Now a PIVOT transformation, which is primarily for human output/display, can be performed as needed. This is were a column in the output table (not schema table!) is generated per set of record values. However, this is a secondary issue and should not affect the primary schema.
If using SQL Server, one could first UNPIVOT the information-filled column names, perform the join and then re-PIVOT (given a known set of column names). However, I have no idea how this would be done in MySQL - a messy dynamic query, perhaps. In any case, this is an approach I would avoid.

2 While special characters are not allowed in bare identifiers, it is possible to use such names when used in quoted identifiers - e.g. `Vancouver, WA` or, with ANSI quotes, "Vancouver, WA". However, keep reading the rest of this response which argues against using such identifiers.


How to calculate really big number mod 990

Question: How to calculate $67^{26^{42^{23}}}\mod 990$?
My idea is to solve $x \equiv 42^{23}\mod 990$ then solve $26^x\mod 990$ and so on. But how to "compute" $42^{23}\mod 990$ only with a pencil and a sheet of paper?
Second idea is that we may factor $990$ into $2 \cdot 3^2 \cdot 5 \cdot 11$ and use chinese remainder theorem...
Comment: use the second idea
Comment: [finding a^b^c^… mod m](http://stackoverflow.com/q/4223313/995714)
Comment: Could be useful to note $67^2 \cong 67^{26}$.
Answer: If you don't mind a bit of pen and paper work, you can solve this problem just using a little modular arithmetic.
First, calculate $67^n \mbox{ mod } 990$ for a few $n$. There's no need to calculate each $67^n$ explicitly; just take $67^{n-1} \mbox{ mod } 990$, multiply that by 67, and mod out by 990 again. You'll notice that \begin{equation*}
67^6 \equiv 199 \mbox{ mod } 990
\end{equation*}
and thus \begin{equation*}
67^{12} \equiv 1 \mbox{ mod } 990.
\end{equation*}
Great! Since $67^{n+12} \equiv 67^n \mbox{ mod } 990$ in general, we only need to know $26^{42^{23}} \mbox{ mod } 12$. A bit more hand calculation shows that, for $n \geq 2$, \begin{equation*}
26^{\mbox{ even } n} \equiv 4 \mbox{ mod } 12
\end{equation*}
and
\begin{equation*}
26^{\mbox{ odd } n} \equiv 8 \mbox{ mod } 12.
\end{equation*}
Since $42^{23}$ is even, we thus see that \begin{equation*}
26^{42^{23}} \equiv 4 \mbox{ mod } 12.
\end{equation*}
Therefore \begin{equation*}
67^{26^{42^{23}}} \equiv 67^4 \equiv 661 \mbox{ mod } 990.
\end{equation*}
Answer: First use the Chinese remainder theorem:
$$\mathbf Z/990\mathbf Z\simeq \mathbf Z/2\mathbf Z\times\mathbf Z/5\mathbf Z\times\mathbf Z/9\mathbf Z\times\mathbf Z/11\mathbf Z. $$
Now

$67\equiv1 \mod 2$,
$67\equiv2 \mod 5$, hence it has order $4$ modulo $5$,
$67\equiv4 \mod 9$, hence it has order $3$ modulo $9$
$67\equiv1 \mod 11$.

The order of $67$ modulo $990$ is the l.c.m. of its orders modulo $\;2,5,9$ and $11$: $\;\color{red}{12}$, and
$$67^{26^{42^{23}}}\mod 990=67^{26^{42^{23}}\bmod12}$$
Value of the exponent modulo 12:
First observe $26\equiv 2\mod 12$; it is easy to check that, if $n\ge 2$,
$$2^n\equiv\begin{cases} 4\mod 12&\text{if $n$ is even,}\\8\mod 12&\text{if $n$ is odd.}
\end{cases}$$
We conclude that $26^{42^{23}}\equiv2^{42^{23}}\equiv 4 \mod 12$, and
$$67^{26^{42^{23}}}\equiv 67^4\equiv 661\mod 990.$$


How to get information about an SQL Select statement

Question: I am wondering if it is possible to get the real name of the tables/fields from which each field in a select statement comes from.
Lets say you have two tables, Creditors and Debtors both have the fields Code, Name and Phone.
If a user enters the following sql statement:
<code>SELECT Code AS CustomerCode, Name AS CustomerName, Phone AS ContactNumber FROM Debtors.
</code>
This will result in SQL server returning field names CustomerCode, CustomerName and ContactNumber.
Is it possible to get from the SQL server some sort of meta data that maps each field to its real name and the table it comes from?
Programmically, given an SQL select statement, I want to be able to determine the real name of each field and the real name of the tables they come from.
I don't want to parse the SQL myself so I thought that there might be away to send the statement to the sql server and get back this information without the row data.
What we are trying to do is implement table/field level security. A user can enter an sql statement to select fields from a table or across multiple tables (using joins) and have the results displayed in a table.  The fields get added dynamically to a grid control but only the ones that the user is allowed to see.
If the user joins multiple tables how do we know programmically which fields come from which table? the problem gets worse if they use aliases in the SQL.
Currently this is working on a legacy in house built sql engine (that uses a proprietary database) which can return all of the required table/field information without the row data so part of the applications security model is built around this.  However moving this application to something like SQL server might prove difficult if we can't get this to work.
Besides Sql server, do any other sql databases support this type of functionality?
Comment: This is tricky to do in a general way because result set columns don't always map directly back to table columns.  (in fact, they frequently don't).  You could have a result column that's the sum of values in rows in table A and table B.  Or, you could have a table who's data is used for a join that's not shown in the result set.
Answer: To the best of my knowledge, you cannot get that information.
You can probably handle your problem in many databases, however, by using GRANT / REVOKE security in the database itself.  Assuming that users are logging into the database itself (not just your application), many DBMSes allow you to GRANT SELECT privileges on restricted columns from a table.  Using that technique, it will not fool the server if the user specifies ALIASes for columns.
A quick google indicates that at least PostgreSQL, SQL Server, and Oracle offer column level GRANT SELECT protection based on userid.
Interesting question, by the way.
Comment: +1. Good answer, but I would personally try to avoid granting column permissions in all but the simplest cases.
Comment: Me too, but presumably the OP really does need to do this and apparently already _is_ doing it in the application code.  If he can move it to the database layer, I can't imagine it will be any _harder_ to maintain (he can repurpose the existing management front end to use GRANT and REVOKE).  If he _really_ needs to do it, most databases will already handle it.
Comment: Using grant/revoke sounds like that way we need to go, thanks for that.  One more problem is that a user can write a query and then drill down on the results returned.  For example, a user writes a query to select invoices from the invoice table (invoice number, invoice date, customer name, total gross, total tax).  If you user then double clicks on the row the application looks at the first column and figures out that this column came from the invoice table.
Comment: Based on the table and field name it knows to launch the invoice details screen passing it the invoice number which will in turn display the transactions that make up the invoice. If a user has used aliases and if we can't get the real table/field involved in the select then I don't see how this could work on sql server. Any suggestions?
Comment: After a bit of googling I found this on microsofts site SqlDataReader.GetSchemaTable. The GetSchemaTable method returns a dataset containing the resultset meta data for a select statement. This includes the name of the column as returned in the result set, the real name of the column and store in the table and the real name of the table. This seems to be supported by sql server, I wonder if other database support it.
Comment: The Enterprise class SQL servers have had row level and column level security for many years, downstream it is new (MS 2008, still figuring outhow to do it). Extensions to the SQL standard security model.  Absolutely no performance impact. They also handle column level encryption, but that costs a little.
Comment: @no spoon.  All that is handled by SQL.  The problem is, you have been doing that in app code, which is the wrong place to implement security.  If you stop doing that, and do normal GRANT/REVOKE per table per LOGIN, the problem disappears.
Answer: No. The whole point is you should only know the name presented to you and not where it came from.
The way to solve your problem is to remove all access from tables and only grant access through views with appropriate access permissions.
Comment: That doesn't strike me as having the granularity that the OP is requesting.
Comment: column permissions are indeed possible in MS SQL 2k8; but managing them can be, lets say, interesting.
Comment: also note: A table-level DENY does not take precedence over a column-level GRANT. This inconsistency in the permissions hierarchy has been preserved for backward compatibility. http://msdn.microsoft.com/en-us/library/ms188371.aspx
Comment: Presumably, they're already dealing with the issue of handling permissions on the column level already, just with the added complexity of doing it themselves.  But I agree, _any_ column level permission management will be time consuming and, probably, error prone.
Comment: "Backward compatibilty" (not your post, but the MS statement) is bulldust.  Sybase and DB2 implemented it years ago, on top of the SQL Standard security model, with no issues whatsoever. The simple truth is 2008 is a new codeline, land it has many bugs that 2005 did not have; like when 2005 was new and had many bugs that 2000/6.5 did not have.  New codelines are hilarious, but MS types buy it.  In the Sybase DB2 Enterprise market, we never throw out precious code, we just keep adding to it, because the structure allows it.


Let A a subset of X be a finite dimensional linear subspace. Show that A is complete

Question: Let X be a normed space. Let A a subset of X be a finite dimensional linear subspace. Show that A is complete (even if X is not).
Using the above show that A is a closed subset of X.
For the first part do I need to generalise it to $\mathbb{R^n}$ or is there a quicker way?
I think I can do the second bit.
Answer: Given a basis for $A$, the components in that basis give a vector $x(y)$ of $\mathbb R^n$ for each $y\in A$, where $n$ is the dimension of $A$. Note that a sequence $y_n$ in $A$ is a Cauchy sequence if and only if $x_n=x(y_n)$ is a Cauchy sequence in $\mathbb R^n$. From now on you can thus proceed as if $A$ was $\mathbb R^n$. This implies that $A$ is complete (because $\mathbb R^n$ is complete, with respect to any norm, since all norms are equivalent) and so it is also closed (since any convergent sequence is a Cauchy sequence and so has a limit in the space).
Added:
On the claim "a sequence $y_n$ in $A$ is a Cauchy sequence if and only if $x_n=x(y_n)$ is a Cauchy sequence in $\mathbb R^n$". Let $v_1,\ldots,v_n$ be a basis of $A$, say with $\|v_i\|=1$ for each $i$. Given a vector $v\in A$ one can write $v=c_1v_1+\cdots+c_nv_n$ in a unique manner. This gives the bijection $v\mapsto (c_1,\ldots,c_n)$ from $A$ onto $\mathbb R^n$.
Now let $w_k$ be a sequence in $A$ and write $w_k=c_1(k)v_1+\cdots+c_n(k)v_n$. Note that
$$
\|w_k-w_l\|\le \sum_{i=1}^n|c_i(k)-c_i(l)|
$$
and so if $(c_1(k),\ldots,c_n(k))$ is a Cauchy sequence in $\mathbb R^n$, then $w_k$ is a Cauchy sequence in $A$. Let me leave as an exercise showing that the converse also holds (hint: all norms on $\mathbb R^n$ are equivalent).
Comment: If you understand my answer, you can detail it as much as you may need. It really depends for what you want it,as I wrote it is fine for a book, perhaps not if it is homework... Of course, it is always more difficult to write mathematics in a short manner while still complete, but often not much appreciated in homework...
Comment: Could you make it more formal please. I do not understand what you mean by components in that basis..
Comment: Components of $v$ in a basis $e_1,\ldots, e_n$ are the numbers $c_1,\ldots,c_n$ such that $v=c_1e_1+\cdots+c_ne_n$, right?
Comment: So I don't have to prove anything just state the basis and the theorems?
Comment: Ok so I have a basis with dimension n. The components (the scalars) form a vector x(v) of R^n for each v in A. Now I have to show cauchy convergence? Or is that iff to show A can be assumed to be R^n?
Comment: Your choice, depending on what it is for. But note that $x(v_k)$ is a Cauchy sequence if and only the components, say $(c_1(v_k),\ldots,c_n(v_k))$, form a Cauchy sequence in $\mathbb R^n$. Depending on what it is for, you may also want to prove this statement!
Comment: I have not actually come across that theorem , is there any other way?
Comment: Not a theorem, much simpler. I will a few details to my answer.
Comment: What is the vk inside the components and the k?
Comment: I'm sorry to say, but you really need to make an effort. Especially if this is homework.
Comment: I'm confused about your notation. In your comments you said c1(vk) but in the answer you said c1(k)?
Comment: I see. I changed the notation in the answer, because it was convenient due to the rest of the notation. It is better to look only at the answer.
Comment: Why is it closed. I only have a lemma for banach spaces (but x does not have to be complete here).


Entity Framework vs SQL Injection (segurança?)

Question: Olá! Sou novato em desenvolvimento então me desculpem se a pergunta for boba. Se for agradeço link's com referências para que eu possa me informar melhor.
Por mais que tenha entendido o conceito e a utilização de SQL injection não consigo ter malícia suficiente para imaginar ataques e utilizações práticas, aí fico preocupado com a segurança do meu aplicativo. Estou desenvolvendo em .NET ASP MVC com C# e acesso a dados com Entity Framework. Li que o melhor método para evitar o famigerado SQL injection é utilizar store procedures para tudo. Mas fazer isso com Entity Framework, me parece, acabaria por retirar toda a praticidade dessa ferramenta.
Então vem minha dúvida. Se faço uma entidade assim:
<code>public class Cliente
{
    public int ClienteID { get; set; }
    public string Nome { get; set; }
    public string CNPJ { get; set; }
    public string Telefone { get; set; }
}
</code>
E crio um Controller padrão, utilizando Scaffolding onde tenho uma action Edit:
<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="ID,Nome,Cnpj,Telefone")] Cliente cliente)
{
    if (ModelState.IsValid)
    {
        db.Entry(cliente).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(cliente);
}
</code>
Estou sujeito a SQL Injection se meu usuário digitar uma cláusula Insert ou Delete no campo Nome da minha View? Se sim, como me prevenir disso?
Vejo um monte de tutoriais e cursos ensinando assim, mas ninguém comenta sobre questões de segurança.
Answer: Quando usamos LINQ to Entities é livre de SQL Injection sim. Eu não tenho certeza quando ao uso de ADO.NET.
Enfim. Do jeito que está fazendo não é possível injetar códigos SQL.
Comment: Obrigado @Manaces Você entende bem de segurança? Poderia me indicar algum texto para que eu me informe melhor?
Comment: Tem a própria documentação aqui: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/ef/security-considerations
Comment: Desde que não use nada de SQL. Segurança é algo extremamente complexo e não será um texto que ajudará muito. Na verdade costuma atrapalhar, porque é comum a pessoa ler algo e achar que já sabe o que precisa.
Comment: @bigown Kkkkk! Pois é, principalmente quando temos pressa e hoje em dia tudo parece urgente, temos que dar um jeitinho agora e "depois vemos melhor". Mas por algum lugar tenho que começar certo? Eu já até me interessei por seguir carreira em segurança de TI, mas não conheço nenhum curso ou nada que dê o caminho das pedras para isto.


Google App Script HTML table styling

Question: I've created a function within GAS that takes data from google sheets and sends out individual emails based on a specific person; the function then loops to the next person and continues through the data.
What I am having issue with now is formatting the HTML table that I've created by looping through the data.  When I run this the data shows up in a table format but I am unable to add borders, color, ect.  I currently have the styling under the TABLEFORMAT variable but I've also tried putting the style tags within the table, th, td, tr tags, but it just seems to ignore it.  However, I put the output into an HTML simulator and it comes out the way I want it.
Does anyone know why this wouldnt work with a gs file?  Also, I'm trying to get cashGoalPosition to be in dollar format.  Thanks in advance for the help; I've been racking my brain with this and can't seem to figure it out.
function Auto_Email(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var shData = ss.getSheetByName("E-mail Data");
  var shEmail = ss.getSheetByName("E-mail List");
  var dataRange = shData.getDataRange(); // Fetch values for each row in the Range.
  var emailRange = shEmail.getDataRange(); //fetch values for email list
  var data = dataRange.getValues();
  var nameData = emailRange.getValues();
  var lastCol = dataRange.getLastColumn();

   for (var i = 1; i < nameData.length; i++) {
      var rows = nameData[i];
      var emailAddress = rows[2];//position of email header -1
      var fullName = rows[1]; //position of name header -1
      var firstName = rows[3]// the first name only
      var cashGoalPosition = rows[0].toString(); //position of billing goal -1
      var subject = firstName+"'s Cash Goal";
      var htmltable = '';
      var htmlmessage = "";
     var TABLEFORMAT = '<!DOCTYPE html>'
      var pre_html = '
Dear '+firstName+',

Your new balance is '+cashGoalPosition+'. Below is a list of the invoices past due or due in the current month.

'
      var post_html = '
Regards,
John
'

      for (row = 0; row<data.length; row++)
      {
        for (col = 0 ;col<data[row].length; col++){
          if (row == 0 && col == 0) {htmltable += '
' + data[row][col] + '	';}
          else
            if (row == 0 && col == lastCol - 1) {htmltable+= '' + data[row][col] + '
';}
          else
            if (row == 0) {htmltable+= '' + data[row][col] + '	';}
          else
            if (data[row][0] == fullName && col == 0) {htmltable += '
' + data[row][col] + '	';}
          else
            if (data[row][0] == fullName && col == lastCol -1) {htmltable += '' + data[row][col] + '
';}
          else
            if (data[row][0] == fullName) {htmltable += "" + data[row][col] + "	";}
}

      }

     htmltable += '

';
     htmlmessage = TABLEFORMAT + pre_html + htmltable + post_html;

     Logger.log(htmlmessage)
MailApp.sendEmail(Session.getActiveUser().getEmail(), subject,'' ,{htmlBody: htmlmessage})
      }(i);
   }

Comment: What do you mean by "but it just seems to ignore it"? What email client are you using to read the email message sent?
Comment: I'm sending it through gmail. What I mean by "ignore it" is that the table is plain and doesn't follow the styling that I set. However, Tanaike's suggestion worked. I must have been doing something wrong because I tried the way he suggested and couldn't get it to work. Must have had it off slightly. Thanks for the input Tanaike. Any idea on an easy way to set the numbers as currency?
Answer: It seems that  and
 can be converted to
.
The modified script is as follows.
From :
var TABLEFORMAT = '<!DOCTYPE html>'
var pre_html = '
Dear '+firstName+',

Your new balance is '+cashGoalPosition+'. Below is a list of the invoices past due or due in the current month.

'

To :
var TABLEFORMAT = '<!DOCTYPE html>'
var pre_html = '
Dear '+firstName+',

Your new balance is '+cashGoalPosition+'. Below is a list of the invoices past due or due in the current month.

'

If I misunderstand your question, I'm sorry.

Google App Script HTML table styling


Como instanciar um objeto de acordo com um evento do Front End?

Question: Boa tarde, Pessoal.
Não sei se minha pergunta faz muito sentido, mas lá vai.
Por exemplo, eu tenho uma classe que tem diversas funções, e tenho o meu Index.php
Ai vamos lá, quando eu carrego o index e preciso executar um método de uma classe, como eu faço pra instanciar o objeto dessa classe e executar a função de acordo com uma ação do usuario? Por exemplo, quando o usuário clicar num botão ele vai instanciar o Objeto e executar determinada função.
Ex:
Classe:
<?php
 class usuario{

 private nome;

 public function getNome(){
  return $this->Nome;
 }
}
?>

Index:
...
$usuario = new usuario();
$usuario->getNome();

...
Answer: Se eu entendi direito, você quer passar um valor de uma ação pra saber o que fazer depois. Normalmente se passa parâmetros por $_GET na url, $_POST via formulário ou quebrando a url quando se usa url amigável.
Passando uma ação através de um link a lógica é a seguinte:
Link:
Carregar usuário

Código php:
if(isset($_GET["acao"]))
{
    if($_GET["acao"]=="carregausuario")
    {
        $usuario = new usuario();
        $nome = $usuario->getNome();
    }
}

Depois é só dar um echo $nome; no lugar que tiver que exibir esse nome.
Comment: Perfeito, então ele só vai gerar o objeto se existir o POST/GET correto?
Comment: Sim. Nesse exemplo o objeto só será criado se existir o  get "acao" e se o valor desse get "acao" for igual a "carregausuario".
Answer: Do HTML você não consegue executar um código PHP.
O que você pode fazer é utilizar o javascript para fazer uma requisição http para um script PHP que execute o que você quer.
Você pode fazer uma chamada como no código abaixo na ação que você queira.
$.ajax({
    type: 'POST', // Ou GET
    url: 'arquivo-com-acao-desejada.php'
});

Comment: Isso não faria com que eu tivesse de já deixar os objetos instanciados? O que eu quero saber é como instanciar o Objeto de acordo com a ação do usuario.


How do I insert spaces back into string after removing them

Question: I am trying to :
1) Remove spaces from a given string
2) From the removed spaces string, insert the spaces to where they were original
3) Final result should be the original text.
string original = "The quick brown fox jumps over the lazy dog";
    string removeSpace, withSpace;
int foo[8];
int count = 0;

cout << original << endl;

for (int i = 0; i < original.size(); i++)
{
    if (char(int(original[i])) == 32)
    {
        foo[count] = i;

        count++;
    }
    else
    {
        removeSpace += original[i];
    }
}
cout << endl;
for (int i = 0; i < 8; i++)
{
    cout << "Spaces at : " << foo[i] << endl;
}
cout << "==========With spaces remove==========" << endl;
cout << removeSpace << endl;
count = 0;

for (int i = 0; i < removeSpace.size(); i++)
{
    if (foo[count] == i)
    {
        withSpace += ' ';
        count++;

    }
    withSpace += removeSpace[i];
}

cout << "==========With spaces inserted==========";
cout << "\n" << withSpace << endl;

This is what i am getting:
The quickb rownfo xjum psover thela zydo g
How do I insert them back to make it
"The quick brown fox jumps over the lazy dog"
Answer: It's clear what the problem is from looking at your output. In foo you are storing the indexes of the spaces before any spaces have been removed. But when you put back the spaces you are comparing foo with i which is the index after the spaces have been removed. This is not a meaningful thing to do. You just need to adjust your algorithm to account for this difference.
Here's a minimal adjustment to your code that fixes the problem. By comparing foo[cout] with the size of the withSpace string I'm comparing like with like. Both foo[count] and withSpace.size() are indexes and sizes of the string after spaces have been added.
for (int i = 0; i < removeSpace.size(); i++)
{
    if (foo[count] == withSpace.size())
    {
        withSpace += ' ';
        count++;
    }
    withSpace += removeSpace[i];
}

Full code here.
This code
if (char(int(original[i])) == 32)

is a good example of doing a simple thing in a complicated way. This is better
if (original[i] == ' ')


AWS CodeDeploy to second subnet fails

Question: I'm experiencing some issues these days with CodeDeploy and EC2 instances. I have a VPC with two public subnets (VPC: 10.0.0.0/16 , subnet1: 10.0.0.0/24, subnet2: 10.0.1.0/24), both having assigned an internet gateway. I deploy an EC2 instance to both of them with the correct roles. The problem I have though, is that when using CodeDeploy to deploy to the instance in the first subnet (10.0.0.0/24) it works all the way but when I do the same thing to the instance in the second subnet it remains stuck in pending with no step completed and then times out. Both subnets seem to be the same as configuration but I have no idea why CodeDeploy works with the first one but not the second.
Do you have any idea? What could I check? Is there an obvious reason why it fails?
Answer: Nothing obvious from your description so just a couple of points to check:

Are both EC2 instances registered in the same Deployment Group?
Is the CodeDeploy agent running on the 2nd instance?
Are they both in the same Security Group?
Are they both built from the same AMI using the same automation script? E.g. through AutoScaling Launch Config? (this is to ensure that both EC2 are 100% identical)
What if you create another instance in the 1st subnet - would deployment to that work? (this is to determine whether any second deployment fails or if it's caused by the subnet configuration)
What deployment type do you use? Maybe the first deployment isn't successfully completed so the second one never starts. Can you try all-at-once deployment that kicks of on all instances at the same time?

Either the instances are not identical, or the subnets have different config, or security settings are not identical, or something else is different between them.
Update: Or your AMI has a built-in configuration made for a specific AZ or subnet, as it turns out. AMIs should auto-configure from DHCP when they launch. They shouldn't have any network-related settings hardcoded, that way they will be usable in different subnets and AZs.
Hope that helps :)
Comment: @Andrew that's really odd. The subnets must have different settings - route tables, IGW attachment, automatic public IP assignment, DNS / DHCP options, something like that. Or some IAM policies that specify 10.0.0.0/24? CodeDeploy is definitely not restricted to any IP addr.
Comment: @Andrew Are the CodeDeploy agents successfully connected to the service on both instances? I don't have CodeDeploy stack at hand now but I guess it's visible in the console and also in some log files on the instance. Also while you're looking at the log files is there any sign of any activity in the logs on the non-working instances during deploy attempt?
Comment: Thank you. Checked and everythung is fine. Also deleted both subnets and created only the one 10.0.1.0/24 and it doesn't work. But as soon as I add the second one now 10.0.0/24 it does.
Comment: New test. Created a new vpc altogether (10.0.1.0/24) with only one subnet 10.0.1.0/24. Ad it doesn't work. Apparently it only works when instance in 10.0.0.0/24
Comment: route table is the same one (thus same IGW assigned to both), automatic public IP assignment disabled for both (the instances have it enabled), IAM policies are administrator level to avoid any issue due to that.
Comment: I dug more and I discovered that the image I used was made for a specific availability zone. When I created the instance in another availability zone based on that image the machine wouldn't know how to handle the network and thus code deploy failed as well. So no issue at network level, it was machine and agent related ultimately. Thank you for help!
Comment: @Andrew Glad that you figured out the root cause. I have added that to the response. If you can upvote it and accept as correct that'll be much appreciated :)

AWS CodeDeploy to second subnet fails


How do I reference a AWS Service-Only User config within a Lambda (separate from the User/config I used to deploy the Lambda)?

Question: So I have one IAM Profile/User that I am using to deploy a Lambda function, but this Lambda function needs to instantiate a new AWS Session to connect to a whitelisted S3 bucket. Each of these users have distinct Keys, Secrets, and coordinated policies that are set up for their distinct purposes.
I cannot set the profile in my serverless.yaml to the S3 configuration, as I won't have adequate permissions to deploy the Lambda. How can I in-code reference a distinct aws.Config{}? Ideally, I do not want to statically store the keys/secret for the S3 configured IAM in Parameter Store but that's all I can think as of now.
Comment: Usually you add such permissions to lambda execution role.
Comment: That was not an option has the user arn was whitelisted to a third party s3 bucket
Answer: I ended up using Secrets Manager to store the Access Key and Secret Access Key for my user ARN. When initiating my AWS Session, I would pull the credentials from AWS Secret Manager and use the static credentials configuration option. It is not an ideal implementation but it worked.


Como tratar esse código array com php?

Question: Tenho uma dúvida, de como tratar esse array:
["*original"]=>

array(13) {
["id"]=>
int(1)
["user_id"]=>
int(3)
["reference"]=>
string(36) "c8d2076672c9631e8c048589f3a9a26f3961"
["status"]=>
string(8) "Pendente"
["paymentMethod"]=>
string(2) "ph"
["date"]=>
string(10) "2018-08-30"
["paymentLink"]=>
string(195) ""
["created_at"]=>
string(19) "2018-08-30 17:41:39"
["updated_at"]=>
string(19) "0000-00-00 00:00:00"
["pacote"]=>
int(1)
["tipo"]=>
string(20) "Ativação de pacote"
["valor"]=>
float(0)
["transaction_id"]=>
NULL

}
Precio recuperar o array transaction_id, porém o atributo ["*original"] não deixa, por causa desse asteristico.
Alguém pra resolver comigo?
Answer: Teoricamente seria isto:
$recuperado = $var["*original"]["transaction_id"];

var_dump($recuperado);

Mas como teu array mostra NULL:
["transaction_id"]=>
NULL

Então o valor é nulo.
O asterisco não atrapalha em nada, veja o teste: https://ideone.com/cPnbtZ, provavelmente o problema é no valor null ou algo que você fez errado na sintaxe do seu código pessoal
Comment: assim não vai não
Comment: undefined *original
Comment: @AlissonMaciel se não vai é porque você esta com uma variavel diferente, ou algo assim, no link que enviei mostrei, funciona, o problema é algo que você fez, provavelmente o array deve ter mais dimensões.

Como tratar esse código array com php?


Drupal CRM Core releases

Question: I'd like to install CRM Core module for one of my clients. But I cannot decide which release to use - stable or development. The Recommended release (7.x-0.964) looks more confusing to me while the Development release (7.x-1.x-dev) looks more logical. But I don't know if there any risks of using Development release in production.
Could you please advise the right way to go.
Thanks in advance!
Comment: Why does it look more confusing to you?
Answer: The fact that the stable release has an unusual version number doesn't mean there is anything wrong with it.
It's just the way they are doing there releases.
If you look at all the crm core releases you can see that the first stable release was 0.9.
I would guess they have done this so that they may be able to get more people using it and fix any issues that arise before having a 1.0 release.
So 1.0 will be the next major release.
Then they use versions 0.91, 0.92, 0.93, ... as the intermediate level releases and for minor releases in between those they use numbers like 0.911, 0.912, 0.913, ....
When choosing a version of any module this would be my advice:
Use the latest stable release.
If you encounter any problems with latest stable then check the issue queue for possible fixes and if you need a patch to apply to latest dev or latest dev has already fixed the problem then try using it.
Remember though to test to make sure everything still works as it should as the dev version may have introduced new issues even though it fixed your previous issue.
Also take a database backup before updating module versions in case the newer version is broken and you need to roll back.
Another reason you might want to use dev would be if you know that there are new features in dev that you want that aren't in the latest stable.
But really, if there is a stable release (especially a recommended stable), don't use the dev version instead of the stable release unless you have a good reason to.
Unusual version numbering is not a good reason.
Comment: Hi Rooby, Thanks a lot for your comments. I think I'll follow your advise and will take the latest stable release for the project.

Drupal CRM Core releases


Get view result depending on pager url

Question: In drupal 7 ,this returns the results of the view first page, if using a pager:
Is there a way to get the results depending on the page? (depending on url argument maybe?)
<code>$result = views_get_view_result('viewname', 'displayname');
</code>
Answer: I didn't test the code. But you can use this code.
<code>$page = 1;
$view = views_get_view('payment_schedule_students');
$view->set_display('payment_schedule_students_select');
$view->set_current_page($page);
$view->execute();$view->result;
</code>
Where you can set the <code>$page</code> variable from the url.

Get view result depending on pager url


Approximating lognormal sum pdf (in R)

Question: I have an application for which I need an approximation to the lognormal sum pdf for use as part of a likelihood function.  The lognormal sum distribution has no closed form, and there are a bunch of papers in signal processing journals about different approximations.  I have been using one of the simplest approximations (Fenton 1960), which involves replacing a sum of lognormals with a single lognormal with matching first and second moments.  This is pretty straightforward to code, but judging by the literature on the subject that has been written in the last 50 years, this may not be the best approximation for all applications.  I have no intuition for how to identify which approximations will lead to the best MLE estimates.
Does anyone know if
(A) There is different approximation I should be using for a maximum likelihood application?
(B) There is existing R code for any of the more computationally intensive approximations?
Update: For some background on the problem, see this review
Comment: Moment matching a lognormal to this sounds on the surface like a strange idea. This is because the lognormal is *not* characterized by its moments. I will look here, but perhaps there is a way to turn the problem around a little. Let $f_0(x)$ be a "standard" ($\mu = 0$, $\sigma = 1$) lognormal density. For $b \in (-1,1)$, define $f_b(x) = f_0(x) (1 + b \sin(2\pi\log x))$. Then $f_b$ is a pdf and $f_0$ and $f_b$ have the same moments for *every* such $b$.
Comment: Can you clarify just a touch? Is what you refer to as the "lognormal sum pdf" the density function of $Y = X_1 + \cdots + X_n$ where $X_n$ are iid lognormal with parameters $\mu$ and $\sigma^2$?
Comment: Yes, the pdf for the sum of N iid lognormal variates.
Comment: How large is $n$ in your application?
Comment: I am most interested in the cases where N is small, < 10 or so.  However, it would be very helpful if I could at least manage N up to 100 or so.
Comment: From the papers I have read on this, it looks like this approximation works well in the right tail, but less well elsewhere.  See [this review](http://www.soa.org/library/proceedings/arch/2009/arch-2009-iss1-dufresne.pdf) for some discussion on the history of the problem.
Comment: So, since you're summing iid copies of the same random variable, the lognormal sum distribution has moments that match the moments of the $f_b$. Generalizing further, we can take $\hat{f}(x) = f_0(x)(1 + \sum_k b_k \sin (k \pi \log x))$ and get the same moments as well as long as $\sum_i |b_i| \leq 1$. This may allow for some degrees of freedom to get an approximation while keeping **all** the moments equal.
Comment: It doesn't look like any of the methods in that review are quite what I've outlined above. That's not to say that it or some other paper hasn't looked at such a method. (I'd actually guess that it has been considered somewhere.)
Comment: Thanks for your help, I will look into the approach you suggest.
Comment: I'll keep thinking about this. It's likely some others here will have some suggestions as well. If I come up with anything worthy of an actual "answer", I'll be sure and post it.
Comment: It seems like the lognormal distribution is 'product stable' (in analogy to the 'sum stable' class of distributions).  It seems that this property is shared by the sum of lognormals.  Perhaps there is some clever characterization of the product stable distributions (as there is of the sum stable class). Or maybe this is a dead end...
Answer: To obtain a numerical version of distribution function for moderate $N$ (say a dozen of r.vs or less), a simple approach is to compute the Discrete Fourier Transform (DFT) of each LN density, form the product and then use inverse DFT. The same grid must be used for all densities and it must be designed with some care. The computation can be done quite easily in a R function. However, do not expect to reach the remarkable precision of the classical distributions functions in R.

Approximating lognormal sum pdf (in R)


Div acting like panel

Question: I have a div with grooved border.
I want it to look like this panel: http://www.devmanuals.com/images/images1/444Panel1.gif
The panel on the image has title "User registration".
How to make my div has a title like the panel?
Comment: post what you have tried
Answer: That is called a fieldset, and it is a basic HTML tag.
  <fieldset>
    <legend>User Registration</legend>
    User name: <input type="text" />

    Password: <input type="text" />

  </fieldset>

I cringe at giving you a link to this site, but it does have the ability for you to try out your HTML right there.
Answer: Try a "fieldset":
<fieldset>
    <legend>caption goes here</legend>
</fieldset>

Answer: You could do some styling on the fieldset.
Stylesheet.css
fieldset.panel
{
    border: 1px solid #000;
    width: 200px;
}
fieldset.panel input[type=text]
{
    width: 170px;
}

Usage
<fieldset class="panel">
    <legend>User Registration</legend>
    User name:
<input type="text"/>

    Email-id:
<input type="text"/>

    Password:
<input type="text"/>

    Confirm password:
<input type="text"/>

    <input type ="submit" value="Register"/>
</fieldset>

Basically it's using a fieldset but with some basic styling, the css class panel will make the border 1px solid black and the inputs are all going to be 170px width, since the css style will only be applied to the inputs which type is text and being inside a fieldset whose class attribute is panel, translated to css like this: fieldset.panel input[type=text].

Div acting like panel


What are bundles? Can we create custom bundles?

Question: Does all nodes have bundles? Also can we create custom  bundles?
Answer:
Bundles are an implementation of an entity type to which fields can be
  attached. You can consider bundles as subtypes of an entity. With
  content nodes, for example, you can generate subtypes like articles,
  blogs, or products. Not all entity types have bundles, however. For
  example, users do not have separate bundles or subtypes. With bundles,
  you can have as many subtypes as you want. Then, using the Field
  system, you can add additional fields to those bundles such as file
  download field for Articles and location fields for Users.

Read more here and a good article that i found. Hope it helps :-)


Google places details Json response parsing stops when a value is blank

Question: I am trying to parse a JSON response received from google places details, and trying to populate a custom object.
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONObject placeDetailsJsonArray = jsonObj.getJSONObject("result");

googlePlaceDetails placeDetails = new googlePlaceDetails();

placeDetails.placeName = placeDetailsJsonArray.getString("name");
placeDetails.placeAddress = placeDetailsJsonArray.getString("formatted_address");
placeDetails.vicinity = placeDetailsJsonArray.getString("vicinity");
placeDetails.phoneNo =placeDetailsJsonArray.getString("international_phone_number");
placeDetails.website =placeDetailsJsonArray.getString("website");
placeDetails.socialPage = placeDetailsJsonArray.getString("url");
placeDetails.rating = placeDetailsJsonArray.getString("rating");

JSONObject geometry = placeDetailsJsonArray.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");

placeDetails.lat = location.getString("lat");
placeDetails.lng = location.getString("lng");

the class GooglePlaceDetails is very simple with just few String values
public class googlePlaceDetails {
String placeName;
String placeAddress;
String vicinity;
String phoneNo;
String website;
String socialPage;
String rating;
String lat;
String lng;
}

The code works fine when all the values are present in the JSON response, but when one value is not present (say International Phone number), then the code throws exception, and the remaining values are not processed at all.
Here is a sample JSON response which does not have the international phone number.
LOGCAT:
org.json.JSONException: No value for international_phone_number
        at org.json.JSONObject.get(JSONObject.java:355)
        at org.json.JSONObject.getString(JSONObject.java:515)
        at manasthemarvel.travelflow.PlaceAPI.getPlaceDetails(PlaceAPI.java:83)
        at manasthemarvel.travelflow.placeInfoMap.doInBackground(place_info.java:107)
        at manasthemarvel.travelflow.placeInfoMap.doInBackground(place_info.java:103)
        at android.os.AsyncTask$2.call(AsyncTask.java:288)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:841)

How do I skip a value when it is not present and continue parsing the remaining values?
Answer: I solved my problem by creating a method for checking if the value exists.
private String checkEmptyJsonResponse(JSONObject jsonArray, String jsonKey)
{
    try {
        if (jsonArray.has(jsonKey))
            return jsonArray.getString(jsonKey);
    }
    catch (JSONException e) {
        Log.e(TAG, "Cannot process JSON results", e);
    }

    return "Not Available";
}


Troca de servidor de hospedagem para sites

Question: Um colega meu quer passar o site dele para o servidor que hospedo os meus sites. O que eu gostaria de saber é oq realmente eu preciso para que essa troca seja feita? A agência que detém o site, domínio e hospedagem dele deve alterar o DNS para o meu servidor, correto? Se sim, não corre-se o risco de a qualquer momento eles trocarem esse dns causando uma queda no site? O que fazer para que isso não ocorra? Além do mais, meu colega possui os e-mails pelo gsuite, então, uma troca de domínio não é viável pois ele possui muitos clientes. Eu precisaria que tanto o domínio quanto a hospedagem ficassem sob minha responsabilidade e não que a outra empresa tivesse qualquer tipo de acesso ou vínculo após a troca.
Answer:
(sic) oq realmente eu preciso para que essa troca seja feita?
  A agência que detém o site, domínio e hospedagem dele deve alterar o DNS para o meu servidor, correto?

Deve sim apontar o domínio para seu servidor.

não corre-se o risco de a qualquer momento eles trocarem esse dns causando uma queda no site?

Esse é um risco praticamente "certo". Quando apontar o domínio para o seu servidor, vai ter um tempo de propagação que, normalmente, é de até 72 horas. Essa propagação vai acontecendo aos poucos e pode ser liberado antes em determinadas regiões.

O que fazer para que isso não ocorra?

Mantenha uma réplica do site no servidor antigo e não suspenda-o até o término da propagação. Vale lembrar que o banco de dados deve ser o mesmo para ambos os servidores. Logo, se o site está no mesmo servidor (atual), o site novo deve apontar para o banco de dados do servidor antigo. Quando passar o tempo de propagação, basta migrar seu banco de dados e reconfigurar o servidor novo com esse banco de dados. Assim você só vai ficar com o site em manutenção enquanto somente estiver migrando...

Eu precisaria que tanto o domínio quanto a hospedagem ficassem sob minha responsabilidade e não que a outra empresa tivesse qualquer tipo de acesso ou vínculo após a troca.

Basta solicitar à empresa que gerencia o domínio atualmente.