text:
Q: Add the database layer to your application with a service or include it directly? I am planning to set up a new Web-application that contains the following things:
I want to use JavaEE with JSF for the Frontend & Backend combined with git-hooks to deploy them onto my server. Also it seems to be useful to integrate the Spring-Framework whenever you use JEE. Now additionally, I need some database interaction. Now I have two possibilities:

*

*Set up an Rest-API combining Java, Hibernate and Spring (at least that is what my research told me).

*Simply add a Hibernate layer to my application.
Why would you use method 1? So for me, there are the following things to do when picking this method:

*

*Communication with JSON, so you need a mapper on both sides

*Since I want to pass objects, I would need to define a class (lets say "book") on both servers - wouldn't that be redundant?

*Include security mechanisms for the API

*Set up an additional server for the service

In method 2, I would not need any mappers or security mechanisms for the connection to the API, or did I get that wrong? So why would people use the method 1?

A: The answer for such question cannot be short, so let's start with the terms:

*

*frontend - software subsystem directly interacting with user. In consumer applications term "frontend" usually refers to an application running in a web browser or to a mobile application.

*backend - software subsystems that do not interact with user directly. As a backend software developers usually consider the application server or microservice plus a database and related services (e.g. message queue or distributed cache).

*JavaEE - is no longer known as such. Modern name for this technology stack is JakartaEE (https://www.jakarta.ee) This is a group of specifications of various APIs in Java, which greatly vary in popularity and use: pure JEE project today is not a common thing - according to many surveys, only Servlet and JPA APIs are widely used as part of Spring/Hibernate combo.

*JSF - more often hated than loved UI framework that is in steady decline for last 5 years due to limitations of its architecture. I would not recommend to start a new project on JSF and look for a more mainstream solution.

*A layer in software architecture - logically separated part of the application that performs a specific role. In Java applications layers are typically represented by specific packages or even jar modules. One of the examples of layers is persistence layer, which represents an object-oriented abstraction of a database. By definition layer is not a separate application, so your option 1 does not make sense as a solution to interact with database. Hibernate as a database layer however does make sense. Please note, that Hibernate is a popular implementation of JPA API from JEE, so if you are already on JEE stack, you either already use it or don't need it, because you use some other implementation (e.g. EclipseLink).

Now, let's talk about the architecture in general. Your option 1 is a modern and the most popular solution for the whole application. Spring is a framework of choice for majority of Java developers according to recent surveys (including SO), with more and more of them choosing Spring Boot as a complete technology stack and alternative to JEE. Hibernate is one of the popular options for persistence there, but there are others - check the Spring Boot reference guide (https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/).
Building a REST API on the backend (Spring Boot/Hibernate), that can be consumed by your frontend is one of the easiest ways to develop interactive web applications today, but of course not the only one - choice of the particular solution should always be based on business requirements. For web applications displayed in browser the frontend is usually written on JavaScript or related languages (e.g. TypeScript) with one of the many frameworks that exist there (check Angular and ReactJS).
The considerations for option 1 that you mention:

*

*JSON mapping is pretty straightforward. In the frontend it's automatic, in the backend easily implemented with the libraries like Jackson - comes out of the box with Spring Boot.

*You will have just one server, either providing REST API to JS-based frontend or implementing server-side rendering (in JEE via JSF/JSTL, in Spring Boot - with Thymeleaf).

*Security is a business requirement. If you need to protect some data, implementation of it must be present. With Spring you can use Spring Security with various options.


text:
Q: Why is there no update for Firefox? Firefox 85.0 was released 6 days ago and still there is no update.
Is something wrong?
I'm using Ubuntu 20.04.1 LTS.

A: It seems that Canonical has been slow to package the update. You can check the current status of any official package at packages.ubuntu.com. For example,
https://packages.ubuntu.com/source/focal/firefox
It currently tells that the latest available package for 20.04 LTS is
84.0.2+build1-0ubuntu0.20.04.1
If you want to know why it's taking longer than expected, you probably have to search for it in launchpad.net. For example, according to https://launchpad.net/ubuntu/+source/firefox/
version 85 has been in proposed state since 2021-01-18 but for some reason it has not yet entered main repository which you probably have enabled.
If you want Firefox updates faster than the usual Canonical QA process can handle, you probably want to add PPA: https://launchpad.net/~ubuntu-mozilla-security/+archive/ubuntu/ppa
However, note their description:

Staging PPA for Mozilla and other browser-related security updates.
Unless you are testing updates, you should NOT install packages from
this PPA.

After searching for "firefox 85" in bugs, I found this:
https://bugs.launchpad.net/ubuntu/focal/+source/cargo/+bug/1901571
It seems that building new Firefox packages requires upgrading rustc and cargo, too, which requires those dependencies to be upgraded before Firefox can be upgraded. This is an another example where Ubuntu is getting hurt for not being rolling release distribution and at the same time still trying to keep Firefox updated to latest version. They end up requiring to upgrade some other packages, too, but because this is not officially allowed by no-rolling-release rules they get extra delays for cases like this because they need to coordinate all changes across multiple packages.
If there were some important security patches, those would be handled separately and backported manually if needed to avoid such stalls.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding text above background image to uiswitch My custom UISegmented control has background images [for each state]. How do I add text above the images [for each state, meaning that when index 0 will be selected I will have a specific color and font] ?
Here's how my UISegmented control looks like:
UISegmentedControl *customUISC=[[UISegmentedControl alloc] initWithItems:[[[NSMutableArray alloc] initWithObjects:@"ON",@"OFF",nil] autorelease]];

    [customUISC setFrame:CGRectMake(11,14,298,28)];
    customUISC.selectedSegmentIndex=0;
    customUISC.segmentedControlStyle=UISegmentedControlStyleBar;

    [customUISC setImage:[UIImage imageNamed:@"FirstTabActive.png"] forSegmentAtIndex:0];
    [customUISC setImage:[UIImage imageNamed:@"SecondTab.png"] forSegmentAtIndex:1];
    [customUISC addTarget:self action:@selector(checkOnOffState:) forControlEvents:UIControlEventValueChanged];

and the checkOnOffState method looks like:
-(IBAction)checkOnOffState:(id)sender{

UISegmentedControl *iSeg=(UISegmentedControl *)sender;

if(iSeg.selectedSegmentIndex==0){

    [iSeg setImage:[UIImage imageNamed:@"FirstTabActive.png"] forSegmentAtIndex:0];
    [iSeg setImage:[UIImage imageNamed:@"SecondTab.png"] forSegmentAtIndex:1];
}
else {

    [iSeg setImage:[UIImage imageNamed:@"FirstTab.png"] forSegmentAtIndex:0];
    [iSeg setImage:[UIImage imageNamed:@"SecondTabActive.png"] forSegmentAtIndex:1];
}
}

A: I'm not sure I fully understand what you're after, but could you just make use of UILabels (positioned above the images). You could then change the colours and text quite easily using myLabel.text and myLabel.textColor.
Hope this helps in some way!


text:
Q: Sorting items in list view just work in detail view I use this code to sorting items in list view control, but it just work in detail view , for other views nothing happened. did I missing something?
Note:FileListItem  is a class inherit from ListViewItem.
public class ListViewItemComparer : IComparer
        {
            private SortOrder sortOrderAcDe;
            private SortBy sortByProperty;
            //
            public ListViewItemComparer(SortOrder sortOrder, SortBy sortBy)
            {
                sortOrderAcDe = sortOrder;
                sortByProperty = sortBy;
            }
            //
            public int Compare(object x, object y)
            {
                FileListItem itemX = (FileListItem)x;
                FileListItem itemY = (FileListItem)y;

                int result = 0;

                //x is directory , y is file
                if (itemX.IsDirectory && !itemY.IsDirectory)
                {
                    return -1;
                }

                //x is file , y is directory
                if (!itemX.IsDirectory && itemY.IsDirectory)
                {
                    return 1;
                }

                //both are directories
                if (itemX.IsDirectory)
                {
                    switch (sortByProperty)
                    {
                        case SortBy.Name:
                            result = String.Compare(itemX.Name, itemY.Name, false);
                            break;

                        case SortBy.Size:
                            result = String.Compare(itemX.Name, itemY.Name, false);
                            break;

                    }//switch
                }//if

                //both are files
                if (!itemX.IsDirectory)
                {
                    switch (sortByProperty)
                    {
                        case SortBy.Name:
                            result = String.Compare(itemX.Name, itemY.Name, false);
                            break;

                        case SortBy.Size:
                            result = CompareLong(itemX.Size, itemY.Size);
                            break;

                    }//switch
                }//if

                //ifDescending
                if (sortOrderAcDe == SortOrder.Descending)
                {
                    result = -result;
                }

                //return
                return result;
            }
            //
            private int CompareLong(long x, long y)
            {
                if (x < y)
                    return -1;

                if (x > y)
                    return 1;

                return 0;
            }
        }

then I use this code for calling
 public void SortItems(SortOrder sortOrder, SortBy sortBy)
    {
        this.ListViewItemSorter = new ListViewItemComparer(sortOrder, sortBy);
    }


text:
Q: what does $this-> mean? What is the function of $this-> operator here? is it point that variable?
Can someone explain the code below:
if(isset($this->mDbPort))
{
  $this->mDbHost .= ":" . $this->mDbPort;
}

A: $this-> refers to the object instance.
$this->mDbPort refers to the mDbPort property of the object this code is a part of.
PHP Manual :: Objects and Classes


text:
Q: Setting up GIT and workflow for bigger web based application We have a biggish internal web based system that currently is maintained by a team of 3 developers.
Our current setup is 1 development server and 1 production server - possibly soon 2 prodution servers behind load balancer.
Our current workflow is all developers update files live on dev server. Whenever we are ready with the changes we rsync codebase to production.
We develop fast and change things very often. For quite some time we've been wanting to start using version control to have more control over the changes we make and the overall code quality. The only question is how to do it properly and
what would be the most efficient way since we still have to keep things moving fast.
Some of the question I have are:

*

*Our main codebase contains directories with 3rd party libraries, images etc. We rarely touch them. Should these be tracked as well?

*Is it ok to have just one master branch to work on? So every dev would use master branch that will be pulled to Main Dev and then to Production.

*Should production be setup as bare repo or it doesn't matter?

Here's the setup I came up with. Please let me know what you think and suggest improvements.

A:  all developers update files live on dev server. No source control
At'a Boy to you for fixing your architecture and workflow. I was in this exact situation in a long ago job.

*

*Yes, you should definitely checkin your 3rd party libraries, images etc. You rarely touch them because the world comes to a crashing end if you update them. You can't bring a second production server online unless you can build it exactly like the first one. Every thing need to be running the same version of all the same software. In my project we had everything that got installed on the server in source control.

*Yes it's ok to just use master, you don't want to change too many moving parts at one time. As time goes bye revisit this to see if your ready / need a branching workflow.

*You can't use a bare repo. There would be no files for the web server to run off of.
Great job, good questions and design.
I would definitely use sub domains for each developer. Another place I worked at, a commercial software company, wicked smart people, did it this way.
My one suggestion would be to have stage.project.com running on the Production server. It would use the production data sources and let you test in a production environment.
Also everyone on the Team should have to watch. Git ages 4 and up http://www.youtube.com/watch?v=1ffBJ4sVUb4 and for extra credit watch Advanced Git http://vimeo.com/37408017

A: What I don't like about your plan is the deployment stage. Why? Because 1) it's a manual process and 2) it's pull-based. I'm also not sure what I think about version control repositories on a production server.
What I would like to suggest is to build a little script that rsyncs to the production servers, including rsync's --delete and --exclude .git/ options. If you wanted, you could write the SHA1 of the current commit to a little file so you can always know what is online.
Ideally, that script wouldn't sync directly to your document-root, but to a freshly created directory that you then symlink your document-root to. Name that directory using a timestamp and maybe the commit SHA-1. That way, if anything doesn't work out the way it was supposed to, you just have to adjust the target of your symlink.


text:
Q: How check if ACCESS_RESTRICTED_SETTINGS is enabled? Is there some Java code to check if the ACCESS_RESTRICTED_SETTINGS permission is enabled?

A: public static boolean hasAccessRestrictedPerm(Context context) {
    try {
        PackageManager packageManager = context.getPackageManager();
        ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
        AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOpsManager.checkOpNoThrow("android:access_restricted_settings", applicationInfo.uid, applicationInfo.packageName);
        return (mode == AppOpsManager.MODE_ALLOWED);
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
}


text:
Q: Java 8 : Stream.filter not running as expected Given:
    List<String> str = Arrays.asList ("my", "pen", "is", "your", "pen");
    Predicate<String> test = s -> {
        int i = 0;
        boolean result = s.contains ("pen");
        System.out.print((i++) + ":");
        return result;
    };

This prints: 0:0:
    str.stream().filter(test).findFirst();

And this prints 0:0:0:0:0:
    str.stream().filter(test).collect(Collectors.toList());

What confuses me is, no matter it is findFirst or collect, no matter the terminal operation is short-circuiting or not, they both should iterate through each item in the list, right?
So why "0:" is printed twice, not just once, not 5 times, in the first example findFirst?

A:
What confuses me is, no matter it is findFirst or collect, no matter the terminal operation is short-circuiting or not, they both should iterate through each item in the list, right?

Ability to return without examining the entire stream is exactly what makes an operation (like findFirst) short-circuiting.  See Streams javadoc.
Streams documentation actually makes no promises about how or whether your predicate will be evaluated.  It just guarantees that it will return the first element of the stream that matches the predicate.

A: The idea of the first Stream is iterate to find the first occurrence of "pen", so the Predicate iterates the array until finds the first element which matches the condition of the filter. For that reason, you see only two "0:". Official documentation


text:
Q: How to get number of packets received, Average round trip time from ping command if I use popen I have to ping the given IP address and I need to print the below values in C++. It is fine to use popen and get the output.
1) Average Response Time
2) Data Block Size
3) Failure Count
4) Max. Response time
5) Min. Response time
6) Number Of Repetitions
7) Success Count
8) TimeOut

If I use popen, I will get a file pointer and I need to read on this file pointer to get the whole output and I have to extract the values using some string manipulation. Can any one please let me know if there is any other way instead of using string manipulation? Is there any data structure will be maintained by Operating System through which I can get the values after executing ping command?

A: I can't think of a BETTER way than extracting the results from the string your read. Exactly the BEST way to parse the string, I'm not sure of [mostly because I haven't spent much time thinking about that!]
An alternative is of course to write your own internal implementation of ping, but I'm fairly sure that is a whole lot more work than using a parser on the popen on the system ping - unless you want VERY portable code [but that'd then also require a very portable networking package, since native networking is not very portable either].


text:
Q: writing petgraph Dot to a file I may be missing something very basic -- I am new to Rust.  I'm attempting to write a petgraph::dot::Dot representation to a file.
The following small code example doesn't compile:
use petgraph::Graph;
use petgraph::dot::{Dot, Config};
use std::fs::File;
use std::io::Write;

fn main() {
    println!("hello graph!");
    let mut graph = Graph::<_, ()>::new();
    graph.add_node("A");
    graph.add_node("B");
    graph.add_node("C");
    graph.add_node("D");
    graph.extend_with_edges(&[
        (0, 1), (0, 2), (0, 3),
        (1, 2), (1, 3),
        (2, 3),
    ]);

    println!("{:?}", Dot::with_config(&graph, &[Config::EdgeNoLabel]));
    let mut f = File::create("example1.dot").unwrap();
    let output = format!("{}", Dot::with_config(&graph, &[Config::EdgeNoLabel]));
    f.write_all(&output.as_bytes());
}

Here's the compiler error output:
error[E0277]: `()` doesn't implement `std::fmt::Display`
  --> examples/graphviz.rs:21:32
   |
21 |     let output = format!("{}", Dot::with_config(&graph, &[Config::EdgeNoLabel]));
   |                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `()` cannot be formatted with the default formatter
   |
   = help: the trait `std::fmt::Display` is not implemented for `()`
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
   = note: required because of the requirements on the impl of `std::fmt::Display` for `petgraph::dot::Dot<'_, &petgraph::graph_impl::Graph<&str, ()>>`
   = note: required by `std::fmt::Display::fmt`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.

The petgraph docs note that Dot implements Display trait and I based my code on sample code in trait.Display doc
I can get the code to work by changing the format string to {:?} but I thought that was only supposed to be for debugging.  Is there a better way to write code to accomplish the same thing?

A: Dot implements Display only if both the edge and node weights implement Display.
Since your edges are (), you cannot display this graph.
For example, changing the graph declaration to use i32 edge weights:
    let mut graph = Graph::<_, i32>::new();

causes the program to compile with no errors.


text:
Q: Web API 2 OData = $format not working: the request is always ignored I have a Web API OData project and everything is working great. I'm now trying to return xml instead of JSON using the $format parameter, as opposed to specifying a header request, and it is not working. I've tried these approaches:
http://localhost:3845/api/Customer?$format=application/xml
http://localhost:3845/api/Customer?$format=xml
http://localhost:3845/api/Customer?$format=application/xml;odata.metadata=full

All without success. This article says that it is possible: https://blogs.msdn.microsoft.com/webdev/2014/03/13/getting-started-with-asp-net-web-api-2-2-for-odata-v4-0/
I have updated all of my NuGet packages, but it seems that the request is always ignored, and instead I get JSON every time.

A: Since the ATOM format (XML) is only a technical committee specification instead of an OASIS standard for the OData V4 protocol, the ATOM format is disabled in the ODataLib from the version 6.3.0.
The correct way to ask the OData V4 service to respond in XML is as follows:
GET http://localhost:3845/api/Customer?$format=application/atom+xml

or set the header Accept to application/atom+xml. But due to the reason mentioned above, it doesn't work for Web API OData V4.

A: To support $format=xml and $format=json, add the following configuration:
config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml");


text:
Q: How can I call function from a map? I want to know how can I (if I even can) output(call) the functionality from a function. I want to have the 1, UP output. Its a new task from my mentor. Practicing callback functionality in real life examples. (im starting to create a little game).
#include <functional>
#include <iostream>
#include <string.h>
#include <map>

using namespace std;

void up (){

    cout<<"UP";
}

void down (){

    cout<<"DOWN";
}

void left (){

    cout<<"LEFT";
}
void right (){

    cout<<"RIGHT";
}

int main (){

   typedef map<int, void (*)()> mapaF;

    mapaF Kretnje;

    Kretnje.insert(pair<int,void (*)() >(1, up));
//    Kretnje.insert(pair<int, void (*)()>(2, down));
//    Kretnje.insert(pair<int, void (*)()>(3, left));
//    Kretnje.insert(pair<int, void (*)()>(4, right));

    for(auto a: Kretnje){
        cout<<"Kljuc: "<<a.first<<", Funkcija: "<<a.second<<endl;

    }
    //output 1, 1(?))
    return 0;
}

A: You can just use the same function call syntax () on it.
for (auto a : Kretnje)
    a.second(); //UP

Keep in mind that calling the function returns void, so you can't call it in a cout chain.
std::cout << a.first << a.second(); //error, a.second() is void


text:
Q: How to convert dynamic html to pdf? I want to convert dynamic html to pdf. Following code show the conversion of static html to pdf:
Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("d:/sample/pdfaskkea.pdf"));
        // step 3
        document.open();
        // step 4
        XMLWorkerHelper.getInstance().parseXHtml(writer, document,new FileInputStream("webcontent/jsp/index.jsp"), null);

//        XMLWorkerHelper.getInstance().parseXHtml(writer, document,new FileInputStream("C:\\pdf_table1.html"), null);
        //step 5

         document.close();

        System.out.println( "PDF Created!" );

A: From your question it is not clear, what you mean under "dynamic HTML".
If it is an HTML dynamically created with JSP, for example, PD4ML offers a JSP custom tag library - you only need to surround your code with   and  to output PDF instead of HTML.
If under dynamic HTML you mean JavaScript-rich HTML pages, I would recommend to take a look at PhantomJS, which can convert HTMLs also built on-a-fly with JavaScript. PhantomJS is a native standalone application, based on WebKit.

A: You can use itext pdf library to convert html into rich PDF files. To generate dynamic HTML content you can use a template library like thymeleaf.
I have a detailed article about generating PDF files with thymeleaf in a spring boot application if you are interested.


text:
Q: Tried referencing a Custom setting Text area(255) field inside a Formula in salesforce flow, but somehow it is erroring out saying field not exists Referencing Text area field belonging to custom Settings heirarchy object inside a condition formula of a Record Triggered Flow is giving following Error: Field $Setup.CustomSettingName__c.test__c does not exist. Check spelling.

A: Text Area fields are not supported in Formulas. You can vote for the idea for now.


text:
Q: Calculating ERA5 2018 monthly 2mt temperature anomalies in Google Earth Engine I am trying to calculate in Google Earth Engine using ERA5 the monthly 2mt temperature anomalies from January to December 2018 compared to the long-term reference period of 1981-2010. In other words, I would like to compare the temp anomaly of January 2018 with January of the long-term period. Finally, I would like to create a and create a time-lapse video from January to December 2018.
As a starting point, I am using the "Iterating over an ImageCollection" code example, but I don't get it working properly with the ERA5 data.
link to the code and the code.
// Load era5
var era5_2mt = ee.ImageCollection('ECMWF/ERA5/MONTHLY')
               .select('mean_2m_air_temperature')
               .map(function (image){
                return image.clip(geometry);
  });
print(era5_2mt);

// Define reference conditions from the first 30 years of data.
var eraref = era5_2mt.filterDate('1980-01-01', '2010-12-31')
  // Sort chronologically in descending order.
.sort('system:time_start', false);

// Compute the mean of the first 30 years.
var mean = eraref.mean();

// Compute anomalies by subtracting the 1980-2010 mean from each image
in a
// collection of 2018 images. Copy the date metadata over to the
// computed anomaly images in the new collection.
var series = era5_2mt.filterDate('2018-01-01', '2018-12-
31').map(function(image) {
    return image.subtract(mean).set('system:time_start',
image.get('system:time_start'));
});
var series2 = series.map(function(img){
    return img.clip(geometry);
});

// Display cumulative anomalies.
Map.setCenter(-4.12, 39.834, 5);
Map.addLayer(series.sum(),
    {min: -50, max: 50, palette: ['blue','white','red']}, 'Temp 2mt
anomaly');

// Get the timestamp from the most recent image in the reference
collection.
var time0 = eraref.first().get('system:time_start');

// Use imageCollection.iterate() to make a collection of cumulative
anomaly over time.
// The initial value for iterate() is a list of anomaly images already
processed.
// The first anomaly image in the list is just 0, with the time0
timestamp.
var first = ee.List([
// Rename the first band 'temp'.
  ee.Image(0).set('system:time_start', time0).select([0], ['temp'])
]);

// This is a function to pass to Iterate().
// As anomaly images are computed, add them to the list.
var accumulate = function(image, list) {
 // Get the latest cumulative anomaly image from the end of the list
with
  // get(-1).  Since the type of the list argument to the function is
unknown,
  // it needs to be cast to a List.  Since the return type of get() is
unknown,
  // cast it to Image.
  var previous = ee.Image(ee.List(list).get(-1));
  // Add the current anomaly to make a new cumulative anomaly image.
  var added = image.add(previous)
    // Propagate metadata to the new image.
    .set('system:time_start', image.get('system:time_start'));
  // Return the list with the cumulative anomaly inserted.
  return ee.List(list).add(added);
};

// Create an ImageCollection of cumulative anomaly images by
iterating.
// Since the return type of iterate is unknown, it needs to be cast to
a List.
var cumulative = ee.ImageCollection(ee.List(series.iterate(accumulate,
first)));

// Predefine the chart titles.
var title = {
  title: 'Cumulative Temp anomaly over time',
  hAxis: {title: 'Time'},
  vAxis: {title: 'Cumulative Temp anomaly'},
};

// Chart some interesting locations.
//var pt1 = ee.Geometry.Point(-8.669, 41.187);
//print('Porto:',
//Chart.image.series(cumulative, pt1, ee.Reducer.first(),
500).setOptions(title));

A: Issue is in the start date for computing reference conditions from the first 30 years of data (it computes wrong means). In spite of Dataset Availability of ERA5 Monthly aggregates is 1979-01-01 to present, your script run without any error if your reference conditions are changed for 25 years of data or less (e.g. between '1986-01-01' and '2010-12-31').
Your modified code can be ran here.
After running it, result is observed in following image. It worked!


text:
Q: php condition : first test of my inputs array ignored I want to check the inputs of my inputs with conditions (if, else..) nothing very complicated so far. But the problem is that the first condition is never taken into account.
Here is the code of my form:
 <form method="POST" action="">

author :

      <?php
      for($i=1; $i <= $author; $i++){?>

            <label for="<?= 'author'.$i ?>"> <?='author '.$i ?> :

            <input type="text" placeholder=" nom du author" id=" <?= 'author'.$i ?>" name="authors[]">

      <?php
      }?>

title :

      <?php
      for($i=1; $i <= $title; $i++){?>

            <label for="<?= 'title'.$i ?>"> <?= 'title '.$i ?> :

            <input type="text" placeholder=" title" id="<?= 'title'.$i ?>" name="titles[]">

      <?php
      }?>

article :

      <?php
      for($i=1; $i <= $article; $i++){?>

            <label for="<?= 'article'.$i ?>"> <?= 'article '.$i ?> :

            <input type="text" placeholder="ex: score possible(min:0)" id="<?= 'article'.$i ?>" name="articles[]">

            <input type="hidden" name="article" value="0">

            <input type="submit" name="btnSusbmit" class="modal-btn modal-eventTrigger modal-reportEventTrigger" value="Next">

</form>

and here is my php code :
if(isset($_POST['btnSusbmit']))
{
   if(!empty($_POST['authors']))
   {
      $_SESSION['authors'] = array_unique($_POST['authors']);
      if(!empty($_POST['titles']))
      {
         $_SESSION['titles'] = array_unique($_POST['titles']);
         if(!empty($_POST['articles']) and !empty($articles) and $articles != 0)
         {
            $_SESSION['articles'] = array_unique($_POST['articles']);
         }
         elseif(!empty($articles) and $articles != 0 and empty($_POST['articles']))
         {
            $error = 'all fields "articles" must be filled in.';
         }
      }
      else
      {
         $error = 'all fields "titles" must be filled in.';
      }
   }
   else
   {
      $error = 'all fields "authors" must be filled in';
   }
}

I transmuted the conditions to test and no matter the condition it is always the same problem.
Edit :
var_dump($POST] = array(5) { ["authors"]=> array(1) { [0]=> string(0) "" } ["titles"]=> array(2) { [0]=> string(0) "" [1]=> string(0) "" } ["articles"]=> array(2) { [0]=> string(0) "" [1]=> string(0) "" } ["article"]=> string(1) "0" ["btnSubmit"]=> string(7) "Next" }

A: First thing, your form is missing a closing bracket to your last for loop:
<?php
for($i=1; $i <= $article; $i++){?>

You open it there but never close it.
Second, this is your first condition:
if(isset($_POST['btnSusbmit']))

And it's just checking if theres any POST field with the name 'btnSusbmit', all your submits have this same name so if any of them have been clicked this will always evaluate to true
What i think you want to know is why this line:
if(!empty($_POST['authors']))

Is always returning true even when the 'author' fields are empty, and thats because even if you don't fill in your text inputs, the form is still creating an array with the empty strings. This is what comes out of a var_dump (i defined your variables as 5 just to get some test fields)
array (size=5)
  'authors' =>
    array (size=5)
      0 => string '' (length=0)
      1 => string '' (length=0)
      2 => string '' (length=0)
      3 => string '' (length=0)
      4 => string '' (length=0)
  'titles' =>
    array (size=5)
      0 => string '' (length=0)
      1 => string '' (length=0)
      2 => string '' (length=0)
      3 => string '' (length=0)
      4 => string '' (length=0)
  'articles' =>
    array (size=5)
      0 => string '' (length=0)
      1 => string '' (length=0)
      2 => string '' (length=0)
      3 => string '' (length=0)
      4 => string '' (length=0)
  'article' => string '0' (length=1)
  'btnSusbmit' => string 'Next' (length=4)

'authors' is never empty because even if you don't fill your texts, it is still an array that has elements inside, if you want to throw an error when the text inputs are left empty, then you need to check the strings inside the elements of the 'authors' array


text:
Q: Evaluate $\lim\limits_{n \to \infty}\sum\limits_{k=0}^n \dfrac{\sqrt{n}}{n+k^2}(n=1,2,\cdots)$ I tried to change it into a Riemann sum but failed, since
\begin{align*}
\lim_{n \to \infty}\sum_{k=0}^n \frac{\sqrt{n}}{n+k^2}=\lim_{n \to \infty}\frac{1}{n}\sum_{k=0}^n \frac{\sqrt{n}}{1+(k/\sqrt{n})^2}
,\end{align*}
which is not a standard form. Maybe, it need apply the squeeze theorem, but how to evaluate the bound.
By the way, WA gives its result
\begin{align*}
\lim_{n \to \infty}\sum_{k=0}^n \frac{\sqrt{n}}{n+k^2}=\frac{\pi}{2}.
\end{align*}

A: Integral bounds do the job:  $$\int_k^{k+1} \frac{1}{n+t^2} dt \leq \frac{1}{n+k^2}\leq \int_{k-1}^{k} \frac{1}{n+t^2} dt$$
Summing the left-hand side inequalities for $k\in \{0,\ldots,n\}$ and the right-hand side inequalities for $k\in \{1,\ldots,n\}$ yields
$$\int_0^{n+1}\frac{1}{n+t^2} dt \leq  \sum_{k=0}^n \frac{1}{n+k^2} \leq \frac 1n + \int_{0}^{n} \frac{1}{n+t^2}$$
that is
$$\frac{1}{\sqrt{n}}\arctan\left(\frac{n+1}{\sqrt n}\right)\leq \sum_{k=0}^n \frac{1}{n+k^2} \leq \frac 1n + \frac{1}{\sqrt{n}}\arctan\left(\frac{n}{\sqrt n}\right)$$
Multiplying by $\sqrt n$ and squeezing yields
$$\lim_n \sqrt n \sum_{k=0}^n \frac{1}{n+k^2} = \lim_n \arctan\left(\frac{n}{\sqrt n}\right) = \frac \pi 2$$

A: $$\lim_{n\to\infty} \sum_{k=0}^n \frac{\sqrt{n}}{n+k^2}=\lim_{n\to\infty} \frac{1}{n}\sum_{k=0}^n\frac{\sqrt{n}}{1+(k/\sqrt{n})^2}$$
Now make the substitution $n=m^2$, so that we have
$$\lim_{n\to\infty} \frac{1}{m}\sum_{k=0}^n\frac{1}{1+(k/m)^2} $$
which is equal to
$$\lim_{x\to\infty }\lim_{m\to\infty} \sum_{k=0}^{mx}\frac{x}{mx}\frac{1}{1+(kx/mx)^2} =\lim_{x\to\infty }\int_0^x \frac{dk}{1+k^2}=\int_0^\infty \frac{dk}{1+k^2}$$
which is, of course, equal to $\frac{\pi}{2}$.

A: you could let: $n\rightarrow n^2$ then we get:
$$L=\lim_{n\to\infty}\sum_{k=1}^\infty\frac{n}{n^2+k^2}$$
and we know that:
$$\frac{1}{n^2+k^2}\le\frac{n}{n^2+k^2}\le\frac{n^2}{n^2+k^2}$$
Now from here we can see that:
$$\sum_{k=-\infty}^\infty\frac{1}{k^2+a^2}=\frac\pi a\coth(\pi a)$$
and notice that:
$$\sum_{k=-\infty}^\infty=\sum_{k=-\infty}^{-1}+f(0)+\sum_{k=1}^\infty,\,\,\sum_{k=-\infty}^{-1}=\sum_{k=1}^\infty$$
and so:
$$\sum_{k=1}^\infty\frac{1}{k^2+a^2}=\frac12\left[\frac\pi a\coth(\pi a)-\frac1{a^2+1}\right]$$
This gives us:
$$\frac12\left[\frac\pi n\coth(\pi n)-\frac1{n^2+1}\right]\le\sum_{k=1}^\infty\frac{n}{n^2+k^2}\le\frac12\left[\pi n\coth(\pi n)-\frac{n^2}{n^2+1}\right]$$
Hope this is correct!, Although I don't think the bounds are particularly tight

A: We make a substitution $t^2=k $,
$$\lim_{n \to \infty}\sum_{t=0}^\sqrt {n} \frac{\sqrt{n}}{n+t}=\lim_{n \to \infty}\sum_{t=0}^\sqrt {n} \frac{1}{1+\frac{t}{\sqrt{n}}} \frac {1} {\sqrt{n}} $$
In a normal Riemann Transformation I would replace $\frac {1}{n}$ with $dx $ (where $x= \frac {t}{n}$) but since we have $\frac {1}{\sqrt {n}}$ we would replace it with $2dx $ (where $x= \frac {t}{\sqrt {n}}$)
Hence the limit becomes
$$2 \int_ 0^1 \frac {1}{1+x^2}\,dx = \frac {\pi}{2}$$


text:
Q: Elastisearch queries that are used for APM UI are slow I have noticed problems with queries returning 500 response when clicking on APM UI on our Kibana GUI. The server makes a request
GET /api/apm/ui_filters/local_filters/services?uiFilters=%7B%7D&start=2020-07-07T07%3A08%3A42.818Z&end=2020-07-08T07%3A08%3A42.818Z&filterNames=%5B%22host%22%2C%22agentName%22%5D

I have run the request in debug mode, so that I could obtain the query and run it in the Search Profiler  in Kibana. I have run this >
{
"size": 0,
"query": {
    "bool": {
        "filter": [
            {
                "terms": {
                    "processor.event": [
                        "transaction",
                        "error",
                        "metric"
                    ]
                }
            },
            {
                "range": {
                    "@timestamp": {
                        "gte": 1594105722818,
                        "lte": 1594192122818,
                        "format": "epoch_millis"
                    }
                }
            },
            {
                "range": {
                    "observer.version_major": {
                        "gte": 7
                    }
                }
            }
        ]
    }
},
"aggs": {
    "host": {
        "filter": {
            "bool": {
                "filter": []
            }
        },
        "aggs": {
            "by_terms": {
                "terms": {
                    "field": "host.hostname",
                    "order": {
                        "_count": "desc"
                    }
                },
                "aggs": {
                    "bucket_count": {
                        "cardinality": {
                            "field": "service.name"
                        }
                    }
                }
            }
        }
    },
    "agentName": {
        "filter": {
            "bool": {
                "filter": []
            }
        },
        "aggs": {
            "by_terms": {
                "terms": {
                    "field": "agent.name",
                    "order": {
                        "_count": "desc"
                    }
                },
                "aggs": {
                    "bucket_count": {
                        "cardinality": {
                            "field": "service.name"
                        }
                    }
                }
            }
        }
    }
}

}
When I have run it I have recieved the timeout again and I needed to shorten the time interval of the query but when "aggs" are removed I see that the query is really fast. The main problem is on the trasaction index for APM and for 4h I get a 3 second response time while without the "aggs" I have 50ms repsonse time for that index. The main delay is "next_doc" and  "build_scorer".
Could perhaps somebody let me know how I can go on and troubleshoot this as the query can't be changed there is probably something on the APM index or on the ES nodes itself.
The ELK cluster is running in docker and we have 5 nodes (6 CPU 30GB RAM - 10GB JVM, 1TB SSD) with a coordinator node where we run as well Kibana and an APM server. All of this is deployed in GCP in the same zone. I have measured network delay, resource usage and I/O speed and couldn't find anything that would block the speed of the cluster.
The APM loads data for 24h if I change the timerange on the first page to 1h and then select a service and move in there.


text:
Q: Generate unique numbers at compile time I want to generate unique numbers for each class in my header, primes in my case primes but let's say this should only be consecutive numbers i.e. 1,2,3,4,etc.
Of course I can hardcode these:
struct A { enum { ID = 1; }; };
struct B { enum { ID = 2; }; };
struct C { enum { ID = 3; }; };
struct D { enum { ID = 4; }; };

This is very error-prone since in reality the classes are not that small and if I add a new class in the middle I have to change all the following numbers if I don't want to completely loose the overview of the IDs.
I wish I could do the following:
struct A { enum { ID = get_next_int(); }; };
struct B { enum { ID = get_next_int(); }; };
struct C { enum { ID = get_next_int(); }; };
struct D { enum { ID = get_next_int(); }; };

But since constexpr functions calls can't have side effects afaik, this is impossible. I think using macros such a result is impossible too.
I would also be lucky with something like that:
struct A_id_holder : some_base_counter {};
struct A { enum { ID = A_id_holder::ID; }; };

struct B_id_holder : some_base_counter {};
struct B { enum { ID = B_id_holder::ID; }; };

struct C_id_holder : some_base_counter {};
struct C { enum { ID = C_id_holder::ID; }; };

struct D_id_holder : some_base_counter {};
struct D { enum { ID = D_id_holder::ID; }; };

But honestly, I have no idea how to implement that.
Can I achieve my goal and if yes, how?

A: I think that Boost preprocessor library can do that for you, maybe you should read that: How can I generate unique values in the C preprocessor?
There is an alternative depending on the compiler that you are using, gcc and msvc have a ___COUNTER___ macro that allows sequential number: http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html#Common-Predefined-Macros

A: Most people do this with the __COUNTER__ macro. But that's nonstandard, and there's only one for the whole program.
Here is a C++ hack I came up with using templates and overloading which is standard-compliant and supports multiple counters.

A: If you use gcc, you can use the __COUNTER__ macro.

A: One way might be to hard-code a placeholder wherever you want a unique number, and then write a small utility to pre-process the files, perhaps keeping the last-used number in a file so it will persist across invocations.


text:
Q: Log::Log4perl::Config::DOMConfigurator I am writing Perl script. In that I have to read log4j.xml file from perl and log messages into specific queues. I read that DOMConfigurator can do that. Can anyone provide me the sample code to read log4j.xml file from perl and log the messages using DOMConfigurator? Is there any other way in Perl to read xml based log4j to log messages?
Thanks in advance.
Regards

A: The Log::Log4perl::Config::DOMConfigurator documentation references the test files t/038XML-DOM1.t, t/039XML-DOM2.t as code examples.


text:
Q: Cannot install packages with apt-get update in debian (Proxy) I have Debian 10 installed in my Virtual Machine and want to use
sudo apt-get update

Problem is I am in a network with an internet connection over proxy. So far so good, I set up the automatic proxy address and also set up IvP4 as it is set up in Windows. I can normally browse the internet with my VM, but when I want to use the bash mentioned earlier I get the error message that it is not able to establish the connection and download files.
I found this
sudo http_proxy='http://user:pass@proxy.example.com:8080/'
apt-get install package-name

but my attempts on using this all failed.
So do anyone knows a solution for this?

A: Create a /etc/apt/apt.conf.d/http-proxy.conf with the following line:
Acquire::http::Proxy "http://user:pass@proxy.example.com:8080/";

Then run:
export http_proxy=http://user:pass@proxy.example.com:8080/

Or add it to your ~/.bashrc .
sudo apt install package_name

Debian FAQ: Q: How do I tell {{{apt-get}}} which http-proxy to use?

A: Set the environment Variable http_proxy: export http_proxy="http://192.168.1.1:8080" or export http_proxy=http://uid:pw@proxy:port if the proxy needs authentication. Alternatively you can configure it in /etc/apt/apt.conf.d


text:
Q: How do a I setup mongodb messagestore in aggregator using annotation I am trying to add an aggregator to my code.
Couple of problems I am facing.
1. How do I setup a messagestore using annotations only.
2. Is there any design of aggregator works ? basically some picture explaining the same.
@MessageEndpoint
public class Aggregator {

    @Aggregator(inputChannel = "abcCH",outputChannel = "reply",sendPartialResultsOnExpiry = "true")
    public APayload aggregatingMethod(List<APayload> items) {
        return items.get(0);
    }

    @ReleaseStrategy
    public boolean canRelease(List<Message<?>> messages){

        return messages.size()>2;
    }

    @CorrelationStrategy
    public String correlateBy(Message<AbcPayload> message) {
        return (String) message.getHeaders().get(RECEIVED_MESSAGE_KEY);
    }

}

A: In the Reference Manual we have a note:

Annotation configuration (@Aggregator and others) for the Aggregator component covers only simple use cases, where most default options are sufficient. If you need more control over those options using Annotation configuration, consider using a @Bean definition for the AggregatingMessageHandler and mark its @Bean method with @ServiceActivator:

And a bit below:

Starting with the version 4.2 the AggregatorFactoryBean is available, to simplify Java configuration for the AggregatingMessageHandler.

So, actually you should configure AggregatorFactoryBean as a @Bean and with the @ServiceActivator(inputChannel = "abcCH",outputChannel = "reply").
Also consider to use Spring Integration Java DSL to simplify your life with the Java Configuration.


text:
Q: How to implement the infinite scroll in React Material Autocomplete? I am trying to add infinite scroll function to the react material ui autocomplete(https://material-ui.com/components/autocomplete/).
But i couldn't find the way to solve this problem , if anyone had already experience in this, please help me.


text:
Q: Задержка загрузки таблицы стилей в Mozilla Firefox Подскажите пожалуйста кто сталкивался. Во всех браузерах нормально. В Mozilla Firefox при загрузке страницы примерно на пол секунды показывает страницу без стилей, очень раздражает. Файл стилей прописан в head как положено. Как лечить?

A: Столкнулся с подобной проблемой. Решил добавив всем элементам:
transition:none!important;

По этой статье


text:
Q: Error: Notice: Trying to get property of non-object I am working on a project that requires technologies in both Java and PHP. I use Java to implement my business logic and data source management while the PHP helps to consume the web service I provided using Java.
My problem:
When I consume a response from the web service and the result contains more than one return collection, the program runs fine.
(http://driesmeers.mamca.be/images/successpage.png)
However once the result return only one collective response, i get an error as shown below.
(http://driesmeers.mamca.be/images/errorpage.png)
Here are my code.PHP
<?php
  try {
$wsdl_url = 'http://localhost:8080/Mamca/MamcaWS?WSDL';
$client = new SOAPClient($wsdl_url);
$params = array(
    'projectid' => $_SESSION['projectID'],
);
$return = $client->getAlternativeListByProjectID($params);
if (isset($return->return)) {
    foreach ($return->return as $eachItem) {
        echo "
";
        echo " " . $eachItem->alternativedescription . "	";
        echo "" . $eachItem->alternativeGroup . "	";
        echo "";
        echo ($eachItem->status === 1 ? 'Active' : 'Inactive');
        echo "	";
        echo "	";
        echo "
";
    }
}
} catch (Exception $e) {
echo "Exception occured: " . $e;
}
?>

Response from WS with error output:
 <?xml version="1.0" encoding="UTF-8"?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<S:Body>
    <ns2:getAlternativeListByProjectIDResponse xmlns:ns2="http://services.mamca.be.vub/">
        <return>
            <alternativeGroup>testt</alternativeGroup>
            <alternativedescription>testtt</alternativedescription>
            <alternativeid>10670</alternativeid>
            <id>19</id>
            <projectid>12313</projectid>
            <status>1</status>
        </return>
    </ns2:getAlternativeListByProjectIDResponse>
</S:Body>
 </S:Envelope>

How do i resolve this error? thank you.

A: When the result is one single element, SOAPClient doesn't return an array by default, but an object.
You can set SOAPClient to return always an array, even when the result is one element, adding this parameter on instantiation:
$client = new SOAPClient($wsdl_url ,array(
  "features" => SOAP_SINGLE_ELEMENT_ARRAYS
));


text:
Q: Query Optimizer can't push predicate past rollup? HINTs doesn't work also This is the schema :

And this is the sql that as I understand is too complex for SQL Optimizer:
SELECT * FROM
(
    select pp.Id as PaymentPartId,  b.Id as BudgetId, grouping(bp.ID) as g1 , sum(pp.Amount) PaymentsSum, sum(bp.Amount) BudgetSum
    from  Projects pr
            inner join Payments p      ON pr.Id = p.ProjectID
            inner join PaymentParts pp ON p.Id = pp.PaymentId
            inner join Budgets b       ON pr.Id = b.ProjectID
            inner join Budgetparts bp  ON b.Id = bp.BudgetId
    group by pp.Id, b.Id, rollup(bp.ID)
)  x
WHERE   x.PaymentPartId = 777

SQLFIDDLE: http://sqlfiddle.com/#!6/aa74e/11  (with autogenerated data)
What I expect: execution plan should contain index seek on x.PaymentPartId. Why? Because this query is equivalent to:
select pp.Id as PaymentPartId,  b.Id as BudgetId,  grouping(bp.ID) as g1, sum(pp.Amount) PaymentsSum, sum(bp.Amount)  BudgetSum
from  Projects pr
        inner join Payments p      ON pr.Id = p.ProjectID
        inner join PaymentParts pp ON p.Id = pp.PaymentId
        inner join Budgets b       ON pr.Id = b.ProjectID
        inner join Budgetparts bp  ON b.Id = bp.BudgetId
WHERE   pp.Id = 777
group by pp.Id, b.Id, rollup(bp.ID)

...and the last query uses index seek.
But SQL Optimizer not only refuse to use the index but ignore all hints (I propose you to expirement wiht sqlfiddle - it is really interesting).
So the question is: am I right that it is impossible to force SQL Server Optimizer to use index seek there?  It seems like rollup is something that split sql optimizer "optimization frame" to two parts and it makes it impossible  to optimize WHOLE query.
P.S. For those who votes for closing this "non-programming question": try to put optimizer hints (sqlfiddle is ready to test your programming skills!).

A:
Why hints doesn't work? - Roman Pokrovskij

It is in the documentation:
http://technet.microsoft.com/en-us/library/ms181714.aspx
Query hints can be specified only in the top-level query, not in subqueries


text:
Q: perfectly normal space If $X$ is a Hausdorff topological space, we say that $X$ is perfectly normal if, for every closed set $A$, there exists a continuous function $f_A:X\rightarrow[0,1]$ such that $f_A^{-1}(0)=A$.
Prove that perfectly normal spaces are normal.
My effort:
Suppose $A$ and $B$ are two disjoint closed set. Define $g=\frac{f_A}{f_A+f_B}$. $g(x)=0$ if and only if $x\in A$, and $g(x)=1$ if and only if $x\in B$.
As long as I can prove $g:X\rightarrow [0,1]$ is continuous, I am done. But I do not know how to show it is continuous.

A: $f_A(x)+f_B(x) \geq 0$ and $f_A(x)+f_B(x) = 0$ if and only if $f_A(x)=f_B(x)=0$ if and only if $x \in A$ and $x\in B$ which is impossible. Hence $g$ is the ratio of two continuous functions in which the denominator never vanishes. This implies that $g$ is continuous.

A: Another way can be to see your map $g$ as the following composition
$g=G\circ (f_A,f_B)$ where
$(f_A,f_B): X\to [0,1]\times [0,1]$
and
$G: E\subseteq [0,1]\times [0,1]\to [0,1]$
where $E=\{(x,y): x\neq 0 \textit{ or } y\neq 0\}$
And the map is $G(x,y):= \frac{x}{x+y}$
that is continuos on its domain. This map is continuos for the same reasoning of Kavi Rama Murthy.


text:
Q: "Failed to download" when creating new virtual maching in gnome boxes so I just installed gnome-boxes on Ubuntu 20.04 LTS. When I click on the top left corner (the plus icon) and click "create new virtual machine", I select one of the "featured downloads" (i've tried all of them) Ubuntu, Red Hat, and openSUSE.
After clicking and trying to download it, it immediately tells me "Failed to download"
I've tried searching for other things to do, if I was missing any software, but couldn't find anything that I seemed to have been missing.


text:
Q: Xamarin Camera2Basic sample throws exception after UnlockFocus call Downloaded Xamarin Camera2Basic project
Initially all works correctly as it's begin tested in Visual Studio 2017 emulator.
Commented out code inside "CameraCaptureStillPictureSessionCallback.cs" as shown below to allow the still image captured to be displayed on the emulator screen after clicking the "Take Picture" button:
public override void OnCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result)
{
    //Owner.ShowToast("Saved: " + Owner.mFile);
    //Log.Debug(TAG, Owner.mFile.ToString());
    //Owner.UnlockFocus();
}

Clicking the "Take Picture" button hides itself, and shows another button labeled "Retake Picture" on the screen (which I added after the fact and the code is located in the Camera2BasicFragment.cs file, but the code is inconsequential to the issue).
Clicking the now visible "Retake Picture" button does the following:

*

*Hides itself

*Shows the "Take Picture" button

*Calls UnlockFocus()

UnlockFocus() allows the camera's stream to display continuously on the screen instead of the still image captured previously.
Now, when I click the "Take Picture" button again (to attempt to capture a new still image), the app crashes.
Visual studio does not provide any meaningful error messages.  The closest useful bit of information are the error messages displayed int the Device Log:
07-26 23:29:03.201   10.1" Marshmallow (6.0.0) XHDPI Tablet Error   6987    BufferQueueProducer [ImageReader-640x480f100m2-6987-0] dequeueBuffer: can't dequeue multiple buffers without setting the buffer count
07-26 23:29:07.174   10.1" Marshmallow (6.0.0) XHDPI Tablet Error   6987    RequestThread-0 Hit timeout for jpeg callback!
07-26 23:29:03.201   10.1" Marshmallow (6.0.0) XHDPI Tablet Error   6987    Legacy-CameraDevice-JNI LegacyCameraDevice_nativeProduceFrame: Error while producing frame Function not implemented (-38).

I'm not sure what to make of these errors, or which settings/code to change to allow the "Retake Picture" functionality to work without crashing the app.
Any suggestions?
EDIT 1:
Per request, where is a link to the project as I currently have it.
https://drive.google.com/file/d/0B7OSuA_ybXcFb081T210UlQzZkE/view?usp=sharing
Here is some other seemingly pertinent information:

*

*This code was run using:
a. Windows 10 Pro, Visual Studio 2017 Community, Android Emulator
For Visual Studio, Hyper-v Virtual Manager, Android 6.0
(Marshamallow SDK 23), Tablet sized template
b. 2013 Macbook Pro, Visual Studio For Mac (latest version), default
emaulator, Android 6.0 (Marshmallow SDK 23), Tablet sized template.

*The failure to take snapshot after second "LockFocus" call is observed in both environments.

*The Mac made it easier to find some more meaninful errors:
a. The error I saw happened on method "produceFrame" inside
LegacyCameraDevice.java

A: I've the problem with this demo also, The real problem behind this is about the IOnImageAvailableListener, it will not trigger the OnImageAvailable method to save the picture...
After read the code, i found out that the demo is broken, it missing some piece.
In the Camera2BasicFragment.cs, in the OnCreateMethod, you will need to add this line
mCaptureCallback = new CameraCaptureListener() { Owner = this};

The entire method should look like this:
public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        mStateCallback = new CameraStateListener() { owner = this };
        mSurfaceTextureListener = new Camera2BasicSurfaceTextureListener(this);

        // fill ORIENTATIONS list
        ORIENTATIONS.Append((int)SurfaceOrientation.Rotation0, 90);
        ORIENTATIONS.Append((int)SurfaceOrientation.Rotation90, 0);
        ORIENTATIONS.Append((int)SurfaceOrientation.Rotation180, 270);
        ORIENTATIONS.Append((int)SurfaceOrientation.Rotation270, 180);
    }

The interesting thing is, if you run this on emulator, nothing will happened, because in the CameraCaptureListener.cs file, this will always return 0, not ControlAFState.FocusedLocked or ControlAFState.InActivate
Integer afState = (Integer)result.Get(CaptureResult.ControlAfState);

Event if i hack the If method to be able to run jump into next step, the method OnImageAvaiable of ImageAvailableListener.cs will never be triggered by emulator. But if i run on the real device, it ran fine ?!
So the fix is:
1. Add the code above like i explained on the onCreate function.
2. Don't use emulator to run Camera2, it's buggy.
Hope it help :)

A: If you are still interested; IOnImageAvailableListener not trigger OnImageAvailable method in Visual Studio Emulator For Android.
Code is correct but Visual Studio Emulator For Android have a bug. I hope they fix it as soon as possible. On the other hand you can try your code in Xamarin by using Android Studio Emulator without any bug. It is easy and you dont need to know anything about Java or Android Studio Just follow the below steps

*

*Install Android Studio with virtual device

*Close Hper-v on your pc (windows -> control panel -> programs -> programs and features -> Turn windows features on or off)

*Open android studio -> Tools -> Avd Manager -> Create Virtual Device

Visual studio detect the virtual device just use it on Visual Studio Xamarin
hope it help


text:
Q: Working with a block/chunk splitted memory I'm trying to implement garbage collector in c++ but I am having a few problems.
So I have an array of 5 elements each one with 1024 bytes in it and thats the memory that is going to be used to allocate different variables, arrays, pointers, etc. So I can't change things in it. And for that reason I made another class Chunk that has a start, size and a variable for which of the five elements its in. I also made a list of chunks which will keep all of the allocated chunks of memory.
TASK:With this I am trying to make a method/function in the garbage collector class to allocate a chunk of memory in the first array by finding a free spot that has enough space for the given chunk and it returns a pointer to that chunk.
The problem is that I have no idea how to work with both the sheet array and the list of chunks in order to find which space is empty and which isn't. Any ideas?
Here is my code:
class Chunk
{
    char *start;
    size_t size;
    size_t page_num;

    Chunk(); // default constructor
    Chunk(char *start, size_t size, size_t page_num); // constructor to make a chunk
}

class GC
{
    static char *sheets[5];
    static size_t chunks_count;
    static list <Chunk> chunks;

    static void init() // i initialize the sheets, sheet_count and chunks_count
    static void* alloc(size_t size) // given size of chunk
    {
        Chunk();
        ...
    }
}

Note: class GC must be static and make no instances

A: Let's start by defining a freelist. This is a list of Chunks that are not yet allocated. For simplicity I will reuse your Chunk datastructure:
static list<Chunk> freelist;

// We need this for sorting and comparing Chunk objects.
bool operator<(const Chunk& c1, const Chunk& c2) {
  return std::tie(c1.page_num, c1.start) < std::tie(c2.page_num, c2.start);
}

Your init function should create the initial freelist entries:
  freelist.emplace_back(sheets[0], sheet_size, 0);
  freelist.emplace_back(sheets[1], sheet_size, 1);
  freelist.emplace_back(sheets[2], sheet_size, 2);
  freelist.emplace_back(sheets[3], sheet_size, 3);
  freelist.emplace_back(sheets[4], sheet_size, 4);

We establish three invariants now:

*

*freelist is always sorted by page_num and start

*chunks is always sorted by page_num and start

*If you interleave chunks and freelist, you should end up with the full memory range again

The alloc function must now find or split a chunk that is large enough:
static void* GC::alloc(size_t size) {
  for (auto it = freelist.begin(); it != freelist.end(); it++) {
    Chunk& c = *it;
    if (c.size < size) { continue; }
    if (c.size > size) {
      // Shrink the current free chunk
      char *new_start = c.start + c.size - size;
      c.size -= size;
      insert_sorted(chunks, Chunk{new_start, size, c.page_num});
      return new_start;
    }
    if (c.size == size) {
      // Move the chunk from the freelist to chunks
      char *new_start = c.start;
      insert_sorted(chunks, c);
      freelist.erase(it);
      return new_start;
    }
  }
  return nullptr;
}

void insert_sorted(list<Chunk>& l, const Chunk& c) {
  auto it = std::lower_bound(l.begin(), l.end(), c);
  l.insert(it, c);
}

Implementing dealloc is now the fun part: you need to move the chunk back from chunks to freelist and then possibly merge it with the chunk before and/or after it.


text:
Q: Creating a Windows Task that runs when enabled and periodically thereafter until disabled I'm a bit confused about triggering in windows task scheduler.
I want to create a task that runs upon being enabled by the user, and as long as it stays enabled I want it to also run periodically (say for example hourly, whether logged on or off), and also at system startup as well, until the user manually disables the task. Is that set by using one trigger, or two, and what settings should be used for the triggers?

A: Is that set by using one trigger, or two, and what settings should be used for the triggers?
I think you will need 2 triggers for this.

I want to create a task that runs upon being enabled by the user, and as long as it stays enabled I want it to also run periodically (say for example hourly, whether logged on or off), and also at system startup as well, until the user manually disables the task.

Try the following:

*

*Start > Run > Task Scheduler

*Click "Create Task"

*Click "General" tab

*

*Enable "Run whether user is logged on or not" then click "OK"

*Click "Triggers" then click "New"

*

*Select "At Startup" then click "OK"

*Click "Triggers" then click "New"

*

*Select "On a schedule"

*Set "Start" date and time as appropriate

*Enable "Daily"

*"Recur every" to 1 "days"

*Set Repeat task every" to 1 hour

*Set "for a duration of" to Indefinitely

*Click "OK"

*Select the "Actions" tab and click "New"

*

*Complete as appropriate and click OK.

*Click "OK" a final time to finish creating the task.

*Test it all works as expected.


text:
Q: How to find out when the QQuickItem-derived class object is initialized? I've got class that inherits from QQuickItem and inside I'm operating on its width height properties. I'm also exposing my own properties.
class MyQQuickItem : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(QUrl source MEMBER m_source NOTIFY sourceChanged)

    public:
    explicit MyQQuickItem(QQuickItem *a_parent = Q_NULLPTR);
     ~PDFPage();

    signals:
    void sourceChanged(const QUrl a_source);

    private:
    QUrl m_source;
};

In qml:
...
MyQQuickItem
{
    width: parent.width / 2
    height: parent.height
    source: "someSource"
    Component.onCompleted
    {
        console.log("component onCompleted");
    }
}

When sourceChanged is emmited I'm working on width height properties, but with the first emit they are not initialized yet, and Component.onCompleted is called after my NOTIFY signal.
I can check if component is ready before getting width and height by calling isComponentComplete and execute my code when it is, but I can't find out when it happens and the initial value of source is skipped when it is not.
Of course I could create slot 'itemReady' and call it from Component.onCompleted, but I have many QMLs using my class and I will create more in the future, so I don't want to make copy-paste job.
I also do not want to set the source in Component.onCompleted.
Connecting to widthChanged, and heightChanged signals isn't also good idea, because I'm resizing my item very frequently, and I don't want to execute my code then.

Is there any way to get completed signal from C++?
EDIT:
I did as @Mitch said - overriten componentComplete method and inside, called it's base class equavilent. isComponentComplete() returns true, but I'm still getting 0 from width() and height() methods:
void MyQQuickItem::componentComplete()
{
    QQuickItem::componentComplete();
    if(isComponentComplete())
    {
        qDebug() << "c++: oncompleted, width,height: " << width() << height(); //gives 0,0
    }

}

Actually I figured out that Component.onCompleted in QML prints 0's too:
...
MyQQuickItem
{
    width: parent.width / 2
    height: parent.height
    source: "someSource"
    Component.onCompleted
    {
        console.log("component onCompleted width, height: ", width, height); //it gives 0 too
    }
}

@derM Component.onCompleted is not emmited by QQuickItem::componentComplete() directly, because it prints its log after the qDebug in c++ above.
So, although it is ready, properties are not initialized.

EDIT2:
Finally I've solved it. The Window was guilty, because it uses contentItem as the parent of his childrens, and in MyQQuickItem Component.onCompleted width and height of contentItem(his parent) are 0.
When I do so:
Window
{
    id: wnd
    width: 640
    height: 480
    Component.onCompleted:
    {
        console.log("Window completed: ", this, width, height);
        console.log("windowContentItem: ", contentItem, width, height);
    }

    MyQQuickItem
    {
        width: parent.width
        height: parent.height
        Component.onCompleted:
        {
            console.log("MyQQuickItem completed: ", this, width, height);
            console.log("MyQQuickItem parent: ", parent, parent.width, parent.height);
        }
    }
}

It prints:
qml: Window completed:  QQuickWindowQmlImpl(0x345b5eb4d0) 640 480
qml: windowContentItem:  QQuickRootItem(0x345e2cdec0) 640 480
qml: MyQQuickItem completed:  MyQQuickItem(0x345b5b99e0) 0 0
qml: MyQQuickItem parent:  QQuickRootItem(0x345e2cdec0) 0 0

So MyQQuickItem parent is Window's contentItem. When I replace
width: parent.width
height: parent.height

to:
width: wnd.width
height: wnd.height

It works perfectly, and in my void MyQQuickItem::componentComplete() I've got width and height initialized as expected.
One thing that I do not understand is why in Window onCompleted, contentItem size is correct, but in MyQQuickItem onCompleted the size is 0,0. If anyone could explain it to me, I would be grateful :P

A: Qt code uses componentComplete() like so:
void QQuickControl::componentComplete()
{
    Q_D(QQuickControl);
    QQuickItem::componentComplete();
    d->resizeContent();
    // ...
}

You can do something similar, replacing resizeContent() with your function that works on the width and height. Assuming that function is also called whenever source changes, you'd need the isComponentComplete() check. With this approach, you shouldn't have any issues.

A: You can inherit QQmlParserStatus and implement componentComplete().
class MyQQuickItem : public QQuickItem, public QQmlParserStatus
{
    Q_OBJECT
    Q_PROPERTY(QUrl source MEMBER m_source NOTIFY sourceChanged)

public:
    explicit MyQQuickItem(QQuickItem *a_parent = Q_NULLPTR);
    ~PDFPage();

    void classBegin();
    void componentComplete();

signals:
    void sourceChanged(const QUrl a_source);

private:
    QUrl m_source;
};

componentComplete() will be called automatically by the QML-engine.


text:
Q: How to get actual number of channel in asterisk 13? In asterisk 1.4 number of channel was specified in chan->name.
e.g. number 62:
asterisk 1.4 ZAPTEL: Zap/62-1

How to get actual number of channel in asterisk 13 in c-language?
e.g. in chan->name this number of span only.
asterisk 13 DAHDI: DAHDI/I2/102-1

Here is what R.Mudget say about extentons.conf:

You can use the AMI action DAHDIShowChannels to get the current channel mapping.

There is an AMI event that you can look for:
Event: DAHDIChannel Channel: name Uniqueid: id DAHDISpan: 5
DAHDIChannel: 23

It is generated whenever a call is assigned to a B channel or a call moves to a different B channel.

There is also the CHANNEL() dialplan function:
CHANNEL(dahdi_channel)
CHANNEL(dahdi_span)
CHANNEL(dahdi_type)

The DAHDIChannel event and CHANNEL() function are mentioned in the UPGRADE.txt file.

Richard

But how do I get an actual number of channel in c-language API?

A: Simplest way answer this question is read source code(writed in c/c++) of chan_dahdi and see how dahdi_channel variable is set in YOUR dahdi/asterisk combination.
You also can use ami from c/c++, but that is not optimal.
In general you should not see number of channel in channel-name unless you setuped one-channel-one-span.


text:
Q: BCP underflow to -Inf Could anyone translate the below warning into plain English for me ?

1: In rcpp_bcpM(y, as.integer(id), as.integer(return.mcmc), as.integer(burnin),  :
    pbeta(*, log.p=TRUE) -> bpser(a=3630, b=21, x=0.8,...) underflow to -Inf

The input is a column of log returns created as follows :
XYZ_xts$LogReturns<-diff(log(XYZ_xts$Adj_Close),lag=10)

I have tried the following commands, all of them return the same warnings :
XYZ_bcp<-bcp(XYZ_xts$LogReturns)
XYZ_bcp<-bcp(na.omit(XYZ_xts$LogReturns))
XYZ_bcp<-bcp(as.vector(XYZ_xts$LogReturns))
XYZ_bcp<-bcp(as.vector(na.omit(XYZ_xts$LogReturns)))

A: Underflow problems means that there are some operations which can't return the exact number due to limitations of your computer or R. The smallest value your computer/R can handle can be found by .Machine$double.xmin, which is equal to 2.225074e-308 on my computer. Underflow warnings occur if you want to calculate a number between 2.225074e-308 and 0.
You are using the bcp package for Bayesian Analysis, so you will calculate likelihood functions. Suppose that there are n data points, a likelihood function is then a product of n terms. If n is large and the value of the terms is smaller than one, the likelihood function can underflow to zero.


text:
Q: How to setup google app engine eclipse plugin logging level? I'd like eclipse to output debug level traces for my app and warning level traces for everything else.
Does not matter what I do in my WEB-INF/logging.properties, the only way to control logging level is through "Run" > "Debug Configurations...", select my app, then click on "GWT" tab and change logging level. The problem is that it sets debugging level for all loggers.
Is there a way to make it output debugging messages only for my app?
Here is how my WEB-INF/logging.properties looks like:
java.util.logging.ConsoleHandler.formatter=myproject.LogFormatter

# Set the default logging level for all loggers to WARNING
.level=WARNING

#org.datanucleus.level=WARNING
#org.apache.level=WARNING
#com.google.apphosting.level=WARNING
myproject.level=FINEST

# Set the default logging level for ORM, specifically, to WARNING
DataNucleus.JDO.level=WARNING
DataNucleus.Persistence.level=WARNING
DataNucleus.Cache.level=WARNING
DataNucleus.MetaData.level=WARNING
DataNucleus.General.level=WARNING
DataNucleus.Utility.level=WARNING
DataNucleus.Transaction.level=WARNING
DataNucleus.Datastore.level=WARNING
DataNucleus.ClassLoading.level=WARNING
DataNucleus.Plugin.level=WARNING
DataNucleus.ValueGeneration.level=WARNING
DataNucleus.Enhancer.level=WARNING
DataNucleus.SchemaTool.level=WARNING

A: It appears that Google broke logging somewhere around SDK 1.3.7 when they tried to combine the GWT and Appengine loggers.  Here's the "Fixed" bug:
http://code.google.com/p/googleappengine/issues/detail?id=4011
Unfortunately they made the situation far worse - it appears there is no way to separate the GWT logging controls from the appengine logging controls, and the GWT logger ignores your logging.properties.  The craziest part is that if you have a GAE app without GWT, you have no control over logging whatsoever - you can't set the threshold to DEBUG.
As far as I can tell, we're screwed until this issue gets resolved - and it hasn't even been Acknowledged yet:
http://code.google.com/p/googleappengine/issues/detail?id=4591
Please star that issue and throw tantrums on the appengine-java mailing list :-(


text:
Q: How do I display a custom 401 page in Fat-Free Framework? I'm new to F3 and I've just implemented a form-based login system (using the Auth plugin). It works, but my not-logged-in check looks like this:
if (!$f3->get('SESSION.user')) $f3->reroute('/login');

The example I was referring to, did this, which seems more correct:
if (!$f3->get('SESSION.user')) $f3->error(401);

However, this 401 error shows a simple error page. I want it to send back the login form (which is at /login) along with an error saying "You must be logged in" and I want this response to be a 401 instead of a 403 or 200.
Am I right in expecting this behaviour or is a 401 only valid for HTTP Basic Auth and not custom form-based auth?

A: You can customize the error response with the ONERROR hook.
So in your case, you could do something like this:
$f3->ONERROR=function($f3) {
  if ($f3->get('ERROR.code')==401) {
    // custom behaviour on 401
    echo \Template::instance()->render('error-401.htm');
  } else
    // default behaviour otherwise
    return FALSE;
};

This page requires authorization

Click here to sign in


text:
Q: Why does this code snippet give a segmentation fault? I am not able to understand why this simple code gives a segmentation fault.
#include <iostream>

using namespace std;

int main ()
{
    vector <vector <int>> graph;
    graph [0] = vector <int> ();
    graph [0].push_back(0);
    cout << graph[0][0];
}

A: vector <vector <int>> graph;
graph [0] = vector <int> ();

Because you're accessing element 0 of an empty vector. First, give it some elements:
graph.emplace_back();

A: You need to either use push_back or resize graph from the start:
vector<vector<int>> graph;
graph.resize(1);
graph[0].push_back(0);
cout << graph[0][0];

A: You declared an empty vector
vector <vector <int>> graph;

So you may not use the subscript operator to change non-existent elements of the vector.
You could declare the vector at least with one element like
vector <vector <int>> graph( 1 );

In this case this statement
graph [0] = vector <int> ();

shall be removed and you may write
graph [0].push_back(0);
cout << graph[0][0];

And alternative approach is to use one more the method push_back for the initial object.
vector <vector <int>> graph;
graph.push_back( {} );
graph [0].push_back(0);
cout << graph[0][0];


text:
Q: best way to delete a record depending on what data permissions a user has MySQL Take a record from the customers database as an example:
id, company, first_name, last_name, email, phone
'3', 'ABC Company', 'Kevins', 'kevinboy@gmail.com', 667-545-9502

And a sample record from the user permissions table:
user_id    table    column      add    delete    view
1       customers   company     1       1        1
1       customers   first_name  1       1        1
1       customers   last_name   1       1        1
1       customers   email       0       0        0
1       customers   phone       0       0        0

On our frontend, user 1 might be logged in, and the permissions table basically says that for any customer record, which fields do they have access to see. So from the customer record (id 3), on the front-end they would only see company, first and last name.
Normally, before permissions were implemented, on the frontend anyone could click a delete button, and a delete query was made DELETE FROM customers WHERE id = 3.
Now with permissions implemented, values for a record will only be returned where the user has view = 1 for a given table + column combo.
The question is, this works great for adding and editing a record. I was able to create logic on our API that checks specifically what the user is allowed to see. My challenge though is with DELETE. I have 2 ideas, and wanted to get some advice on the best approach, or if there is an easier way to achieve this directly in MySQL.
option 1) when a user sends a DELETE request to the API, I can take the customer id given and get the record from the db using a SELECT. Then, I can evaluate which fields have data, and which fields the user is permissioned to delete. Basically, if a record contains what they are permissioned to, then yes they can delete it, but if it contains values in other fields they are not permissioned to, then no they cant delete the record.
option 2) when the user sends a DELETE request to the API they can include the full record from the frontend. So I'd expect them to send all values for id 3 as shown above. In this case, i can also evaluate what they are sending me and what fields they have access to delete.
This query runs at the API level before ever adding, deleting a record.
SELECT column FROM permissions WHERE table = ? and delete = ? and user_id = ?


text:
Q: Saving pandas dataframe variable to csv from google compute engine to google storage bucket without saving to disk first I have a google cloud storage bucket called google-storage-bucket-1.
I'm connected my compute engine instance and I have a pandas dataframe variable which is created in python as a temporary variable called df1.
I want to save the dataframe as a csv file into the bucket. I use the following command.
import pandas as pd

df1.to_csv('gs://google-storge-bucket-1/test/dataframe1.csv')

But I get the following error,

OSError: Forbidden: https://www.googleapis.com/upload/storage/v1/b/xxx/o
Insufficient Permission

Whats the proper command to save the file to the bucket without saving it to disk first?

A: Like this:
from google.cloud import storage
import os
from io import StringIO

f = StringIO()  ## this is to avoid creating local file
df1.to_csv(f)
f.seek(0)

gcs = storage.Client()
gcs.get_bucket('google-storge-bucket-1').blob('dataframe1.csv').upload_from_file(f, content_type='text/csv')


text:
Q: Finding String permuatations Given a string of characters(a-z) ,find subsequence such that every character is strictly greater than all previous characters in that subsequence.
Example if S=abc then there are 7 subsequences which follow the above constraint. These are a,b,c,ab,ac,bc,abc. Notice that we are considering 'a' is smaller than 'b' and so on
Note: A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
We need to find number of such sequences and algo to print all such subsequences.
How to approach this problem ??

A: You have a string of $n$ characters and you can form the substrings of $1, 2, \cdots, n$ characters.
The number of combinations is for the substring given by
$$ \frac{n!}{k![n-k]!} $$
So you need to calculate
$$ \sum_{k=1}^n \frac{n!}{k![n-k]!} $$
This is
$$ \sum_{k=0}^n \frac{n!}{k![n-k]!}  - 1$$
Which can be written as
$$ 2^n - 1 $$


text:
Q: Why do we have to import keras from tensorflow if we have already imported tensorflow in python? I'm now learning tensorflow and keras and I see all tutorials have these two imports:
import tensorflow as tf
from tensorflow import keras

Based on my understanding of python import, I thought the second line was an extra, since if we have already imported tensorflow in the first line, then we shall have imported every module in tensorflow. Just like if we have
import math

then we shouldd have math.log(), math.sqrt() available.
However, if I comment
from tensorflow import keras

then this line of code
model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])

would return
NameErrorTraceback (most recent call last)
<ipython-input-3-740ba65f0ade> in <module>()
----> 1 model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])

NameError: name 'keras' is not defined

Why can't we directly use tf.keras if we only have import tensorflow as tf? What's special about this import compared to the import in import math?
Thanks

A: When you import a module in python, you import only that module (along with the modules imported by the module), any modules defined in the imported module need to be imported on their own,
example
$ ptree
.
├── imports.py
└── pmod
    ├── cmod.py
    └── __init__.py

1 directory, 3 files

$ cat imports.py
import pmod

pmod.do()
pmod.cmod.do()

$ python3 imports.py
hello from pmod
Traceback (most recent call last):
  File "imports.py", line 4, in <module>
    pmod.cmod.do()
AttributeError: module 'pmod' has no attribute 'cmod'

however if I import it explicitly it does work
$ cat imports.py
import pmod
import pmod.cmod

pmod.do()
pmod.cmod.do()

$ python3 imports.py
hello from pmod
hello from cmod

A: The error is not with tf.keras. In your model definition, you use layers from keras and not tf.keras. That's why your'e getting the error when you remove the import. Replace your model definition with:
model = tf.keras.Sequential([tf.keras.layers.Dense(units=1, input_shape=[1])])
Now, you do not need to import keras from tensorflow.


text:
Q: Simple exercise on Galois theory Find the splitting field of $x^6-2x^4-8x^2+16$ over $\mathbb {F}_3$ and list the intermediate fields between the base camp and the splitting field.

A: Hint: Over $\mathbb{F}_3$ we have
$$
x^6-2x^4-8x^2+16=(x^2 + 2x + 2)(x^2 + x + 2)(x^2 + 1).
$$

A: $x^6-2x^4-8x^2+16 = x^6+x^4+x^2+1$ in $\mathbb {F}_3[x]$.
$x^6+x^4+x^2+1 = \dfrac{x^8-1}{x^2-1} = (x^2 + 1) (x^4 + 1)$
Therefore, the splitting field of $x^6-2x^4-8x^2+16$ is the same as the splitting field of $x^4 + 1=(x^2 + x + 2) (x^2 + 2 x + 2)$, which is $\mathbb {F}_9$.

A: My factorization was incorrect, I have understood my error. Now to calculate the Galois group of the extension (which is actually a Galois extension, as $\mathbb {F}_9$ is the splitting field of a separable polynomial, having first derivative different from zero, with coefficients in $\mathbb {F}_3$) I just note that the degree of the extension is $[\mathbb {F}_9:\mathbb {F}_3]=2$, so the group has 2 elements and it is isomorphic to $\mathbb {Z}_2$. Is it right?


text:
Q: I am getting error that #import  not found in xcode I installed these pod files.
pod 'TwitterKit'
pod 'TwitterCore'
When I try to import file i. e #import < TwitterKit/TwitterKit.h > it is showing  not found error.
Why it is comming any idea ? anything going wrong or anything is pending to add ?

A: Since version 3.3.0 TwitterKit has a new home on github, the installation page states that you need to import like this:
#import <TwitterKit/TWTRKit.h>

A: Import it as a module using @import TwitterKit.

A: Before import tries to clean and build your project or restart Xcode, then import Twitter.


text:
Q: Yii 2 restful api custom param I am using Yii 2 to create a Restful API. Til now I am able to get all products from the database as shown.
   [
        {
            "product_id": 28,
            "model": "Product 1",
            "date_modified": "2011-09-30 01:05:39"
        }
    ]

The problem with this is i cannot access the details of a single product using the product_id which is the primary key in my case.
How do map my URLs so that I can access single product details using
index.php?r=products/product_id unlike Yii 2 default which would be index.php?r=products/id  Below is my UrlManager Configs
'urlManager' => [
            'class' => 'yii\web\UrlManager',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                'product/<product_id:\d+>' => 'product/view',
            ],
  ],


text:
Q: Load the xml in php and return the data i'm looking how to Load the XML file in PHP and Return the data not redirect. Preferably to hide the xml content from the end user as much as i can.
I've seen something like this, but i can not make it work, please if you can write out the complete code with a link example..
     public function sendResponse($type,$cause) {

    $response = '<?xml version="1.0" encoding="utf-8"?>';
    $response .= '<response><status>'.$type.'</status>';

            $response = $response.'<remarks>'.$cause.'</remarks></response>';
            return $response;
 }

 ....
 ....

 header("Content-type: text/xml; charset=utf-8");
 echo sendResponse($type,$cause);

Please help if you can.
Thank's in Advance,
SX

A: I'm not sure to understand your request, but first you can't call sendResponse() cause it's not a function but a method in a Class
You need to instantiate your class and after, call the method.
Example :
$yourObject = new YourClass();

$yourObject->sendResponse();

See the manual
For your case, see the manual for simpleXML and try that :
    function sendResponse($type,$cause) {

    $response = '<?xml version="1.0" encoding="utf-8"?>';
    $response .= '<response><status>'.$type.'</status>';

            $response = $response.'<remarks>'.$cause.'</remarks></response>';
            return $response;
 }

$type="type";
$cause="cause";
var_dump(simplexml_load_string(sendResponse($type,$cause)));

If your script is external, you can get it with file_get_contents
$xml = file_get_contents('http://yourTarget.com');

var_dump($xml);

A: You question misleads me to some extent, make sure if you want to load an external xml file and make your PHP code parse it. Try the following code
Assume the following is your xml content fo text.xml

<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>"

<-- PHP -->

$file = 'http://exmp.com/text.xml';     // give the path of the external xml file
if(!$xml = simplexml_load_file($file))    // this checks whether the file exists
exit('Failed to open '.$file);           // exit when the path is wrong
print_r($xml);                          // prints the xml format in the form of array

your output will be this
SimpleXMLElement Object (
[to] => Tove
[from] => Jani
[heading] => Reminder
[body] => Dont forget me this weekend!
 )

Hope this helps...


text:
Q: Unable to create new Java class in new package on IntelliJ Idea? When i am creating new package in my intelliJ Idea for java it doesn't shows java class option after creating new package.

A: HyperSkill OOPS is not a valid package name, because it contains spaces. Also, you can't use the keyword as a package name, for example as a package name, variable name, or class name. If you choose a different name for your package, the option to create a Java class should appear.
for learn about valid package names in java click here


text:
Q: You can not install Windows 8.1 on ubuntu 15.04 phenon IIx6 1090T Download ubuntu, then download yumi and create a multiboot USB, set the priority of the bios, but every time I reboot does not start installing Linux, I do not know what could be wrong? or am I doing wrong? but I can not install the operating system with Windows 8.1
features
ASUS PC motherboard Hibrit CFX CPU phenon IIX6 1090T,
video Gigabyte GT 240 1Gb,
4 GB of RAM
It is the first time I install ubuntu, as I fix it?

A: You can use Unetbootin to make bootable Linux USB stick.
sudo apt-get install unetbootin

Here is the version for Windows: http://unetbootin.sourceforge.net/


text:
Q: Joining Excel tables to data attribute in ArcMap? I am trying to join an Excel table to my parcel attribute table in ArcMap.
I have run a validation and all checks out except it says there are no matches.
What would cause this?

A: Exporting to a dbf works most of the time and is the easier way, but it doesn't really identify the problem.
In ArcCatalog:
Ensure the Excel Table in your spreadsheet (the xls or xlsx file) is viewable, has the expected number of records, and you receive no errors (i.e. you see your data values when previewing).
Compare the Data Types for your parcel attribute table and your Excel Table and ensure they match (i.e. text is text and floats are floats).
In ArcMap:
Another quick and easy check is to find a value that you know should match between the two tables.  Simply copy/paste the value (ctrl-c, ctrl-v) into something like notepad and make sure there are no spaces or any other characters.   Do a Select by Attribute on your copy/pasted value and see if you get a result in both tables.

A: You're going to want to export your excel table as a .dbase or .dbf file, then your join should work as expected.


text:
Q: Pandas combinations and merge If you have the following dataset,
BookStrategy    Trade   DV01    Maturity

STRAT1  Bond    1000    04/05/23

STRAT1  Swap    -200    04/05/23

STRAT1  Swap    -300    04/05/23

STRAT1  Swap    -500    04/05/23

And the ultimate aim is to get this
STRAT1  Bond    1000    04/05/23    STRAT1  Swap    -200    04/05/23    STRAT1  Swap    -300    04/05/23    STRAT1  Swap    -500    04/05/23

STRAT1  Swap    -200    04/05/23    STRAT1  Bond    1000    04/05/23    STRAT1  Swap    -300    04/05/23    STRAT1  Swap    -500    04/05/23

STRAT1  Swap    -300    04/05/23    STRAT1  Bond    1000    04/05/23
STRAT1  Swap    -200    04/05/23    STRAT1  Swap    -500    04/05/23

STRAT1  Swap    -500    04/05/23    STRAT1  Bond    1000    04/05/23    STRAT1  Swap    -200    04/05/23    STRAT1  Swap    -300    04/05/23

In short, if I have
row1
row2
row3
row4,
I want the combinations to be
row1 --> row1 row2 row3 row4

row2 --> row2 row1 row3 row4

row3 --> row3 row1 row2 row4

row4 --> row4 row1 row2 row3

The code that I have so far is this,
dataset = pd.read_csv('bla.csv')

print (dataset.head(1))

df = dataset.values

df1 = pd.DataFrame(df.reshape(1,-1))

This gives the output,
0   STRAT1  Bond    1000    04/05/23    STRAT1  Swap    -200    04/05/23    STRAT1  Swap    -300    04/05/23    STRAT1  Swap    -500    04/05/23

A: You can using pop for moving the list
l=[]
for x in range(len(df)):
    s = df.apply(tuple, 1).values.tolist()
    s=[s.pop(x)]+s
    l.append(s)

pd.DataFrame(l).stack().apply(pd.Series).unstack().sort_index(level=1,axis=1)

Out[398]:
        0     1     2         3       0     1     2         3       0     1  \
        0     0     0         0       1     1     1         1       2     2
0  STRAT1  Bond  1000  04/05/23  STRAT1  Swap  -200  04/05/23  STRAT1  Swap
1  STRAT1  Swap  -200  04/05/23  STRAT1  Bond  1000  04/05/23  STRAT1  Swap
2  STRAT1  Swap  -300  04/05/23  STRAT1  Bond  1000  04/05/23  STRAT1  Swap
3  STRAT1  Swap  -500  04/05/23  STRAT1  Bond  1000  04/05/23  STRAT1  Swap
     2         3       0     1    2         3
     2         2       3     3    3         3
0 -300  04/05/23  STRAT1  Swap -500  04/05/23
1 -300  04/05/23  STRAT1  Swap -500  04/05/23
2 -200  04/05/23  STRAT1  Swap -500  04/05/23
3 -200  04/05/23  STRAT1  Swap -300  04/05/23


text:
Q: Request method 'POST' not supported at pass value I use the interceptor in spring to make the user has login in,but when i transfer value from front end to back,the interceptor intercept the request,but it warns me that
WARN 8484 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved[org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]

and send me to "/error",but i have add the controller into the excludePath like this
public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(cookiesInterceptor).addPathPatterns("/**")
            .excludePathPatterns("/adminapi/login")
            .excludePathPatterns("/Login.html")
            .excludePathPatterns("/index.html")
            .excludePathPatterns("/static/**");
    }

and the controller
@RequestMapping(value = "/adminapi")
public class AdminController {
   @RequestMapping("/login")
   public String .....
}

the action of form
<form th:action="@{/adminapi/login}" method="post">

so i do not know why the problem occur

A: In your AdminController,
replace @RequestMapping("/login")
with @PostMapping("/login")
This tells Spring Boot that you are using the POST method, otherwise by default GET is expected

A: I don't see the @Controller annotation in your AdminController
By the way, you should specify the method for your RequestMapping, you can use
@Controller
@RequestMapping(value = "/adminapi")
public class AdminController {
   @RequestMapping(value = "/login", method = RequestMethod.POST)
   public String .....
}

or
@Controller
@RequestMapping(value = "/adminapi")
public class AdminController {
   @PostMapping("/login")
   public String .....
}

A: *

*Check whether CSRF is enabled in spring security xml file . If so add the

So you should be able to submit the model attribute.
Seems duplicate check here Spring,Request method 'POST' not supported

*Check whethr on the Controller receiving function for Spring MVC , you ahve this annotation. @ModelAttribute

*For the requestmapping specify the method type .
@RequestMapping(value = "/login", method = RequestMethod.POST)


text:
Q: Where are the Woodflies? in the Quest Subduing the Woodflies i need to kill woodflies at a Take Spot. i would have assumed that i would get into a set encounter however i've checked the ones in A3 and B7 and neither have i faced woodflies.
The only place on Emerald Grove / B2 that i have yet to explore is behind the door with the White Crystal in C3 however since the quest appeared before i have learned how to open those doors with the crystals i would have assumed it's doable.
I am wondering, where are these wood flies i have to kill or are they behind the White Crystal Door in C3?
Note: i don't want to know how to open the White Crystal door in C3

A: You won't be able to get into that crystal door for a while. Near the stairs leading down to floor 3 (So it's on floor 2 of the labyrinth) to the left there is a small indent to the north in the hall of A6. There should be an event in that small indent. Beware, as there is an encounter with the mini-boss Giant Woodfly, though he is far easier than any FOEs.


text:
Q: Convert htaccess sef rewrite to lighttpd I read link: http://redmine.lighttpd.net/projects/1/wiki/Docs_ModRewrite
But I don't find how to sef_rewrite
htaccess
    RewriteRule . index.php?sef_rewrite=1 [L,QSA]
Could you help convert to lighttpd ?

A: lighttpd not using sef_rewrite
Please using:
url.rewrite-once = (

  "^/(images|css|js|lib|payments|skins|var)/(.*$)" => "$0",
  "^/([^.*]+)$" => "/index.php/$1/",
)


text:
Q: What are the set of cosets of an induced graph? I am reading Hau Huang's proof of the sensitivity conjecture and I am a bit confused by the group theory notation. I would like to understand the following line:

Recall that $Q^n$ denotes the n-dimensional cube graph. For an induced graph $H$ of $Q^n$, let $Q^n-H$ denote the subgraph of $Q^n$ induced on the vertex set $V(Q^n) \setminus V(H)$.

I am assuming that $V(Q^n) \setminus V(H)=\{V(Q^n)h:h\in V(H)\}$, but what does $gh$ mean when $g$ and $h$ are vertices?
Am I interpreting this correctly, and if so what does it mean?

A: This is not $/$, the quotient operator, but $\setminus$ the "set difference" operator.
See https://en.wikipedia.org/wiki/Complement_(set_theory)
In particular, this has nothing to do with cosets or group theory.


text:
Q: How to use some apply function to solve what requires two for-loops in R I have a matrix, named "mat", and a smaller matrix, named "center".
temp = c(1.8421,5.6586,6.3526,2.904,3.232,4.6076,4.8,3.2909,4.6122,4.9399)
mat = matrix(temp, ncol=2)
       [,1]   [,2]
[1,] 1.8421 4.6076
[2,] 5.6586 4.8000
[3,] 6.3526 3.2909
[4,] 2.9040 4.6122
[5,] 3.2320 4.9399

center = matrix(c(3, 6, 3, 2), ncol=2)

     [,1] [,2]
[1,]    3    3
[2,]    6    2

I need to compute the distance between each row of mat with every row of center. For example, the distance of mat[1,] and center[1,] can be computed as
diff = mat[1,]-center[1,]
t(diff)%*%diff
        [,1]
[1,] 3.92511

Similarly, I can find the distance of mat[1,] and center[2,]
diff = mat[1,]-center[2,]
t(diff)%*%diff
         [,1]
[1,] 24.08771

Repeat this process for each row of mat, I will end up with
          [,1]      [,2]
[1,]  3.925110 24.087710
[2,] 10.308154  7.956554
[3,] 11.324550  1.790750
[4,]  2.608405 16.408805
[5,]  3.817036 16.304836

I know how to implement it with for-loops. I was really hoping someone could tell me how to do it with some kind of an apply() function, maybe mapply() I guess.
Thanks

A: apply(center, 1, function(x) colSums((x - t(mat)) ^ 2))
#           [,1]      [,2]
# [1,]  3.925110 24.087710
# [2,] 10.308154  7.956554
# [3,] 11.324550  1.790750
# [4,]  2.608405 16.408805
# [5,]  3.817036 16.304836

A: If you want the apply for expressiveness of code that's one thing but it's still looping, just different syntax. This can be done without any loops, or with a very small one across center instead of mat. I'd just transpose first because it's wise to get into the habit of getting as much as possible out of the apply statement. (The BrodieG answer is pretty much identical in function.) These are working because R will automatically recycle the smaller vector along the matrix and do it much faster than apply or for.
tm <- t(mat)
apply(center, 1, function(m){
    colSums((tm - m)^2) })

A: Use dist and then extract the relevant submatrix:
ix <- 1:nrow(mat)
as.matrix( dist( rbind(mat, center) )^2 )[ix, -ix]

          6         7
# 1  3.925110 24.087710
# 2 10.308154  7.956554
# 3 11.324550  1.790750
# 4  2.608405 16.408805
# 5  3.817036 16.304836

REVISION: simplified slightly.

A: This will solve it
t(apply(mat,1,function(row){
  d1<-sum((row-center[1,])^2)
  d2<-sum((row-center[2,])^2)
  return(c(d1,d2))
}))

Result:
          [,1]      [,2]
[1,]  3.925110 24.087710
[2,] 10.308154  7.956554
[3,] 11.324550  1.790750
[4,]  2.608405 16.408805
[5,]  3.817036 16.304836

A: You could use outer as well
d <- function(i, j) sum((mat[i, ] - center[j, ])^2)
outer(1:nrow(mat), 1:nrow(center), Vectorize(d))