text:
Q: Why are stackoverflow errors chaotic? This simple C program rarely terminates at the same call depth:
#include <stdio.h>
#include <stdlib.h>

void recursive(unsigned int rec);

int main(void)
{
  recursive(1);
  return 0;
}

void recursive(unsigned int rec) {
    printf("%u\n", rec);
    recursive(rec + 1);
}

What could be the reasons behind this chaotic behavior?
I am using fedora (16GiB ram, stack size of 8192), and compiled using cc without any options.
EDIT

*

*I am aware that this program will throw a stackoverflow

*I know that enabling some compiler optimizations will change the behavior and that the program will reach integer overflow.

*I am aware that this is undefined behavior, the purpose of this question is to understand/get an overview of the implementation specific internal behaviors that might explain what we observe there.

The question is more, given that on Linux the thread stack size is fixed and given by ulimit -s, what would influence the available stack size so that the stackoverflow does not always occur at the same call depth?
EDIT 2
@BlueMoon always sees the same output on his CentOS, while on my Fedora, with a stack of 8M, I see different outputs (last printed integer 261892 or 261845, or 261826, or ...)

A: You won't have the same behaviour between executions because it depends on the current memory available. The more memory you have available, the further you'll go in this recursive function.

A: Your program runs infinitely as there is no base condition in your recursive function. Stack will grow continuously by each function call and will result in stack overflow.
If it would be the case of tail-recursion optimization (with option -O2), then stack overflow will occur for sure. Its invoke undefined behavior.

what would influence the available stack size so that the stackoverflow does not always occur at the same call depth?

When stack overflow occurs it invokes undefined behavior. Nothing can be said about the result in this case.

A: Change the printf call to:
printf("%u %p\n", rec, &rec);

This forces gcc to put rec on the stack and gives you its address which is a good indication of what's going on with the stack pointer.
Run your program a few times and note what's going on with the address that's being printed at the end. A few runs on my machine shows this:
261958 0x7fff82d2878c
261778 0x7fffc85f379c
261816 0x7fff4139c78c
261926 0x7fff192bb79c

First thing to note is that the stack address always ends in 78c or 79c. Why is that? We should crash when crossing a page boundary, pages are 0x1000 bytes long and each function eats 0x20 bytes of stack so the address should end with 00X or 01X. But looking at this closer, we crash in libc. So the stack overflow happens somewhere inside libc, from this we can conclude that calling printf and everything else it calls needs at least 0x78c = 1932 (possibly plus X*4096) bytes of stack to work.
The second question is why does it take a different number of iterations to reach the end of the stack? A hint is in the fact that the addresses we get are different on every run of the program.
1 0x7fff8c4c13ac
1 0x7fff0a88f33c
1 0x7fff8d02fc2c
1 0x7fffbc74fd9c

The position of the stack in memory is randomized. This is done to prevent a whole family of buffer overflow exploits. But since memory allocations, especially at this level, can only be done in multiple of pages (4096 bytes) all initial stack pointers would be aligned at 0x1000. This would reduce the number of random bits in the randomized stack address, so additional randomness is added by just wasting a random amount of bytes at the top of the stack.
The operating system can only account the amount of memory you use, including the limit on the stack, in whole pages. So even though the stack starts at a random address, the last accessible address on the stack will always be an address ending in 0xfff.
The short answer is: to increase the amount of randomness in the randomized memory layout a bunch of bytes on the top of the stack are deliberately wasted, but the end of the stack has to end on a page boundary.

A: There is a gap between the stack segment and the heap segment. Now because the size of heap is variable( keeps on changing during execution), therefore the extent to which your stack will grow before stackoverflow occurs is also variable and this is the reason why your program rarely terminates at the same call depth.

A: The above code can cause two issue:

*

*Stack Overflow.

*Integer overflow.
Stack Overflow: When a recursive function is called, all its variable is pushed onto the call stack including its return address. As there is no base condition which will terminate the recursion and the stack memory is limited, the stack will exhausted resulting Stack Overflow exception. The call stack may consist of a limited amount of address space, often determined at the start of the program. The size of the call stack depends on many factors, including the programming language, machine architecture, multi-threading, and amount of available memory. When a program attempts to use more space than is available on the call stack (that is, when it attempts to access memory beyond the call stack's bounds, which is essentially a buffer overflow), the stack is said to overflow, typically resulting in a program crash.
Note that, every time a function exits/return, all of the variables pushed onto the stack by that function, are freed (that is to say, they are deleted). Once a stack variable is freed, that region of memory becomes available for other stack variables. But for recursive function, the return address are still on the stack until the recursion terminates. Moreover, automatic local variables are allocated as a single block and stack pointer advanced far enough to account for the sum of their sizes. You maybe interested at Recursive Stack in C.
Integer overflow: As every recursive call of recursive() increments rec by 1, there is a chance that Integer Overflow can occur. For that, you machine must have a huge stack memory as the range of unsigned integer is: 0 to 4,294,967,295. See reference here.

A: Your recursive call is not necessarily going to cause undefined behaviour due to stackoverflow (but will due to integer overflow) in practice. An optimizing compiler could simply turn your compiler into an infinite "loop" with a jump instruction:
void recursive(int rec) {
   loop:
    printf("%i\n", rec);
    rec++;
   goto loop;
}

Note that this is going to cause undefined behaviour since it's going to overflow rec (signed int overflow is UB).  For example, if rec is of an unsigned int, for example, then the code is valid and in theory, should run forever.

A: When a process loads a program from an executable, typically it allocates areas of memory for the code, the stack, the heap, initialised and uninitialised data.
The stack space allocated is typically not that large, (10s of megabytes probably) and so you would imagine that physical RAM exhaustion would not be an issue on a modern system and the stack overflow would always happen at the same depth of recursion.
However, for security reasons, the stack isn't always in the same place.  Address Space Layout Randomisation ensures that the base of the stack's location varies between invocations of the program.  This means that the program may be able to do more (or fewer) recursions before the top of the stack hits something inaccessible like the program code.
That's my guess as to what is happening, anyway.


text:
Q: Where does the first term go in this partial derivative? I am reading this paper https://papers.nips.cc/paper/4329-practical-variational-inference-for-neural-networks.pdf and I cannot see where the first part of the partial derivative for equations 7 and 8 go. Here is equation 7 from the paper.
$$
L^C(\mathbf{\alpha}, \mathbf{w}) = W\ln2b + \frac{1}{b} \sum_{i=1}^W |w_i - \mu| + C \implies \frac{\partial L^C(\mathbf{\alpha}, \mathbf{w})}{\partial w_i} = \frac{sgn(w_i - \mu)}{b}
$$
Shouldn't there be a leftover term $\ln2b$ as a result of the derivative of the first term on the RHS?

redpajama_set_name: RedPajamaStackExchange


text:
Q: WPF Nesting ItemsControls I've just began meddling with ItemsControls/Binding, and I've encountered an issue. I've looked at various tutorials regarding nested ItemsControls, so I'm not positive what it is that I'm doing wrong. I believe all is coded correctly, but the Expander doesn't display content as it ought to. The Header properly aligns itself to the top of its parent, but the ScrollViewer won't appear, and it only scrolls the parenting "TimeScrollViewer". Am I perhaps binding something incorrectly?
All suggestions are appreciated.
C#:
private string[][] hours = new string[][]
{
    new string[] { "11:00", "11:30", "12:00", "12:30", "1:00", "1:30", "2:00", "2:30", "3:00", "3:30", "4:00", "4:30", "5:00", "5:30", "6:00", "6:30", "7:00", "7:30", "8:00", "8:30" },
    new string[] { "5:00", "5:30", "6:00", "6:30", "7:00", "7:30", "8:00", "8:30", "9:00" },
    new string[] { "5:00", "5:30", "6:00", "6:30", "7:00", "7:30", "8:00", "8:30", "9:00" },
    new string[] { "5:00", "5:30", "6:00", "6:30", "7:00", "7:30", "8:00", "8:30", "9:00" },
    new string[] { "5:00", "5:30", "6:00", "6:30", "7:00", "7:30", "8:00", "8:30", "9:00" },
    new string[] { "5:00", "5:30", "6:00", "6:30", "7:00", "7:30", "8:00", "8:30", "9:00" },
    new string[] { "5:00", "5:30", "6:00", "6:30", "7:00", "7:30", "8:00", "8:30", "9:00" }
};

public class GuestItem
{
    public string GuestName { get; set; }
}

public class RegistryItem
{
    public string Header { get; set; }
    public List<GuestItem> GuestList = new List<GuestItem>();
}

Expander currentExpander = null;

public MainWindow()
{
    int day = (int)DateTime.Now.DayOfWeek;

    InitializeComponent();

    List<RegistryItem> items = new List<RegistryItem>();

    foreach(string hour in hours[day])
    {
        RegistryItem registryItem = new RegistryItem(){ Header = hour };

        registryItem.GuestList.Add(new GuestItem() { GuestName = "Bob" });
        registryItem.GuestList.Add(new GuestItem() { GuestName = "Frank" });
        registryItem.GuestList.Add(new GuestItem() { GuestName = "Jim" });

        items.Add(registryItem);
    }

    TimeItemsControl.ItemsSource = items;
}

private void ExpanderExpanded(object sender, RoutedEventArgs e)
{
    if(currentExpander != null)
    {
        currentExpander.IsExpanded = false;
    }

    currentExpander = e.Source as Expander;

    currentExpander.IsExpanded = true;
}

private void ExpanderCollapsed(object sender, EventArgs e)
{
    currentExpander = null;
}

XAML:
<s:SurfaceScrollViewer Name="TimeScrollViewer" Grid.Row="1" Grid.Column="1" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Hidden" Background="#4CAAAAFF" Style="{DynamicResource SurfaceScrollViewerHorizontalTop}" Foreground="#4CAAAAFF">
    <ItemsControl Name="TimeItemsControl">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Left"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Expander Expanded="ExpanderExpanded" Collapsed="ExpanderCollapsed" Header="{Binding Header}" Style="{DynamicResource SurfaceExpander}" HorizontalContentAlignment="Center" FontSize="21.333" Width="100">
                    <s:SurfaceScrollViewer Width="{Binding ElementName=TimeScrollViewer, Path=ActualWidth}" Height="{Binding ElementName=TimeScrollViewer, Path=ActualHeight}" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Hidden">
                        <ItemsControl ItemsSource="{Binding GuestList}">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Left"/>
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <s:SurfaceButton Content="{Binding GuestName}"/>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </s:SurfaceScrollViewer>
                </Expander>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</s:SurfaceScrollViewer>

A: When you run (debug) your application and check the output tab in Visual Studio, you can see the following output multiple times:

System.Windows.Data Error: 40 : BindingExpression path error: 'GuestList' property not found on 'object' ''RegistryItem' (HashCode=15478206)'. BindingExpression:Path=GuestList; DataItem='RegistryItem' (HashCode=15478206); target element is 'ItemsControl' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')

So the data binding to the GuestList property could not be resolved on the RegistryItem object. If you look closely at the definition of the type, you can see why:
public class RegistryItem
{
    public string Header { get; set; }
    public List<GuestItem> GuestList = new List<GuestItem>();
}

GuestList is not a property, but a field. The WPF binding engine requires properties, so the GuestList field, despite being public, does not exist for the binding engine, resulting in above error. To fix this, simply make it a property. You can use an empty constructor to initialize the list:
public class RegistryItem
{
    public string Header { get; set; }
    public List<GuestItem> GuestList { get; set; }

    public RegistryItem ()
    {
        GuestList = new List<GuestItem>();
    }
}

Then everything will work correctly. So the bottom line is: Always check for error messages, especially binding errors, they usually tell you what might be wrong. As binding errors are usually rather hidden (since they don't break stuff), you could use a technique described [in this other question](
How can I turn binding errors into runtime exceptions?) to turn them into full exceptions or to at least log them somewhere else.


text:
Q: I wonder about .htaccess rule
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([a-zA-Z0-9_-]+)$ index.php/$1 [L]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ index.php/$1/$2 [L]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ index.php/$1/$2/$3 [L]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ index.php/$1/$2/$3/$4 [L]

you can see my code..
$1/$2/$3/$4 .. (now)
$1/$2/$3/$4/$5 ~ $unlimited (I wanted)
sorry my bad english..
do you understand?

A: If you want unlimited ([a-zA-Z0-9_-]+)/'s, you could just match for [a-zA-Z0-9_-/]+ and call it a day:
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([/a-zA-Z0-9_-]+)$ index.php/$1 [L]


text:
Q: DDD: Share entity with multiple aggregate roots Learning DDD, in our application there are three aggregate roots, different types of forms, all of which needs some PDF to be uploaded. These pdf uploads have some metadata, like who uploaded and when uploaded etc, attached to it so they are stored in their own table.
My question is whether this PDF should be modeled as a value object or an entity or an aggregate root.
For me it looks like an entity named as "Attachment" but then this entity should be shared, only the type not the instances, by all the aggregate root. Is it an allowed practice to use same entity type in multiple roots, if so then which part of the model should take the responsibility for creating this entity.
Update
class Attachment{
   Java.io.File pdf;
   Date attachedOn;
   .....
   //no operation for this class
}

@AggregateRoot
class DocumentA {
   Set<Attachment> attachments;
   Set<DocumentB> supportingDocumentsB;
   Set<DocumentA> supportingDocumentsA;
   .... //other properties unique to DocumentA

   attach(Attachment a);
   detach(Attachment a);
   addSupportingDocumentA(DocumentA doc);
   removeSupportingDocumentA(DocumentA doc);
   addSupportingDocumentB(DocumentB doc);
   removeSupportingDocumentB(DocumentB doc);
   .... //other operations unique to DocumentA
}

@AggregateRoot
class DocumentB {
   Set<Attachment> attachments;
   Set<DocumentB> supportingDocumentsB;
   Set<DocumentA> supportingDocumentsA;
   .... //other properties unique to DocumentB

   attach(Attachment a);
   detach(Attachment a);
   addSupportingDocumentA(DocumentA doc);
   removeSupportingDocumentA(DocumentA doc);
   addSupportingDocumentB(DocumentB doc);
   removeSupportingDocumentB(DocumentB doc);
   .... //other operations unique to DocumentB
}

@AggregateRoot
class SomeAggregateRoot{
   Set<Attachment> attachments;
   //some properties

   attach(Attachment a);
   detach(Attachment a);
   //some operations
}

Now the question is how the Attachment class should be modeled, as a value object (or) an entity (or) an aggregate root. Quoting «Domain-Driven Design Distilled», Vaughn Vernon (ISBN-13: 978-0134434421):

Furthermore, a Value Object is not a thing but is often used to describe, quantify, or measure an entity.

A: I think the Attachment concept fits better in the Value Object concept, since there is no life cycle and the fields are naturally immutable.
The fact that the data base entry has an primary key doesn't imply it has to be an entity in the domain context.


text:
Q: How to output 7 records for each row, 1 for each day of week? Trying to save myself a lot of data entry here. I have the output below currently:
CONTID  DESCR
001     Area 1
001     Area 2
001     Area 3

What I'd like to do is output 7 records for each "DESCR" (Area), 1 for each day of the week (0 - 6 accordingly).
Example output would be:
CONTID  DESCR         DAYOFWEEK
001     Area 1        0
001     Area 1        1
001     Area 1        2
001     Area 1        3
001     Area 1        4
001     Area 1        5
001     Area 1        6
001     Area 2        0
001     Area 2        1
001     Area 2        2
001     Area 2        3
001     Area 2        4
001     Area 2        5
001     Area 2        6
001     Area 3        etc...

I'd like to do this with straight SQL if possible. This is for a one-time "copy/paste" job to populate a new table.

A: You might do this with a CROSS JOIN
(Thx to @TT. for pointing out, that my answercan be shortened)
DECLARE @tbl TABLE(CONTID INT,  DESCR VARCHAR(100));
INSERT INTO @tbl VALUES
 (001,'Area 1')
,(001,'Area 2')
,(001,'Area 3');

SELECT *
FROM @tbl AS tbl
CROSS JOIN (VALUES(0),(1),(2),(3),(4),(5),(6)) AS AllDays(DayInx)

A: Also, consider this other solution that too uses a cross join but implicitly with derived tables for any future readers needing a generalized SQL solution in their specific RDMS:
SELECT CONTID,  DESCR, DAYOFWEEK
FROM
  (SELECT CONTID,  DESCR FROM dataTable) AS T1,
  (SELECT 0 As DAYOFWEEK
    UNION  SELECT 1
    UNION  SELECT 2
    UNION  SELECT 3
    UNION  SELECT 4
    UNION  SELECT 5
    UNION  SELECT 6) As WeekDays


text:
Q: e(fx)clipse - Tutorial2 - step 18 - can't generate update site Tutorial2 – e(fx)clipse - step 18 - Problem occurred
I am following
http://www.efxclipse.org/trac/wiki/Tutorial2
At step 18: generate update site with button )Build All(

18 : The result of the operation should look similar to the screenshot
  below

. ...
But I actually got "Problem occurred"

eclipse.buildId=M20130204-1200
java.version=1.7.0_17
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=ru_RU
Command-line arguments:  -os win32 -ws win32 -arch x86

Error
Thu Apr 04 21:51:03 CST 2013
An internal error occurred during: "Build Site".

java.lang.NoClassDefFoundError: at/bestsolution/efxclipse/tooling/pde/adaptor/IClasspathContributor
    at org.eclipse.pde.internal.core.exports.BuildUtilities.getBootClasspath(BuildUtilities.java:59)
    at org.eclipse.pde.internal.core.exports.FeatureExportOperation.createAntBuildProperties(FeatureExportOperation.java:471)
    at org.eclipse.pde.internal.core.exports.FeatureExportOperation.doExport(FeatureExportOperation.java:255)
    at org.eclipse.pde.internal.core.exports.FeatureBasedExportOperation.run(FeatureBasedExportOperation.java:50)
    at org.eclipse.pde.internal.core.exports.SiteBuildOperation.run(SiteBuildOperation.java:65)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:53)

A: I answered your question already yesterday on the e(fx)clipse forum. This is a bug caused by the fact that we have to fix the PDE-Classpath-Container in a very nasty way.


text:
Q: How to define context resource in spring boot I am new to Spring Boot. I want to define resource tag which is present in context.xml in spring boot. So that I can define my Datasource for jdbctemplate.
This is what I am doing :
 @SpringBootApplication
 @EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
 public class Application extends SpringBootServletInitializer{

private static final Logger LOGGER = Logger.getLogger(Application.class);
public static void main(String[] args) {
    LOGGER.info("Spring Boot Application Started");
    SpringApplication.run(Application.class, args);
    LOGGER.info("Spring Boot Application Ended");
}
  @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(Application.class);
  }

  @Bean
  public EmbeddedServletContainerFactory tomcatFactory() {
      return new TomcatEmbeddedServletContainerFactory() {

          @Override
          protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
                  Tomcat tomcat) {
              tomcat.enableNaming();
              return super.getTomcatEmbeddedServletContainer(tomcat);
          }

          @Override
          protected void postProcessContext(Context context) {
              ContextResource resource = new ContextResource();
              resource.setName("jdbc/mydb");
              resource.setType(DataSource.class.getName());
              resource.setProperty("driverClassName", "oracle.jdbc.OracleDriver");
              resource.setProperty("url", "jdbc:oracle:thin:@localhost:1521:XE");
              resource.setAuth("Container");
              resource.setProperty("username","uname");
              resource.setProperty("password","pword");
              resource.setProperty("validationQuery","select 1 from dual");
              resource.setProperty("initSQL","select 1 from dual");
              context.getNamingResources().addResource(resource);

          }
      };
  }

  @Bean(destroyMethod="")
  public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
      JndiObjectFactoryBean bean = new JndiObjectFactoryBean();

      bean.setJndiName("java:comp/env/jdbc/mydb");
      bean.setProxyInterface(DataSource.class);
      bean.setLookupOnStartup(false);
      bean.afterPropertiesSet();
      return (DataSource)bean.getObject();
  }

}
But i am getting this exception :
    2016-08-07 23:08:18.391  WARN 656 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Client': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected org.springframework.jdbc.core.JdbcTemplate com.example.test.app.srv.test.BasetestServiceController.jdbcTemplate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jndiDataSource' defined in com.example.test.app.Application: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'jndiDataSource' threw exception; nested exception is javax.naming.NameNotFoundException: Name [comp/env/jdbc/mydb] is not bound in this Context. Unable to find [comp].
    2016-08-07 23:08:18.394  INFO 656 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat
    2016-08-07 23:08:18.406 ERROR 656 --- [           main] o.s.boot.SpringApplication               : Application startup failed

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Client': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected org.springframework.jdbc.core.JdbcTemplate com.example.test.app.srv.test.BasetestServiceController.jdbcTemplate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jndiDataSource' defined in com.example.test.app.Application: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'jndiDataSource' threw exception; nested exception is javax.naming.NameNotFoundException: Name [comp/env/jdbc/mydb] is not bound in this Context. Unable to find [comp].
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at com.example.test.app.Application.main(Application.java:34) [classes/:na]
    Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected org.springframework.jdbc.core.JdbcTemplate com.example.app.srv.ServiceController.jdbcTemplate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jndiDataSource' defined in com.example.test.app.Application: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'jndiDataSource' threw exception; nested exception is javax.naming.NameNotFoundException: Name [comp/env/jdbc/mydb] is not bound in this Context. Unable to find [comp].
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        ... 17 common frames omitted

What am i missing here..??
even i tried
   @Resource(name="jdbc/mydb", type=javax.sql.DataSource.class, lookup="jdbc/mydb")

But its not working.
I also tried
    @Bean(destroyMethod="")
public DataSource dataSource() {
   final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
    dsLookup.setResourceRef(true);
    DataSource dataSource = dsLookup.getDataSource("jdbc/mydb");

    return dataSource;
}


text:
Q: Xamarin application access LAMP server on a Raspberry Pi I'm currently making my first steps into developing a basic iPhone app and want it to retrieve information from a raspberry Pi set up as a server and send a push alert to the app user. The process should look something like this:

*

*Daily list of Flavours added to Pi (which is set up as a server using LAMP)

*iPhone app (designed/built using Xamarin) retrieves list of flavours from the server

*Push notification sent based on user defined 'favourite flavours'

At this stage I'm trying to keep the app as simple as possible in that the users only need to select their favourite flavours from a full list and the app will retrieve and compare their list against the source list giving them a notification if any of their favourites are available.
I realise this is quite an open ended question. What I'm really looking for is any ideas if this process sounds feasible, possible flaws in my understanding, any interaction issues between the pi server the app and if people think that a Pi would be able to handle this functionality.


text:
Q: button label colour change after click IOS I have a piece of code which creates a button, in the right space size colour etc:
UIButton *learnmorebutton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.view addSubview:learnmorebutton];
learnmorebutton.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.3];
learnmorebutton.frame = CGRectMake(0.0, 518.0, 159.0, 50.0);
[learnmorebutton setTitle:@"learn more" forState:UIControlStateNormal];
[learnmorebutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
learnmorebutton.titleLabel.font = [UIFont fontWithName:@"Helvetica Light" size:17.0];

I then have a trigger for when the button is pressed:
[learnmorebutton addTarget:self action:@selector(learnMoreClickEvent:) forControlEvents:UIControlEventTouchUpInside];

Then I want the buttons background to change and also the text colour, so:
sender.titleLabel.textColor = [UIColor redColor];
sender.backgroundColor = [UIColor whiteColor];

The background changes colour but the text disappears. Like its gone white too.

A: You need to set the color of the label via
[sender setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

The button accept no color change on the label directly cause its appearance changes with his state. That is why you need to use the specific UIButton API for this.

A: [learnmorebutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

Change to
[learnmorebutton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

when you click on uibutton get Highlight with white color that why your text  looks like  text disappears.

A: If you asked "how to change the color when the button is pressed" you can easily change it like this:
self.titleLabel.textColor = [UIColor redColor];
self.*yourlabel*.textColor = [UIColor *desiredColor*];


text:
Q: Google Maps Android API v2 - Hollow Polygon not correctly drawn The code below doesn't work with Google Maps API v2. The polygons (outer and inner polygons) are drawn with the right border, but the fill color of the outer one is not drawn.
PolygonOptions polygonOptions = new PolygonOptions();
polygonOptions.add(outerCoordinates);
polygonOptions.addHole(Arrays.asList(innerCoordinates));
polygonOptions.fillColor(Color.BLUE);
polygonOptions.strokeWidth(1.0f);

Does anybody face the same problem?

A: Check whether there is a requirement that polygon coordinates have to be clockwise (or counterclockwise) ordered. Try to change the order.

A:
The vertices must be added in counterclockwise order. Reference

I wrote a function to determinate if a List<LatLng> is clockwise. The code is an implementation of this answer:
public boolean isClockwise(List<LatLng> region) {
    final int size = region.size();
    LatLng a = region.get(size - 1);
    double aux = 0;
    for (int i = 0; i < size; i++) {
        LatLng b = region.get(i);
        aux += (b.latitude - a.latitude) * (b.longitude + a.longitude);
        a = b;
    }
    return aux <= 0;
}

Before adding the polygon points put these three lines:
if (isClockwise(polygon)) {
    Collections.reverse(polygon);
}


text:
Q: How to write the file output to the server In MySQL I can do select * from some_table into outfile 'myfile.csv'
Is there something similar in MongoDB? Cannot find relevant information in the documenatation. I'm working with mongodb 2.2.3.

A: You might want to use mongoexport, which produces a JSON or CSV export of data stored in a MongoDB instance
mongoexport --db dbName --collection collectionName --jsonArray --pretty --query '{"key": "value"}' --output output.json

For more details, please refer to mongoDB documentation.


text:
Q: XmlDocument.Load not processing DTD? I am trying to build & develop a Security POC, this code is part of an app that I've extracted into a smaller app because I am having some difficulty with it.
 String str = "<?xml version=\"1.0\"?><!DOCTYPE foo[<!ELEMENT foo ANY> <!ENTITY word \"A\">]><foo>&word;</foo>";
   System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
  xDoc.LoadXml(str);
 xDoc.Save(@"C:\Temp\xdoc.xml");

Consider the xml string contains a DTD entity word, which is referenced in my actual xml. When the document is loaded I would expect the DTD To get processed and therefore replace the entity "word" referred to in my xml with the character string "A". Then write the whole document back out to disk. However when I examine xDoc.xml. The Entity expansion/replacement hasn't happened.
Why not?

A: You can find the following in the documentation of LoadXml method which you use in your code:

This method does not do DTD or Schema validation. If you want
  validation to occur, use the Load method and pass it an
  XmlValidatingReader. See XmlDocument for an example of load-time
  validation

The article, this one and many other provide code examples of DTD validation.


text:
Q: Cant find 'com.android.support:design:22.2.0' I want to use the FloatingActionButton but for that I need the library:
compile 'com.android.support:design:22.2.0'

But when I add it to my gradle, I get the message:
A problem occurred configuring project ':myModule'.
Could not resolve all dependencies for configuration ':myModule:_debugCompile'.
   Could not find com.android.support:design:22.2.0.
     Searched in the following locations:
         https://jcenter.bintray.com/com/android/support/design/22.2.0/design-22.2.0.pom
         https://jcenter.bintray.com/com/android/support/design/22.2.0/design-22.2.0.jar
         file:/D:/Development/Android/sdk/extras/android/m2repository/com/android/support/design/22.2.0/design-22.2.0.pom
         file:/D:/Development/Android/sdk/extras/android/m2repository/com/android/support/design/22.2.0/design-22.2.0.jar
         file:/D:/Development/Android/sdk/extras/google/m2repository/com/android/support/design/22.2.0/design-22.2.0.pom
         file:/D:/Development/Android/sdk/extras/google/m2repository/com/android/support/design/22.2.0/design-22.2.0.jar
     Required by:
         myProject:myModule:unspecified

I tried updating my Android SDK but everything is up to date:

So why can't com.android.support:design:22.2.0 be resolved?
This is my gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "de.bla.myProject"
        minSdkVersion 19
        targetSdkVersion 22
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_7
            targetCompatibility JavaVersion.VERSION_1_7
        }
    }

    buildTypes {
        debug {
            debuggable true
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile project(':androidcircularcrop_lib')
    compile 'com.google.code.gson:gson:2.2.4'
    compile 'com.android.support:appcompat-v7:22.0.0'
    compile 'com.google.android.gms:play-services:+'
    compile 'com.android.support:design:22.2.0'
    compile files('libs/eventbus-3.0.0-beta1.jar')
    compile files('libs/mpandroidchartlibrary-2-1-0.jar')
    compile files('libs/picasso-2.4.0.jar')
    compile files('libs/YouTubeAndroidPlayerApi.jar')
}

A: Looking at your build file, always set target and compile sdk to the same number. The appcompat lib is also a part of the sdk so when using a 22.x.x support lib, you are goning to need at least the 22 sdk to ensure compatibility, let alone finding the lib.
Also as Arkadiy suggested it is recommended to use the latest build-tools and gradle version compatible with your android studio.


text:
Q: Odd logcat error when switching to new fragment I haven't encountered a stack trace such as this. It's particularly weird because I can only get the error to be thrown when debugging. (Running the app without debugging does not yield this error). This happens upon selecting a particular page from my navigation drawer. I have just recently switched from activities to fragments and I may not have handled my fragment transactions correctly. I would appreciate any input! Thanks a lot guys, happy holidays!
Here's the stack trace:
Process: com.kohlerbear.whowascnscalc, PID: 2415
java.lang.NullPointerException: Attempt to read from field 'boolean android.support.v4.app.BackStackRecord.mAddToBackStack' on a null object reference
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:685)
        at android.support.v4.app.FragmentManagerImpl.execPeerrorndingActions(FragmentManager.java:1479)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:447)
        at android.os.Handler.handleCallback(Handler.java:740)
        at android.os.Handler.dispatchMessage(Handler.java:104)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5223)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

And here is how I am handling my fragment change (Not sure if this is the problem, just judging by the fact that the trace mentions the backstack). The app crashes (again, only when debugging)  regardless of whether or not I call ft.addToBackStack(null) .
Fragment frag = new ThirdScreenFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, frag);
ft.addToBackStack(null);
ft.commit();`

Any ideas and input are appreciated :)

A: I recently ran into the same error message in Android studio. I could run my application but once I tried to start debugging, I would receive "Attempt to read from field 'boolean android.support.v4.app.BackStackRecord.mAddToBackStack' on a null object reference". The solution was to select in Android Studio, Run (toolbar) -> View Break Points -> disable each break point one by one until debugging started to work again. Doing this doesn't remove the break point entirely it simply disables them, so there's no need to worry that you'd need to remove all your break points to find the one causing the issue. It seems that one of the break points I had setup in a IntentService class was causing the issue. I'm not sure why it was causing an issue, but it seemed to fix this error for me.

A: I found a workaround for this issue. Put a breakpoint in the android.support.v4.app.BackStackRecord.run() method and set break condition to false.


text:
Q: How to search in another table in Laravel with Eloquent? I have two models:
Order
Customer

I have customer_id in orders table. Customer details (name, phone, email etc) in customerstable. But I am writing query for orders table.
Now, I want to search with Customer Name on Orders but in Orders table I just have customer_id.
How will I link up with customers table so that I can search with Customer Name. I want to do that with Eloquent.
How is this possible?

A: There are multiple ways of doing relationship filtering with Eloquent.
You can achieve it with whereHas or using an advanced join / left join query.
I suggest you do a research about Eloquent filtering on Laravel documentation, everything you need for your task should be there.
https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
https://laravel.com/docs/8.x/queries#advanced-join-clauses

A: In models define relationships
Customer model
public function orders()
{
   return $this->hasMany(Orders::class);
}

Order model
public function customer()
{
   return $this->belongsTo(ustomer::class, 'foreign Key', 'id');
}

Then you can call relationships and search what you want
Customer::whereHas('orders')

A: First you need to create relationship in the orders model, you can use either belongsTo or hasOne relationship.
belongsTo relationship will be like as below
public function customer()
{
   return $this->belongsTo(ustomer::class, 'foreign Key', 'id');
}

and the hasOne relationship will be like as below
public function customer()
{
   return $this->hasOne(Customer::class, 'foreign_key', 'local_key');
}

The search function will be like as below
public function OrderSearch(Request $request){
   try {

     /**
      * Fetching data with orders relationship
      */
     $orders = OrdersModel::with(['customer'])

     if(!empty($request->search)){
        /**
         * Searching the name key inside
         * the customer relationship
         */
        $orders->where(fn($query)=>
            $query->whereHas('customer',fn($query2) =>
                    $query2->where('name','LIKE','%'.$request->search.'%'));
         );
     }

     /**
      * Returning the response
      */
     return $orders->get();

 } catch (\Throwable $th) {
     throw $th;
 }
}

Kindly refer the laravel eloquent-relationships documentation : eloquent-relationships


text:
Q: React Component Will Not Re-Render After Redux Updates I am new to React and Redux and I have been working on this issue for a few days now.
The problem is my react component will not re-render once Redux updates. I have added Redux Dev Tools and the state updates correctly so at this point I have no idea why my React component will not re-render. I have tried reading the docs and searching Stackoverflow but still I cannot figure out what I am doing wrong. The component (ComponentOne) in question renders initially with the default state from redux but when I change the Redux state through a different component (ComponentTwo), ComponentOne will not re-render. Redux updates in Dev tools. I am updating the redux in ComponentOne and expecting it to change in ComponentTwo. The only time ComponentTwo will re-render is if the props of ComponentTwo change.
I am using Typescript, React, and Redux.
Please disregard that I am using Redux and React state in component #1. I plan on changing this eventually. I have simplified some of the components because there is a lot of code. It should not impact the question.
Structure
|__src
|  |__components
|  |  |__ComponentOne.tsx -redux dispatched, useDispatch
|  |  |__ComponentTwo.tsx -component that will not re-render, uses useSelector
|  |__functions
|  |  |__functions.ts
|  |__redux
|  |  |__store.ts
|  |  |__actionsMaster.ts
|  |  |__reducers
|  |  |  |__quarterReducer.ts
|  |  |  |__filingStatusReducer.ts
|  |  |  |__rootReducer.ts

ComponentOne.tsx
import { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { changeQuarter, changeFilingStatus } from "../redux/action-creators/actionsMaster";
import { constantsOne } from "../constants";
import { RootState } from "../redux/store";

const ComponentOne= () => {

const quarter = useSelector<RootState, string>(state => state.quarter);
const filingStatus = useSelector<RootState, string>(state => state.filingStatus);
const dispatch = useDispatch();

const [ quarterState, setQuarterState ] = useState("1");
const [ filingStatusState, setFilingStatusState ] = useState("SINGLE");

const handleSubmit = () => {
  let tempQuarter = quarterState;
  let tempFilingStatus = filingStatusState;

try {
  dispatch(changeQuarter(tempQuarter));
  dispatch(changeFilingStatus(tempFilingStatus));
  setQuarterState(tempQuarter);
  setFilingStatusState(tempFilingStatus);
     }

catch(err) {
  console.log(err);
     }
 };

const handleChange = (elementId: number, e: { target: HTMLSelectElement }) => {
 let tempValue = e.target.value;

 // Each case goes in order from the constantsOne Element value from constants. If you   // break the order, the function will not perform properly.
switch(elementId){
 case 0:
  setQuarterState(tempValue);
  break;
 case 1:
  setFilingStatusState(tempValue);
  break;
 default:
  console.log("No case was selected");
     };
 };

return (

COMPONENT 1 TITLE

               {constantsOne.map((item) =>

{item.element}:
                 <select name={item.element} className="component1-select" id="component1-item" onChange={(e) => handleChange(item.id, e)}>
                 {item.array.map((value) =>
                     <option key={value.id} value={value.arrayValue}>{value.arrayValue}</option>
                 )};
                 </select>

                )}

             <button id="component1-submit-button" className="submit-button" type="submit" onClick={handleSubmit}>SUBMIT</button>

      );
 }

export default ComponentOne;

ComponentTwo.tsx
import functionOne from "../functions/functionOne";
 import functionTwo from "../functions/functionTwo";
 import functionThree "../functions/functionThree";
 import { useSelector } from "react-redux";
 import {
  modelOneType,
  modelTwoType,
  modelThreeType
 from "../types";
 import {
  constantsTwo,
  constantsThree }
 from "../constants";
 import { RootState } from "../redux/store";

 interface componentTwoProps {
  props1: modelOneType,
  props2: modelTwoType,
  props3: modelThreeType
 }

 const ComponentTwo= ({
  props1,
  props2,
  props3
 }: componentTwoProps
 ) => {

 const quarterFromStore = useSelector<RootState, string>(state => state.quarter);
 const filingStatusFromStore = useSelector<RootState, string>(state => state.filingStatus);

 const valueOne: number = functionOne(quarterFromStore);
 const ValueTwo: props1Type = functionTwo(props1, props2, valueOne);
 const valueThree: number = functionThree(valueTwo, constantsTwo);

 // There are many more consts that have new data based off of other consts. I excluded because I    // do not think it impacts the problem at hand. There are really up to like valueThirty.
 // the div below has also been simplified but should not impact issue at hand

 return (

             COMPONENT TWO TITLE

                       DESCRIPTION
                        COLUMN ONE

                        {constantsTwo.map((item) =>

                            {item.element}
                          {valueTwo[item.hardValue as keyof modelOneType]}

                       )}

                            TOTAL
                            {valueThree}

                       {constantsThree.map((item) =>

                            {item.element}
                            {valueTwo[item.hardValue as keyof modelOneType]}

                        )}

      );
 }

 export default ComponentTwo;

App.tsx
import Header from './components/Header'
import UserTitleBox from './components/UserTitleBox';
import ComponentOne from './components/ComponentOne';
import InputComponent from './components/InputComponent';
import Notes from './components/Notes';
import Contact from './components/Contact';
import Footer from './components/Footer'

function App() {
  return (

         <UserTitleBox />
         <ComponentOne/>
         <InputComponent />

        // ComponentTwo is a child of InputComponent

        <Notes />
        <Contact />

  );
}

export default App;

store.ts
import rootReducer from "./reducers/rootReducer";
import { configureStore } from "@reduxjs/toolkit";

export const store = configureStore({
    reducer: rootReducer
});

export type RootState = ReturnType<typeof store.getState>;

actionsMaster.ts
import {
    modelOneType,
    modelTwoType,
    modelThreeType
} from "../../types";
import { Dispatch } from 'redux';
import {
    CHANGEQUARTER,
    CHANGEFILINGSTATUS,
    CHANGENUMBERSINPUT,
    CHANGENUMBERSANNUALIZATION,
    CHANGEPAYMENTSINPUT
 } from '../constants';

export const changeQuarter = (quarter: string) => {
    return (dispatch: Dispatch) => {
        dispatch({
            type: CHANGEQUARTER,
            payload: quarter
        })
    }
};

export const changeFilingStatus = (filingStatus: string) => {
    return (dispatch: Dispatch) => {
        dispatch({
            type: CHANGEFILINGSTATUS,
            payload: filingStatus
        })
    }
};

export const changeNumbersInput = (numbersInputValues: modelOneType) =>{
    return (dispatch: Dispatch) => {
        dispatch({
            type: CHANGENUMBERSINPUT,
            payload: numbersInputValues
        })
    }
};

export const changeAnnualization = (numbersAnnualizationValues: modelTwoType) =>{
    return (dispatch: Dispatch) => {
        dispatch({
            type: CHANGENUMBERSANNUALIZATION,
            payload: numbersAnnualizationValues
        })
    }
};

export const changePaymentsInput = (paymentsInputValues: modelThreeType) =>{
    return (dispatch: Dispatch) => {
        dispatch({
            type: CHANGEPAYMENTSINPUT,
            payload: paymentsInputValues
        })
    }
};

quarterReducer.ts
import { PayloadAction } from '@reduxjs/toolkit';
import { CHANGEQUARTER } from '../constants';

const initialState: string = "1";

const reducer = (state = initialState, action: PayloadAction<string>) => {
    switch(action.type){
        case CHANGEQUARTER:
            return state = action.payload;
        default:
            return state;
    };
}

export default reducer;

filingStatusReducer.ts
import { PayloadAction } from '@reduxjs/toolkit';
import { CHANGEFILINGSTATUS } from '../constants';

const initialState: string = "SINGLE";

const reducer = (state = initialState, action: PayloadAction<string>) => {
    switch(action.type){
        case CHANGEFILINGSTATUS:
            return state = action.payload;
        default:
            return state;
    };
}

export default reducer;

rootReducer.ts
import { combineReducers } from "redux";
import quarterReducer from "./quarterReducer";
import filingStatusReducer from "./filingStatusReducer";
import numbersInputReducer from "./numbersInputReducer";
import paymentsInputReducer from "./paymentsInputReducer";
import numbersAnnualizationReducer from "./numbersAnnualizationReducer";

const rootReducer = combineReducers({
    quarter: quarterReducer,
    filingStatus: filingStatusReducer,
    numbersInputValues: numbersInputReducer,
    paymentsInputValues: paymentsInputReducer,
    numbersAnnualizationValues: numbersAnnualizationReducer
});

export default rootReducer;

All help is appreciated. Please let me know if I need to clarify anything.

A: I'm a Redux maintainer.  There's a few issues.
First, the line return state = action.payload is probably not going to do what you want.  If you're trying to replace the existing state, do return action.payload.
The second is that even though you have Redux Toolkit installed, the rest of your logic is still a very outdated style of Redux code.  With Redux Toolkit, you should be using the createSlice API to write your reducers.  createSlice uses Immer inside, so that you can write "mutating" syntax in reducers, which gets turned into correct immutable updates.  It also generates action creators for you, so you don't have to write any of those by hand.
Please see our Redux docs tutorials, which explain how to use Redux Toolkit:

*

*https://redux.js.org/tutorials/essentials/part-1-overview-concepts
Along with that, you're writing way too many unnecessary TS types.  Instead of writing useSelector<RootState, string> everywhere, follow our steps for setting up "pre-typed" versions of useSelector and useDispatch that have the right state and dispatch types configured:

*

*https://redux.js.org/tutorials/typescript-quick-start


text:
Q: Is there a moving knife procedure for envy-free cake cutting with connected pieces? In the wikipedia page on envy-free cake cutting, continuous "moving knife" algorithms for envy free cake cutting to connected pieces is only mentioned for up to 4 players. As the wikipedia article does not say so explicitly, is there a general solution?

A: As far as I know, this is an open question. Some information can be found in:
Branzei and Nisan (2017), The Query Complexity of Cake Cutting.


text:
Q: Lock down SFTP access on OpenSolaris I have an OpenSolaris 2009.06 server and I'd like to enable a user to remotely change files in a specific directory, ideally via SFTP or FTP-via-SSH. This user does not yet have an account on the machine and I'd like to create it so it's as restricted as possible. Is there a canonical way of doing this? I know about OpenSolaris' role-based access control and authorizations model, but I figure it's a lot of work (i.e., a lot I can mess up) to really lock down a full-blown user account (prevent fork bombs, make sure there's really no other file in the file system which can be written to...). Any hint is greatly appreciated.
Thanks, Simon

A: rssh is probably what you want.
It's a restricted shell with just enough functionality for file transfers and nothing else.


text:
Q: Problems with submit button in change_form template Django im new with Django and Python, and im still confuse about how to prepopulate values from manytomany field related lookup as my question in Prepopulate tabularinline with value from related lookup in manytomany field
here is my model:
class Product(models.Model):
    product_name= models.CharField(max_length=50)
    price = models.DecimalField(max_digits=10, decimal_places=2, default=Decimal('0.00'))
    tax_per_item = models.DecimalField(max_digits=10, null=True, blank=True, decimal_places=2, default=Decimal('0.00'))
    discount_per_item = models.DecimalField(max_digits=10, null=True, blank=True, decimal_places=2, default=Decimal('0.00'))

class Order(models.Model):
    produks = models.ManyToManyField(Product, verbose_name=u"Kode Produk")
    no_customer = models.ForeignKey(Customer, null=True, blank=True, related_name='%(class)s_kode_cust')

    def order_view(request):
        if 'enter' in request.POST:
            #response to tabular.html template
            return HttpResponseRedirect('/admin/POS/Pemesanan/inline')

class Foo(models.Model):
    product = models.ForeignKey(Product, editable=False)
    pemesanan = models.ForeignKey(Order)
    quantity = models.IntegerField()
    price = models.IntegerField()
    discount = models.IntegerField()
    tax = models.IntegerField()

and here is my admin:
class PemesananAdmin(admin.ModelAdmin):
fieldsets = (
    ('Customer in Time (Person)', {
        'fields': ('no_customer',),
    }),
    ('Date', {
        'fields' : ('date', 'delivery_date',),
    }),
    ('Order Details', {
        'fields' : ('produks',),
    }),
)
search_fields = ['produks', 'no_customer']
raw_id_fields = ('produks', 'no_customer',)
related_lookup_fields = {
'fk': ['no_customer'],
'm2m': ['produks'],
}
inlines = [
    FooInline,
]

class FooInline(admin.TabularInline):
model = Foo
template = 'admin/POS/Pemesanan/inline/tabular.html'
extra = 0
allow_add = True

and here is my change_form override template:
{% extends "admin/change_form.html" %}
{% block after_field_sets %}{{ block.super }}

<form action="" method="post">
<input type="submit" name="enter" value="Enter" />
</form>
{% endblock %}

But, still nobody can tell me how :(. (If you please response to my question on that page). And now, im confusing about 2 problems:
1. I want my submit button in change_form to redirect to change_form too a.k.a in the same page need no refresh page (not to change_list page or the actual submission).
2. How can i get instances of related lookup 'produks' fieldset (manytomany) from submit button so that i can access parent values (Class Product) and prepopulate all to tabularinline (Class Foo or intermediary class)?
FYI, submit button is below all fieldsets.
Anyone help me please :(. Thank you for your kindly responses :).

A: your problem is, that this
<form action="" method="post">
<input type="submit" name="enter" value="Enter" />
</form>

will just send your submit-button back to your server.
the form-tag needs to sorround every form-element.
just remove: <form action="" method="post"> and </form>
and it may work.

A: as i understand you correctly you want to display an order (Order) and its items (Foo)?
my naive solution would be:
class Product(models.Model):
   ...

class Order(models.Model):
   products = models.ManyToManyField(Product, through='Item')

class Item(models.Model):
   order = models.ForeignKey(Order)
   product = models.ForeignKey(Product)
   quantity = models.IntegerField()
   ...

and the admin could be as simple as this:
class ItemInline(admin.TabularInline):
    model = Item

class OrderAdmin(admin.ModelAdmin):
    inlines = (ItemInline,)

you need to test that, as i cant (actually)


text:
Q: Log in form with restricted-country.tpl and Geolocation with Prestashop 1.6 I got to build a log in form on restricted-country.tpl to access my website.
The form and the ajax call work great but it's impossible to call the php script 'cause a 503 error due to geolocation.
The script is in "controllers/front/".
Anybody knows how to grant access to the script or knows an area where I could put it and access it passing through the 503?
Or maybe call it in an other way?
(It's important that the log in form use Geolocation by ip)
Here is the form :

   <form class="form-signin col-xs-12 col-md-6 col-sm-12" id="everaccess_form">
      {l s='Mot de passe'}

            <input type="text" id="login" name="login" class="form-control" placeholder="Identifiant" required>
            <input type="password" id="password" name="password" class="form-control" placeholder="Mot de passe" required>
            <input type="hidden" id="IP" name="IP" class="form-control" value="">
            <input type="hidden" id="shop" name="shop" class="form-control" value="{$cart->id_shop}">
          <input class="btn btn-primary btn-block" type="submit" style="width:22.5%;" value="{l s='Se connecter'}" />

    </form>

Here is the ajax call :
form.submit(function(e) {
  $.ajax({
    type: 'POST',
    url: path_url+'/controllers/front/verif.php',
    data: form.serialize(),
    dataType: 'json',
    success: function(jsonData) {
      if (jsonData == 'OK'){
        console.log('Correct logins');
        location.reload();
      } else {
        console.log(jsonData);
      }
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      alert("Status: " + textStatus);
      alert("Error: " + errorThrown);
    }
  });
e.preventDefault();
});

Here is the script :
if (Tools::getIsset('password') || Tools::getIsset('login') || Tools::getIsset('IP') || Tools::getIsset('shop')) {

    $password = Tools::getValue('password');
        $login = Tools::getValue('login');
        $allowedUsers = EverCommission::getAllAgentLogin();
        foreach ($allowedUsers as $user => $mail) {
          $users[$user] = $mail['email'];
        }
            if ($password == Configuration::get('EVERCOM_COM_PASS') && in_array($login, $users)) {

                //Separator
                $separator = "\n";
                $idShop = Tools::getValue('shop');

                //Geolocalisation whitelist
                $whitelist = Configuration::get('PS_GEOLOCATION_WHITELIST');
                $WhiteListIp = Tools::getValue('IP');
                $New_WhiteList = $whitelist . $separator . $WhiteListIp;

                //Temp whitelist
                $Old_Temp_WhiteList = Configuration::get('PS_TEMP_WHITELIST');
                $New_Temp_WhiteList = $Old_Temp_WhiteList . $separator . $WhiteListIp;

                //Updating values
                Configuration::updateValue('PS_TEMP_WHITELIST', $New_Temp_WhiteList);
                Configuration::updateValue('PS_GEOLOCATION_WHITELIST', $New_WhiteList, false, null, $idShop);
                Configuration::updateValue('PS_GEOLOCATION_WHITELIST', $New_WhiteList, false, null, 'NULL');
                $return = 'OK';
            } else {
                $return = 'Wrong';
            }
        echo Tools::jsonEncode($return);
} else {
        $return = 'ID or Password not set using Ajax';
        echo Tools::jsonEncode($return);
}

Thank you very much.

A: Since your ajax call returns Error: temporarily overloaded, you might have a memory_limit problem on your configuration.

*

*Open your shop BackOffice

*Go to advanced parameters > Informations

*Check that the memory limit is over or equal to 128M

If the memory_limit is lower. You should edit your php.ini file.


text:
Q: Getting parent starting from src attributte i need to know if there's a way of getting parent starting with src attributte of img tag . I have something like : 6 draggable objects and 6 dropspots. At every drop i store in a variable src attribute of image i change. With this src i need to find its parrent and set .css("visibility", "visible"). My question : Is there a way to get parent of an img tag starting with its src attribute?
JS FIDDLE: http://jsfiddle.net/FncKS/
Code:
drop: function( event, ui )
            {
var dropTarget = event.target.id;
var getSrcChanged = $("#" + dropTarget).children('img').attr("src");
console.log(getSrcChanged);
}

Where console return : ../images/map6.svg (for example)
With this src attributte i would like to make one of draggable objects (the one with same src attributte) visible useing:
    var visible = $(dragObjects).children("img").src(getSrcChanged);
    $(visible).css("visibility", "visible");

But unfortunately it doesnt work :(
dragObjects its an array : 6 x div.children("img").
Some HTML:

...

A: I find your scenario very confusing, but it sounds like this is what you want to do:
drop: function( event, ui ) {
    var dropTarget = event.target.id,
        getSrcChanged = $("#" + dropTarget).children('img').attr("src"),
        matchingDraggable =  $(dragObjects).find("img[src='"+ getSrcChanged +"'");
    matchingDraggable.css("visibility", "visible");
    console.log(getSrcChanged);
}

Could you give that a try?


text:
Q: Deciding which node should have landscape When running the openstack-install a node is picked automatically from all those enlisted in MAAS to install landscape on. What are the pre-conditions for the auto-installer picking a node for landscape?
I'm currently using 7 physical nodes including 1 for MAAS and then another gets picked for landscape. The node that gets picked for landscape isn't always the best in my opinion as it could contain a lot of storage which would be wasted.
Is it possible to specify which node to use for landscape as part of the auto-installer?

A: Simple fix, after maas is deployed, only power on and commission the machine you want to be the landscape server.  Deploy landscape then commission the rest of the machines after you're in landscape.
I had to do this myself as it kept picking one of the more powerful machines from MAAS.  Landscape will deploy properly with only 1 machine listed in MAAS.

A: @bc2946088 has a good answer, but there is official support for this in the openstack-install command, I believe.
JUJU_BOOTSTRAP_TO=openstack-vm-bootstrap.maas sudo -E openstack-install

Found here: https://help.ubuntu.com/lts/clouddocs/installer/en/multi-install.html


text:
Q: drawing n balls randomly, *without* replacement from a bag containing b black balls and w white balls ---Part1 A bag has $b$ black balls and $w$ white balls. balls of the same color are indistinguishable.

*

*find, $z_k=$ the number of ways in which $n$ balls can be drawn randomly, without replacement from this bag containing $b$ black balls and $w$ white balls, when $k$ of the $n$ balls drawn are white

*find, $x=$ the number of ways in which $n$ balls can be drawn randomly, without replacement from this bag containing $b$ black balls and $w$ white balls

What I have done

*

*There is just one way of drawing $k$ white balls and $n-k$ black balls without replacement from this bag containing $b$ black balls and $w$ white balls, iff $\space k\leq w$ and $n-k \leq b$. And there are $\frac{n!}{k!(n-k)!}$ ways of ordering the $k$ white balls and $n-k$ black balls. So, the number of ways of ordering $n$ balls from a bag of $(w+b)$ balls, when $k$ of the $n$ balls are white is $$z_k = \frac{n!}{k!(n-k)!}\mathbb{I}\{k \leq w\}\mathbb{I}\{n-k \leq b\}$$

*obviously, $$x = \sum_{k=0}^nz_k = \sum_{k=0}^n \frac{n!}{k!(n-k)!}\mathbb{I}\{k<=w\}\mathbb{I}\{n-k<=b\}$$,  where $\mathbb{I}(x) =\begin{cases}
          1 & x=True \\
          0 & x=False
       \end{cases} $.
now, assuming  $n \leq b,n \leq w$, we have,
$$z_k = \frac{n!}{k!(n-k)!}$$ and $$x = \sum_{k=0}^nz_k = \sum_{k=0}^n \frac{n!}{k!(n-k)!} = \sum_{k=0}^n \binom{n}{k} = 2^n$$
my question is: are the calculations done above correct?

note:- the current question and this question are very similar. I know. the question I gave a link to is just too long to answer, I guess. So, I am trying to break down my question into small pieces so that they can be answered easily. I will change/delete the question(that I gave a link to) based on whether there is a mistake in the calculations done in this question.
edit:- the follow-up question to this question is here

A: This looks good to me. A quick way to check your work would be to solve the problem another way. For example, provided there are enough balls of each color, each of the $n$ balls you draw can be either of two options (black or white), thus there are $2^n$ many ways to draw them, agreeing with your answer.

I hope this helps ^_^


text:
Q: algo problem - fewest choice that maximizes score The problem statement is as follows:
science tournament is taking place where each team can design solar vehicle with following scoring system:

*

*you can submit 0 < D < 20 different designs to compete

*each design will be given different score penalty (based on weight, dimension, production cost, material used, etc)

*for every design submitted, penalty score will be applied immediately and the total penalty score will serve as each team's starting score. more design you submit, the higher the penalty score will be

*each design will run all available terrains, once each

*each design will be given score 0 - 100 based on how many km it travels in an hour on different terrains. there will be 0 < T < 30 terrains

*we get only 1 score from each terrain. if there are multiple designs in the same terrain, the highest score will be awarded

D #
penalty score
T1
T2
T3

D1
1
10
10
7

D2
2
8
8
12

D3
3
15
16
8

if we submit all 3 designs, the total penalty score for our team is 6, making our initial score -6
and our terrain scores:
T1      -> D3 15 points
T2      -> D3 16 points
T3      -> D2 12 points
penalty ->    -6
-------------------------+
total   ->    37 points
D1, even if its penalty score is the lowest, is actually useless, and we dont need to submit it in the first place, thus, we can score 38 points if we only submitted D2 and D3. we need to find the highest score we can get given D designs and T terrains. we can pick and choose which design(s) we want to submit into the tournament.
brute force will give you Big O of D!
is there any better way to solve this?
Thanks

A: This problem is NP hard.
To show that, let's reduce the set cover problem to this one.
Let's assign one terrain per element, and one design per set.  Every design has a penalty of 1.  A design will perform 1 on a terrain that is not in its set, and will perform 2 * number_of_designs on one that is.  It is straightforward to prove that the optimal tournament submission is the smallest set of designs corresponding to a set cover in the original design.  So if we can solve your problem efficiently, then we can find the minimal set cover.
I would suggest attempting some kind of branch and bound algorithm to solve this.  Either exactly or heuristically.


text:
Q: How to test dependent: :destroy with RSpec? I'd like to test my User models association has_many :projects, dependent: :destroy and have gone this far for now:
it "destroys dependent projects" do
  user = FactoryGirl.build(:user)
  project = FactoryGirl.build(:project)

  user.projects << project
  user.destroy

  expect(Project.count).to change(-1)
end

but this gives out an error:
Failure/Error: expect(Project.count).to change(-1)
     ArgumentError:
       `change` requires either an object and message (`change(obj, :msg)`) or a block (`change { }`). You passed an object but no message.

so I presume that change isn't the right matcher, is it? Can you please tell me how I could write this test without getting that error?

A: You can also use shoulda matchers:
it { expect(user).to have_many(:projects).dependent(:destroy) }

https://github.com/thoughtbot/shoulda-matchers

A: It is the right matcher, but you're not using it the correct way:

*

*expect needs to receive a block containing the action to perform (in your case deleting the user)

*change needs to receive a block that produces the numerical value that is expected to change (it can also receive an object and a symbol indicating that rspec should call the named method)

The correct way is
expect { user.destroy }.to change { Project.count }

This just asserts that the numerical value changes, but does not specify by how much. To do that, chain a call to by:
expect { user.destroy }.to change { Project.count }.by(-1)

A: This should work:
expect { user.destroy }.to change { Project.count }.by(-1)

A: You should test for the removal of the actual project.
expect(Project.all).not_to include project

A: This should work:
it { is_expected.to have_many(:projects).dependent(:destroy) }


text:
Q: UnhandledPromiseRejectionWarning: Unclear which file or line the warning is for I have been getting several errors similar to this one:
(node:30892) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 5): SyntaxError

From these questions (What is Unhandled Promise Rejection and NodeJS UnhandledPromiseRejectionWarning) it seems that these warnings are caused by not having a .catch on a promise after a chain of .then
However, these warnings do not have a file or line number where the problem lies. Is there any way to find this out/narrow it down?

A: You can catch the unhandled promise rejection warning, and use the given data to know where it happens.
process.on('unhandledRejection', (reason, p) => {
   console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
});

This gyus here tell us :


text:
Q: Program Guidance - DO WHILE loop I need some structural help! I know how to get what I need done but I can't decipher how to do it via a loop.
So I have a database of IDs in a text file. They are separated by lines for ease of reading. I need to read the ID, download a file based on that ID and date for a date range. I understand how to read the line using streamreader and can do that just fine for 1 file using 1 ID and date, I have that code working fine.
I was think of using a Do While loop but quickly realized that I can download each date for a single ID, I can't loop back to go to the next ID and do the same (or maybe I can and I just don't know how yet)...
The download is based on DateTimePicker2 value. So basically this needs to download the file from ftp://ftp.address.net/UserID/yyyyMMdd.txt.
Sorry to take back a solution but this code reads line 1, attempts to download the file and then stops.
For Each strUserID As String In System.IO.File.ReadAllLines("database.txt")
Dim myDate As DateTime = DateTimePicker2.Value
Do While myDate < DateTimePicker3.Value
    Dim ftpAddr As String = "ftp://ftp.address.net/" & strUserID & myDate.ToString("yyyyMMdd") & ".txt"
    Dim myPath As String = "MyFolder'" & strUserID & myDate.ToString("yyyyMMdd") & ".txt" 'or whatever the path should be
    Try
        My.Computer.Network.Download(ftpAddr, myPath)
    Catch nullDownload as IO.IOException
    Continue For
    End Try

    If My.Computer.FileSystem.Exists(myPath)
        For Each line as String In System.IO.File.ReadAllLines(myPath)
            DataGridView1.Rows.Add(line.Split(","))
            Next
        End If

        myDate.AddDays(1)
    Loop
Next

I basically need to loop the loop again using the next line in the database.txt.
Edit: Quick summary of what I'm trying to do:

*

*Read the ID starting from line 1 in the database.txt
  1a. Download the file based on DateTimePicker2 value (ftp://ftp.address.net/userID/yyyyMMdd.txt)
  1b. Write it to the DataGridView
  1c. Add 1 to the date and repeat from step 1a, repeating until  DateTimePicker2 > DateTimePicker3

*Read the next ID in the database.txt and loop steps 1a-1c but from the initial chosen date.

A: You need two loops. An outer loop to process each UserID, and an inner loop the process all dates with that UserID.
If each UserID is a separate line in the text file, you can use File.ReadAllLines to read them into an array and use a For Each loop to process each UserID. Then make sure that each time you pick a new UserID, you set the date back to the initial date.
For Each strUserID As String In System.IO.File.ReadAllLines("database.txt")
    Dim myDate As DateTime = DateTimePicker2.Value
    Do While myDate < DateTimePicker3.Value
        Dim ftpAddr As String = "ftp://ftp.address.net/" & strUserID & myDate.ToString("yyyyMMdd") & ".txt"
        Dim myPath As String = "MyFolder'" & strUserID & myDate.ToString("yyyyMMdd") & ".txt" 'or whatever the path should be
        Try
            My.Computer.Network.Download(ftpAddr, myPath)
        Catch nullDownload as exception
        End Try

        If My.Computer.FileSystem.Exists(myPath)
            For Each line as String In System.IO.File.ReadAllLines(myPath)
                DataGridView1.Rows.Add(line.Split(","))
            Next
        End If

        myDate.AddDays(1)
    Loop
Next

[Edit]
I have edited to code to match the edited version of the question. The name of the file to be downloaded is based on the UserID and the date.


text:
Q: Calculate the distance for each x and y coordinate I am writing a function that calculates distance from x and y coordinate. I have a two dimensional array that has bunch of x and y coordinates.
Function returns a list of x and y coordinates in the order of distance from a point. To calculate the distance from each point there is a formula(Square root of sum of coordinates).
I can calculate the distance for each x and y coordinate. I am adding that to list. How do I store distance as another property as it is for that particular coordinate and then sort it.
public static List<List<int>> calculateDistance(int[,] Coordinates)
        {
            List<List<int>> result = new List<List<int>>();
            int bound0 = Coordinates.GetUpperBound(0);
            List<double> distance = new List<double>();

            for (int i = 0;i <= bound0; i++)
            {
                distance.Add(Math.Sqrt(Coordinates[i, 0]) + Coordinates[i,1]));
            }

            return result;
        }
    }

A: Based on your description you don't need to create a calculateDistance method. Formula to calculate distance can be given with lambda expression. Anywhere in your code you can create the list you need and get it sorted with Linq.
Example
var list = Enumerable
                .Range(0, Coordinates.GetLength(0))
                .Select(i => new { X = Coordinates[i, 0], Y = Coordinates[i, 1], D = Math.Sqrt(Math.Pow(Coordinates[i, 0], 2) + Math.Pow(Coordinates[i, 1], 2)) });

Math.Sqrt(Math.Pow(Coordinates[i, 0], 2) + Math.Pow(Coordinates[i, 1], 2)) is used here for demonstration. Instead use your own expression to calculate the distance.
To sort this you can simply use
var list2 = list.OrderBy(a => a.D);

A: It would be more helpful if you try to define proper data structures for your inputs and your output. It could be something as simple as a tuple, or something more idiomatic like a struct or a class.
struct Coordinate {
    public Coordinate(int x, int y) {
        X = x;
        Y = y;
    }

    public int X { get; }
    public int Y { get; }
}

Then define a result structure, something like:
struct Result {
    public Result(Coordinate coordinate, double distance) {
         Coordinate = coordinate;
         Distance = distance;
    }

    public Coordinate Coordinate { get; }
    public double Distance { get; }
}

Then you can create a list of those result items like:
public List<Result> ComputeDistances(List<Coordinate> coordinates) {
    List<Result> results = new List<Result>();
    foreach (var coordinate in coordinates) {
        double distance = Math.Sqrt(coordinate.X + coordinate.Y); // *
        results.Add(new Result(coordinate, distance));
    }
    return results;
}

(*) Note that the specified distance function is a little bit odd. Normally you would like to sum the squares of the X and Y coordinate
If you like a more functional style, you can change that code quite a bit:
public IEnumerable<Result> ComputeDistances(IEnumerable<Coordinate> coordinates) {
    return from coordinate in coordinates
        let distance = Math.Sqrt(coordinate.X + coordinate.Y)
        select new Result(coordinate, distance);
}

Changing from List to IEnumerable allows you with the proper care, to delay the execution of the computation.
After you have the sequence of results, the easiest way to sort them is using the OrderBy extension method.
public IEnumerable<Result> SortByDistance(IEnumerable<Result> results)
{
    return results.OrderBy(result => result.Distance);
}

And then combine all:
List<Coordinate> coordinates = .... // get the list of coordinates somehow;
IEnumerable<Result> distances = ComputeDistances(coordinates);
IEnumerable<Result> sortedByDistance = SortByDistance(distances);
// if you want to get back a list, in order to avoid enumerating multiple times
List<Result> results = sortedByDistance.ToList();


text:
Q: Determine which prepared statement causes an error in a try/catch In the catch clause, how do I determine which prepared statement caused the error so that I could apply debugDumpParams on it?  See the below example.
$p1=db::db()->prepare("INSERT INTO t1 (a,b,c) VALUES (:a,:b,:c)");
$p2=db::db()->prepare("INSERT INTO t2 (a,b,c) VALUES (:a,:b,:c)");
try{
    $data=array('a'=>1,'b'=>2,'c'=>3);
    $p1->execute($data);
    $p2->execute($data);
}
catch(PDOException $e){
    //Display debugDumpParams() for the statement that caused the error
}

A: To determine which query fails execute them in different try catch blocks.
$data=array('a'=>1,'b'=>2,'c'=>3);

$p1 = db::db()->prepare("INSERT INTO t1 (a,b,c) VALUES (:a,:b,:c)");
try {
    $p1->execute($data);
} catch(PDOException $e) {
    // Display debugDumpParams() for the statement that caused the error
    // First query has failed
}
$p2 = db::db()->prepare("INSERT INTO t2 (a,b,c) VALUES (:a,:b,:c)");
try {
    $p2->execute($data);
} catch(PDOException $e) {
    // Display debugDumpParams() for the statement that caused the error
    // Second query has failed
}

A: You could check error code of each statement. (read documentation about codes of your DB). null means that statement was not executed.

A: If you are going to catch PDOException you might as well include prepare() in the try catch, and you should also  use one query to inserts if possible.
Prepare returns false when it fails so check the value of $p and throw exception


text:
Q: python negative number divide the number than itself the result is always -1 i have a question about division of negative number in python3
when I do the calculation for 6//(-132) why it is -1 intead of 0 .
what is the mechanism that python deal with this division?

A: In fact, you're not using Python 3.x, you're using Python 2.x and what you see is the result of integer division, which was the default back then:
>>> 1/(-2)
-1
>>> -1/2
-1
>>> -23/45
-1

To get the expected results in Python 2.x, try this:
from __future__ import division

>>> 1/(-2)
-0.5
>>> -1/2
-0.5
>>> -23/45
-0.5111111111111111

Now, for the question after the edit: When you do integer division // the value will be rounded down toward the negative value of -1. (this is also known as "floor division"). See this post for further details.
>>> 6 / (-132)
-0.045454545454545456
>>> 6 // (-132)
-1

A: Well most probably you are not using python 3 because in my idle python 3.8 on 1/-2 it shows -0.5 and the same in case of -1/2

A: In the remainder operation the python always takes the floor or the greatest integer function as the answer


text:
Q: setting variables with argv Here is a minimal working example describing my current situation. The file main.cpp
#include <iostream>
void print_from_external_file();

using namespace std;

int main( int argc, char* argv[])
{
    print_from_external_file();

    return 0;
}

The file containing print_from_external_file()
#include <iostream>
using namespace std;

namespace
{
    int a;
}

void print_from_external_file()
{
    cout << a << endl;
}

Here is my goal: I wish to run this program by command line like "test.exe 2". The integer 2 I want to be loaded into the variable a in the external file. Is there a way to accomplish this without having to call print_from_external_file() with argv[1]? In other words, can "a" be given the value "2" automatically?

A: If you can change the file where the variable "a" is defined then put the variable to a non-anonymous namespace or define an exported getter in the same file (same1.cpp or same2.cpp below). Otherwise you won't be able to set it the way you want.
some1.cpp:
namespace {
   int a;
}
void set_a(int a_) { a = a_; }

some2.cpp:
namespace some {
   int a;
}

main.cpp:
#include <cstdlib>

namespace some {
  extern int a;
}

int main(int argc, char** argv) {
  assert(argc == 2);

  some::a = atoi(argv[1]);
  // or: set_a(atoi(argv[1]));
  return 0;
}

A: You will have to name your namespace. Unnamed namespaces are tied to their translation units, so you will not be able to access the variable in it from another unit.
Your .cpp:
#include <iostream>
#include <stdlib.h>
#include "main.h"
void print_from_external_file();

using namespace std;
using ddd::a;

int main( int argc, char* argv[])
{
    a = atoi( argv[1] );
    print_from_external_file();

    return 0;
}

Your .h:
#include <iostream>
using namespace std;

namespace ddd
{
    int a;
}
using ddd::a;

void print_from_external_file()
{
    cout << a << endl;
}

Alternatively you can get rid of the namespace, and use extern int a in your .cpp file to get access to the variable:
.cpp
#include <iostream>
#include <stdlib.h>
#include "main.h"
void print_from_external_file();

using namespace std;
extern int a;
//the rest goes unchanged

.h:
#include <iostream>
using namespace std;

int a;
//the rest goes unchanged

A: I think what you are looking for is the use of the extern keyword.
If you declare in your main a as an extern variable you should be ok.
#include <iostream>
void print_from_external_file();

using namespace std;

extern int a;

int main( int argc, char* argv[])
{
   //set value of a
   a = atoi(argv[1]); //atoi is deprecated but is easier to use in an example

    print_from_external_file();

    return 0;
}

EDIT
In the second file you need to remove the namespace or specify a name for it.
I tested using the following code for the second file and it worked as expected
#include <iostream>
using namespace std;

namespace
{
    int a;
}

void print_from_external_file()
{
    cout << a << endl;
}

EDIT 2: Code using namespace
File 1
#include <iostream>
void print_from_external_file();

using namespace std;

namespace TEST
{
    extern int a;
}

int main( int argc, char* argv[])
{
    //set value of a
    TEST::a = atoi(argv[1]); //atoi is deprecated but is easier to use in an example

    print_from_external_file();

    return 0;
}

File 2
#include <iostream>
using namespace std;

namespace TEST
{
    int a;
}

void print_from_external_file()
{
    cout << TEST::a << endl;
}

A: yes you can.
for integers you have to use std::atoi().
so the code becomes:
int a = std::atoi(argv[1]);

A: If you are using windows,
namespace
{
    int nArgs = 0;
    int a = wtoi(CommandLineToArgvW(GetCommandLineW(), &nArgs)[0]);
}

For the sake of brevity I skipped all error checking.

A: Standard practice is to use argv to access the command line arguments. You may find on some architectures that there are other way of doing this but they are not likely to be portable and there doesn't seem to be much reason here not to go with the standard practice. To read the value into an int you can either use strtol
long n = strtol( argv[1], NULL, 0 );

(note that I tend to prefer using strtol to atoi as you've a little more control over the inputs and the error handling - but not much)
You can also use streams as follows:
istringstream ss( argv[1] );
long n;
ss >> n;

Two things do concern me about what you're trying to do though: Firstly you want a variable value, set at runtime to be encapsulated within a function. Logically this will make your code less maintainable as there will be an invisible dependency between your function and an outside influence (a command line parameter) - so the deterministic properties of your function will have been compromised. Practically, this is going to make testing your function far more difficult - especially using automated unit testing as there will be no way of setting the value programatically prior to running it.
Secondly, as if to compound this, you are seeking to restrict scope of the a variable to compilation unit within the unnamed namespace. This has two undesirable effects. Firstly, no test harnesss or any other code is going to be able to see this variable so again from an automated UT standpoint, this is pretty bad. Secondly, a becomes effectively a 'global' within your compilation unit. Within functions in this compilation unit, it's going to be quite tricky to follow how and when a is used meaning a bit of a headache for anyone who maintains your code. I'll assume that you're not using multithreading which would really cause problems.
I'd be interested to know the reasons why you don't want to pass argv[1] into print_from_external_file() but I really think that this is the best thing to do. If you don't feel you can pass this variable either directly as a string or converted to an int, you could consider creating a command line parameters or configuration object which could be passed in:
configuration c( argc, argv ); // This contains the hard work of parsing the CL
print_from_external_file( c );

This hides most of the hard work of parsing the command line. Better still it allows you to add real meaning to the CL parameter. Let's say that the a variable represents a catalog number, the constructor of yourconfiguration class can simply do this:
configuration::configuration( int argc, char* argv[] )
{
    // ...
    catalogNo_ = strtol( argv[1], NULL, 0 );

and then if an accessor is added:
int configuration::get_catalog_no() const { return catalogNo_; }

then it becomes much more obvious in print_from_external_file() what we're doing:
void print_from_external_file( const configuration& c )
{
    cout << c.get_catalog_no() << endl;
}


text:
Q: Browser Same Origin Policy - why is RSS data considered dangerous? Modern browsers prevent scripts fetching RSS feeds from sites out of the domain of the running script.
The RSS feed gets transmitted but the browser's Same Origin Policy won't let you access it.
Only feeds from servers that specify the CORS Access-Control-Allow-Origin header can be read.
Why?
We are not talking about malicious scripts - just XML data.
What is the thinking behind considering an RSS feed as a potential danger?
How could it be exploited?

A:
Only feeds from servers that specify the CORS Access-Control-Allow-Origin header can be read.

so all major web-browsers implement a blanket block just so that insecure servers don't leak otherwise publicly available feeds? Still does not make much sense to me.

By default, the Same-Origin Policy won't let a client read the response to a cross-origin request, regardless of whether the requested resource is publicly accessible. CORS is a protocol for the server to instruct a browser to selectively relax some of the Same-Origin Policy's restrictions (both in terms of reading and sending) on network access to a resource from some requesting client.
There's nothing special about an RSS feed. In the case you describe, it's just one cross-origin resource among others. Carving out an exception for RSS feeds in the SOP would have needlessly complicated it.

The RSS can still be downloaded using a download manager or even wget. That does not make any sense.

True, but the SOP was never meant as a substitute for server-side access control; for one thing, it's only enforced in browsers, not in other user agents like curl or Postman. Rather, the SOP is meant to protect Web origins from one another.

why is RSS data considered dangerous?

We are not talking about malicious scripts - just XML data. What is the thinking behind considering an RSS feed as a potential danger? How could it be exploited?

You've got it backwards. The SOP's restrictions on network access are not meant to defend the client against a malicious resource. Instead, they're meant to defend the resource against a malicious cross-origin client, which might for example attempt to exfiltrate data from the resource.
If you control the resource in question, you can override the default behaviour of browsers and configure CORS to allow clients from any Web origin to read the response from the requested resource.

ajax preceded CORS by several years. Ajax W3C Standard 2006; CORS W3C Standard 2014. I know I was programming way back then!

Support for cross-origin requests with AJAX only came later than 2006, prompting the need to devise the CORS protocol. See XMLHttpRequest Level 2, W3C Working Draft 25 February 2008:

XMLHttpRequest Level 2 enhances XMLHttpRequest with new features, such as cross-site requests [...]

(my emphasis)
Note that "cross-site" should be understood as "cross-origin", here. The difference matters now that "site" has a more technical meaning.
Besides, CORS support was added to major browsers in the later 2000s. It didn't wait until the 2014 W3C standard.

A: First a big thanks to all the commenters and to @jub0bs for his considered and detailed answer.  You all gave me a lot of food for thought.
However it has since dawned on me that XML data such as RSS can embed text that contains <script> tags and those tags, once fetched, might be inadvertently inserted verbatim (using innerHTML or similar DOM methods) - and this would be equivalent to any other Cross-site script (XSS) exploit.
So RSS should be considered dangerous.
The remedy according OWASP is not to use innerHTML when incorporating fetched data.


text:
Q: GridView центровать контент, с сохранением стиля и шаблона Есть GridView, когда выглядит вот так:
<ListView x:Name="Accounts" Margin="8" Grid.Column="0"
                  ItemsSource="{Binding Storage.Accounts}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="По умолчанию">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <RadioButton GroupName="DefaultAccount" Width="100"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
...

Выглядит это, с применением стиля MD вот так:

Необходимо сделать так, что-бы RadioButton был посередине столбца. HorizontalAlignment="Center" не работает.
Если погуглить, и применить этот код:
<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    </Style>
</ListView.ItemContainerStyle>

То мы потеряем стиль, предоставляемый Material Design'ом.
Если же прописать BasedOn="{StaticResource {x:Type ListViewItem}}", то вся строка будет выглядеть как простой TextBox, в который написали название класса. Как сделать это правильно?

A: <ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem" BasedOn="{StaticResource MaterialDesignGridViewItem}">
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
    </Style>
</ListView.ItemContainerStyle>

Как я узнал название стиля? Запускаем приложение, открываем окно Live Visual Tree, находим в дереве ListViewItem

Открываем окно Live Property Explorer и смотрим значение свойства Style


text:
Q: Why can't this code access my JSON file in netbeans? So I am trying to learn Javascript. I created a JSON file called "Ancest.json". Then, in a new file on netbeans I tried to execute this code accessing that file:
var ancestry = JSON.parse(Ancest);
console.log(ancestry.length);

I am getting a rejection saying "Ancest is not defined".
What am I doing wrong? Attached is a screen shot. Thank you for your time.

A: JSON.parse method accepts a string which is the JSON object to be parsed into a JavaScript object.
You need to get the content of the file or to move the content of your JSON file into a string variable in the js file. Then you can parse it:

console.log(JSON.parse('{ "a": "test" }'));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

A: You need to assign a string Ancest or var Ancest = './Ancest.json'; Depending on the location and path of Ancest.json, you may have to put in the full path or linked path if the .js file exists in the same path. Also put the path in single quote or double quote. Make sure you have access to read the file.
It also needs correct file system permissions. This is all contingent on who this js is running as, delegate permissions on the parent directories, etc, etc. Chances are permissions are okay for read.


text:
Q: Cordova Build Error: More than one library with package name 'com.google.android.gms I am developing android application with cordova, I need google plus login and admob feature in my my app ,
So I add the following plugins
1) admobpro
2) cordova-plugin-googleplus
Is it necessary to add google play service plugin to use the above plugin ?
After I added Google play service plugin and build the app using cordova CLI
I got the following error,
> FAILURE: Build failed with an exception.
>
> * What went wrong: Execution failed for task ':processDebugResources'.
> > Error: more than one library with package name 'com.google.android.gms' You can temporarily disable this error with
> android.enforceUniquePackageName=fal se However, this is temporary and
> will be enforced in 1.0
>
> * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

kindly help me,

A: I think the problem with google play service plugin i added, google play service is also loaded as dependent plugin with googleplus login plugin, so there occurred a conflict between these two google play service plugins.
I removed all plugins and added google plus login first and then add admobpro, now i can successfully  build the app with no exception.