text:
Q: Why does the total least squares line in 2D pass through the average across all data points? I have $N$ data points $\mathbf{m_k}$ and I want to fit a line through them with minimal error $$J = \sum_k^N ||\mathbf{m_k^*} - \mathbf{m_k}||^2 = \sum_k^N ||\mathbf{m_0} + a_k\mathbf{e} - \mathbf{m_k}||^2.$$
$\mathbf{m_k^*}$ is the point on the line with minimal distance to $\mathbf{m_k}$. It is described as $\mathbf{m_0} + a_k\mathbf{e}$ where $\mathbf{m_0}$ is the support vector of the line and $\mathbf{e}$ a directional vector with length $1$.
My lecture slides contain a proof that $a_k = \mathbf{e}^T(\mathbf{m_k} - \mathbf{m_0})$, yielding $J = \sum_k^N ||\mathbf{m_0} + \mathbf{e}^T(\mathbf{m_k} - \mathbf{m_0})\mathbf{e} - \mathbf{m_k}||^2,$
but I don't get any further from there. My lecture just assumes that $\mathbf{m_0} = \mathbf{\bar{m}}$ and it does feel reasonable, but I want proof.
I tried to search on the internet but most articles e.g. this one want to predict a $y_i$ from $x_i$ (and use vertical offsets whereas I do perpendicular offsets). But I don't want to do a regression nor do I want to be restricted to two dimensional space.
I'm not even quite sure what it is called that I'm trying to do, my guess is total least squares but I'm pretty confused by the wikipedia page.

A: This question can be reduced to a simple Ordinary Least Squares problem of fitting a constant to a set of numbers, where it is well known (and easy to show) that the unique solution is the mean of those numbers.
The analysis comes down to selecting an appropriate coordinate system and analyzing the squared distances (from the data points to any line) coordinate by coordinate.  An appropriate coordinate system is one in which the direction along the line furnishes one coordinate (which happens to be irrelevant) and the other coordinates are perpendicular to it and to each other.

One way to define a line in $d$ dimensions is to provide $d-1$ mutually orthogonal unit vectors $\mathbf u_1, \ldots, \mathbf u_{d-1}$ and $d-1$ corresponding numbers $c_1, \ldots, c_{d-1}$.  The simultaneous solution $\mathbf x\in\mathbb{R}^d$ of the $d-1$ equations
$$\mathcal{L}: \mathbf u_i^\prime \mathbf x = c_i\tag{1}$$
is a line and all lines can be described in this way.
The squared distance between any vector $\mathbf m_k$ and this line is the sum of squared differences between the products $\mathbf u_i^\prime \mathbf m_k$ and the constants $c_i$:
$$\delta(\mathbf m_k, \mathcal{L}) = \sum_{i=1}^{d-1} (\mathbf u_i^\prime \mathbf m_k - c_i)^2.$$
When $\mathcal L$ is any line minimizing the sum of those squared distances to the $\mathbf m_k$, then each $c_i$ must separately minimize its corresponding term.  The result becomes obvious if we fix $i$ for the moment and rewrite this term in the form
$$y_k = \mathbf u_i^\prime \mathbf m_k,\tag{2}$$
for now we see that $c_i$ minimizes the sum $\sum_{k=1}^N (y_k - c_i)^2$.  This is the very simplest version of an Ordinary Least Squares problem, involving just one parameter $c_i$.
It's easy to see that
$$c_i = \bar y_k =  \frac{1}{N}\sum_{k=1}^N y_k\tag{3}$$
is the unique solution, because for any number $c$, the sum of squares
$$\sum_{k=1}^N (y_k - c)^2 = \sum_{k=1}^N (y_k - \bar y_k)^2 + N(c - \bar y_k)^2$$
depends on $c$ only through the second term, which obviously is minimized uniquely at $c = \bar y_k$.
Consider now the mean vector (or "barycenter")
$$\mathbf{\bar m} = \frac{1}{N}\sum_{k=1}^N \mathbf{m}_k.$$
To see whether it lies on $\mathcal L$, plug it in for $\mathbf x$ on the left hand side of $(1)$ and, for each $i$, use $(2)$ and $(3)$ to compute
$$\mathbf u_i^\prime \mathbf{\bar m} = \mathbf u_i^\prime \frac{1}{N}\sum_{k=1}^N \mathbf{m}_k = \frac{1}{N}\sum_{k=1}^N\mathbf u_i^\prime\mathbf{m}_k = \frac{1}{N}\sum_{k=1}^Ny_k = \bar y_k = c_i.$$
Thus $(1)$ holds, proving that the mean vector must lie on $\mathcal L$.

A: I believe you're talking about the least square regression line.
Basically, this is the line where the sum of the residuals of each data point to the line is minimised. A residual is the distance from the point to the LSR-line in an axis (i.e vertically or horizontally).
Now, let's make up some data. Pretend you have 2 points on a straight line, 10 units apart, and you want to find a point where the sum of the distance from each is minimised. It doesn't matter where you place it in the middle; 8 units + 2 units = 5 units + 5 units = 10 units + 0 units, etc. The sum of the distances always equals zero.
However, the least square regression line squares these residuals. As you may know, 102 + 02 is bigger than 82 + 22, which is bigger than 62 + 42, etc. The perfect minimised answer is 52 + 52. Therefore, the point should be right in the middle, which is the mean.
Extend this to a whole scattered data set, and the fact that you take the average of the y-axis and x-axis, and consider the fact that you take the residuals and not the distance, you can see why the line goes through the mean of x and y.


text:
Q: Event detect when shutdown or restart windows 8 I'm working on windows 8 metro style app. I want to show a save confirmation message whenever unexpected events occur such as shutdown or restart and prevent windows to do that event. However, I didn't find any handler event that fitting my need. How can I do that?

A: In general, a Windows app can prevent shutdown (sometimes) by responding with FALSE to a WM_QUERYENDSESSION message.  However, there is no way to get a WindowProc message from a Metro style app.  The best you can do in a Metro style app is handle the Suspending event properly in your app (this will not prevent a shutdown of course).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to display menu in adobe business catalyst? Sorry if my tone is not good,
How to display top menu in Adobe Business Catalyst.
Example:
My custom menu code is given below. Instead of this, I want to display menu created by adobe business catalyst.

Home

Case Studies

Traning

Coaching

Local groups

Deals

Resources

Gear

Contact Us

I am using this {tag_menugroup} to display menu. but menu is not displaying.

A: The tag you're using should only be used within custom layouts for menu version 2.
For inserting a dynamic menu to a template use you should instead
use {module_menu,ID#}
or for a more customisable version use  {module_menu, version="2", menuId="5475", moduleTemplateGroup="Default"}
Sources:
http://kb.worldsecuresystems.com/134/bc_1345.html#main_Menu_Modules
http://helpx.adobe.com/business-catalyst/partner/menu-module-v2.html


text:
Q: How to set the firefox binary in Serenity (previous to geckodriver)? I'm using the serenity 1.1.42 version and I would like to run my test cases in different versions of Firefox. To do that, I try to set where is the Firefox binary file, because I'm using Mac OS, but serenity always starts with the default installed version on mi computer, the last.
What I have tried? I put into the serenity.properties file this different combinations:
webdriver.firefox.driver=/Users/myuser/Applications/Firefox55.app/Contents/MacOS/firefox-bin

In other execution:
webdriver.firefox.preferences="firefox.binary=/Users/myuser/Applications/Firefox55.app/Contents/MacOS/firefox-bin"

In other execution:
webdriver.driver=/Users/myuser/Applications/Firefox55.app/Contents/MacOS/firefox-bin

In one more execution:
webdriver.firefox.bin=/Users/myuser/Applications/Firefox55.app/Contents/MacOS/firefox-bin

But no one of this configurations worked for me. How should I configure the serenity.properties file to run my own version of Firefox?
Thank you in advance.

A: I solve how to pass the Firefox binary. I should pass as argument in the execution:
-Dwebdriver.firefox.bin=/Users/myUser/Applications/Firefox44.app/Contents/MacOS/firefox-bin

But, two things to have in mind:

*

*It is important not used with geckodriver, because selenium 3.0, or higher, cannot work with old Firefox versions.

*I cannot set this property from the serenity.properties. It is ignored.


text:
Q: Get attached PDF file from HTTP request I would like to download a file like this: https://www.bbs.unibo.it/conferma/?var=FormScaricaBrochure&brochureid=61305 with Python.
The problem is that is not directly a link to the file, but I only get the file id with query string.
I tried this code:
    import requests

    remote_url = "https://www.bbs.unibo.it/conferma/"

    r = requests.get(remote_url, params = {"var":"FormScaricaBrochure", "brochureid": 61305})

But only the HTML is returned. How can I get the attached pdf?

A: You can use this example how to download the file using only brochureid:
import requests

url = "https://www.bbs.unibo.it/wp-content/themes/bbs/brochure-download.php?post_id={brochureid}&presentazione=true"
brochureid = 61305

with open("file.pdf", "wb") as f_out:
    f_out.write(requests.get(url.format(brochureid=brochureid)).content)

Downloads the PDF to file.pdf (screenshot):


text:
Q: Zero-Variance Removal I want to remove sensors which appear to have no variance? I removed all sensors with a temperature=0, and can sort by date/day of the week, but further errors within the data have came to light. Some sensors have a string of temperature recordings of 4.5 and 7.3 with no change across many days. I was reproducible code so don't want to simply remove 4.5 and 7.3 values
In [1]: df = pd.DataFrame([[A, 2.045], [A, 3.056], [B, 6], [B, 6], columns=['Sen', 'Temp'])

In [2]: df
Out[2]:
   Sen Temp
0  A  2.045
1  A  3.056
2  B  6
3  B  6
So I have grouped the data using basic group and sort functions to get a simple output as above. However. I want to remove all "B" sensors from df.Sen as the variance of values within df.Temp for B equals 0. I'm getting confused just typing this out but is this possible? I was thinking of creating a new column based on a variance calculation and deleting that way, but is there a simpler solution?
Out[2]:
   Sen Temp
0  A  2.045
1  A  3.05

A: You can use groupby().transform() to mask the variance:
df[df.groupby('Sen').Temp.transform('var') > 0]

Output:
  Sen   Temp
0   A  2.045
1   A  3.056

However, this might fail if you have some groups with only one valid data point. On the other hand, since variance 0 means only one value across the group, you can use nunique:
df[df.groupby('Sen').Temp.transform('nunique') > 1]


text:
Q: Show message before and after certain time Currently i am working on a webshop which sends it's orders placed before 17:00 the same day. On the succes or thank-you page i would like to place a message if it's before 17:00, after 17:00 and in the weekends. So three messages.
I'm trying this with PHP now:
<?php
            //Show message
            $before_17 = "Order received before 17:00, will ship today.";
            $after_17="Order placed after 17:00, will ship tomorrow.";
            $weekend = "It's weekend, order will be shipped on Monday.";

            //Time & Day
            $current_time = date(H);
            $current_day = date(D);

            //Saturday
            if ($current_day == Sat){
            echo $weekend;
            }

            //Sunday
            elseif ($current_day == Sun){
            echo $weekend;
            }

            //Weekdays > 17
            elseif ($current_time > 17){
            echo $after_17;
            }

            //Weekdays < 17
            elseif($current_time < 17){
            echo $before_17;
            }

            else{
            echo 'Niks';
            }
        ?>

I was hoping this should do the trick, but the page still shows the $before_17 after 17:00. Am i doing something wrong?

A: EDIT;
I just noticed another issue. You should use if ($current_time >= 17) (not just greater than) otherwise it will not take effect until the hour is 18.
Also you should use quotes in date()! Try date('H') & date('D') instead of date(H) and date(D). And quotes in the day comparisons if ($current_day === 'Sun').
Failing that, you should echo date('H'); To make sure the time on the server is set correctly.

A: 1 - use quotes in date(). like date('D')
2- use quotes in comparing strings in if. like if($current_day=='Sun')

A: This could be related to time zone issue
I encountered the same bug ($current_time was 16 even though it should have been 17)
Check this link for more info


text:
Q: Error 400 Failed Precondition server side gmail api php hi im trying to get a list of my email using gmail api with php but i got error 400, is PHP for Gmail API is still developed or just im doin it wrong ?
$optParams = [];
    $optParams['maxResults'] = 5; // Return Only 5 Messages
    $optParams['labelIds'] = 'INBOX'; // Only show messages in Inbox
    $optParams['q'] = 'from: "abc"'; // Only show messages in Inbox
    $list = $gmail->users_messages->listUsersMessages("my email",$optParams);

btw i'm non g suite and using service account
Thanks
--- update ---
Here's my $gmail variable source
 putenv('GOOGLE_APPLICATION_CREDENTIALS='.base_path('service_account.json'));
   $client->useApplicationDefaultCredentials();
    $client->setScopes(\Google_Service_Gmail::MAIL_GOOGLE_COM);
    $client->setAccessType('offline');        // offline access
    $client->setIncludeGrantedScopes(true);   // incremental auth
    $gmail = new \Google_Service_Gmail($client);


text:
Q: GCE Instance can't by reached by reserved static IP address I have a GKE cluster with two preemptible instances and one normal instance. I also have a reserved static IP address. I have very liberal firewall rules that basically open tcp:80 and tcp:443 on all nodes from all IP addresses.
If I assign my IP (http://35.226.235.154/) to one of the preemptible instances, I can access port 80 and 443 of the IP address (as expected). However, if I assign the IP to my normal instance, I can't access port 80 or 443. What am I missing?
EDIT:
So i tried to just access it by a normally assigned IP address, and it still does not work, so it seems like my NodePort service is not really working

A: You have to have a service listening on either port 80 or 443 to get a response from the node. You should see the open ports whether the external IP address is static or ephemeral. Normally, the node will host pods which (even if they are exposed on port 80) do not link directly to the node without a service in place (such as node port which does not use a load balancer).
You can also connect to another node to see if the ports are responding using the nodes internal IP address (SSH to node 1, test ports of node 2 using the internal IP address). There is no reason for the external IP address to affect whether a service responds on a port.


text:
Q: Ms acess 2 querys para as mesmas comboboxes Boas a todos estou a programar uma base de dados e gostaria de ter uma espécie de 3 querys.
Vou tentar ser o mais preciso possível.
Tenho 2 caixas de combinação que estão interligadas, neste caso especifico Marca e Modelo, sendo que quando escolho a marca so me mostra o modelo tal como eu queria, mas num outro formulário tenho uma situação que me tem dado bastantes dores de cabeça pois não há maneira de descobrir como o fazer.
formulario inserir carro
Neste formulario insiro o numero interno do veiculo e uso a query que falei acima.
formulario inserir peça
Neste eu gostaria de fazer algo diferente.
Ter uma caixa de texto em que insiro o numero interno do carro e o access vai automaticamente buscar os dados que inseri na tabela no formulário anterior mas caso não esteja presente esse numero eu queria que fizesse o que faz no formulário inserir carro.
Caso queira deixar livre o mesmo funciona mas se quiser fazer uma pesquisa dos dados dos carros inseridos perco a query que me faz a marca e o modelo estarem interligados..... posso fornecer o projecto se ajudar a alguém.

A: RESOLVIDO
Descobri posso fazer a query.
O que queria era mesmo isto que tá em codigo.
'UPDATE DE MARCA, MODELO, MOTORIZAÇÃO, ANO INICIO, ANO FIM, DATA MATRICULA, NUMERO DE PORTAS E COMBUSTIVEL QUANDO VFV EXISTIR
Private Sub Comando713_Click()
If Not IsNull(Me!Texto689.Value) Then
    Me!Combinação65.Value = DLookup("[MARCA]", "[CONSULTA DE VFV INSERIR PEÇAS]")
    Me!Combinação69.Value = DLookup("[MODELO]", "[CONSULTA DE VFV INSERIR PEÇAS]")
    Me!Texto73.Value = DLookup("[ANO INICIAL]", "[CONSULTA DE VFV INSERIR PEÇAS]")
    Me!Texto75.Value = DLookup("[ANO FINAL]", "[CONSULTA DE VFV INSERIR PEÇAS]")
    Me!Texto137.Value = DLookup("[MOTORIZAÇÃO]", "[CONSULTA DE VFV INSERIR PEÇAS]")
    Me!Combinação611.Value = DLookup("[NUMERO DE PORTAS]", "[CONSULTA DE VFV INSERIR PEÇAS]")
    Me!Texto137.Value = DLookup("[MOTORIZAÇÃO]", "[CONSULTA DE VFV INSERIR PEÇAS]")
    Me!Texto445.Value = DLookup("[CODIGO MOTOR]", "[CONSULTA DE VFV INSERIR PEÇAS]")
    Me!Combinação435.Value = DLookup("[COMBUSTIVEL]", "[CONSULTA DE VFV INSERIR PEÇAS]")
    Me.Texto696.SetFocus
    Me.Combinação65.AllowValueListEdits = False
End If
End Sub

Agora precisava que quando faço o DLookup os varios campos mudem para não editaveis.
Tentei este codigo sem sucesso:
Me.Combinação65.AllowValueListEdits = False


text:
Q: Package "mdframed" creating arbitrary gaps in the border I used to define a small environment with the package "mdframed". I've included the package in the following way:
\usepackage[framemethod=tikz]{mdframed}

This is how I've set up the environment:
\newenvironment{bspbox}
  [2]
  {\begin{mdframed}[linecolor=gray!25, innerleftmargin=3pt, innerrightmargin=3pt, leftmargin=5pt, rightmargin=5pt, skipabove=5pt, skipbelow=5pt, linewidth=0pt, frametitle={Title#2: #1}, frametitlefont=\normalfont\bfseries]}
  {\end{mdframed}}

It works okay, but unfortunately, there are some arbitrarily placed gaps interrupting the line / frame. They can appear in various places, but in most cases, it looks like in the following screenshot:

The environment was used in my document in the following way:
\begin{bspbox}{}{}
\lipsum[1]
\end{bspbox}

To sum it all up, this is what the MWE looks like:
\documentclass[a4paper,10pt]{article}
\usepackage[dvipsnames,usenames]{xcolor} % mehr vordefinierte Farben
\usepackage[utf8]{inputenc}
\parindent0pt
\usepackage{tikz}
\usetikzlibrary{mindmap,shadows,trees,positioning,arrows,shapes}
\usepackage[framemethod=tikz]{mdframed}
\usepackage{lipsum}

\newenvironment{bspbox}
  [2]
  {\begin{mdframed}[linecolor=gray!25, innerleftmargin=3pt, innerrightmargin=3pt, leftmargin=5pt, rightmargin=5pt, skipabove=5pt, skipbelow=5pt, linewidth=0pt, frametitle={Title#2: #1}, frametitlefont=\normalfont\bfseries]}
  {\end{mdframed}}

\begin{document}

\begin{bspbox}{}{}
\lipsum[1]
\end{bspbox}

\end{document}

Where lies my fault, why are there those arbitrary gaps interrupting the line?


text:
Q: Reference request: are levelsets/levelspaces (as defined here) used anywhere in mathematics? Thinking about unimodal distributions in multiple dimensions, I came up with the following.
Given a function $f : Y \leftarrow X$ where $X$ is a topological space, define that a levelset of $f$ is a subset $A$ of $X$ such that there exists $y \in Y$ such that $A$ is a connected component of $f^{-1}(y)$. Note that this differs somewhat from what appears to be the usual definition. By the levelspace, let us mean the collection of all level sets. Write $\mathrm{lev}_f$ for the levelspace of $f$. So $\mathrm{lev}_f$ is a partitioning of $X$. We get a (set-theoretic) factorization of $f$ as the composite of two functions,
$$f_1 : Y \leftarrow \mathrm{lev}_f, \mbox{ and } f_0 : \mathrm{lev}_f \leftarrow X.$$
Anyway, returning to the opening sentence, I had this idea that maybe we should define:

Definition. Given a function $f : Y \leftarrow X$ where $X$ is a topological space, $f$ is unimodal iff $\mathrm{lev}_f$ is
  homeomorphic to a connected subset of $\mathbb{R}.$

This assumes that we've chosen a topology on $\mathrm{lev}_f,$ of course; the most sensible choice seems to be that it is the final topology induced by $f_0$.
Anyway, I have a bunch of questions about all this.

Questions.
Q0. Are levelsets/levelspaces (as defined above) used anywhere in e.g. optimization theory, probability theory, or "hard" analysis? If so, what is the accepted terminology regarding these things, and where can I learn more?
Q1. Under reasonable hypotheses, does the above definition of "unimodal" agree with what appears to be the standard definition?
I quote from the wikipedia page:
"A more general definition, applicable to a function $f(X)$ of a vector variable $X$ is that $f$ is unimodal if there is a one to one differentiable mapping $X = G(Z)$ such that $f(G(Z))$ is convex. Usually one would want $G(Z)$ to be continuously differentiable with nonsingular Jacobian matrix."
Q2. Assuming $Y$ carries topological structure and $f : Y \leftarrow X$ is continuous, does it follow that $f_1$ is continuous?

I included "algebraic geometry" in the tags in the hope that someone in that community might know more about this, despite that these questions obviously doesn't fit that tag directly. Also, the main thing I wanted to ask is Q0. The other two questions should be treated as bonus questions, therefore posts that attempt to answer (with at least moderate levels of success) either/both of Q1/Q2 will be awarded a small bounty.


text:
Q: Spring Repository integration test I have a java project with spring framework. I have 4.3.12 (not spring boot!).
My repositories are interfaces, extended from spring base Repository interface.
I have implemented many unit tests with in-memory repositories, however in the database (postgreslq) I have some real database functions, which I would like to test. I cannot implement those with JPA queries.
Now I want to test those database functions, so I want to make integration test. However when the application context is initializing, i cannot load the repository interfaces, and receiving

Caused by:
  org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  qualifying bean of type 'com.company.model.UserRepository' available:
  expected at least 1 bean which qualifies as autowire candidate.
  Dependency annotations:
  {@org.springframework.beans.factory.annotation.Autowired(required=true)}
  exception.

Test class
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { ApplicationContext.class })
public class UserControllerIntegrationTest {
  @Autowired
  private UserRepository userRepository;

  .. test methods
}

The ApplicationContext.class is the real @Configuration class in the project. And it loads the datasource, entitymanagerfactory, transactionmanager, etc. when I execute the test.
package com.company.config;

import com.company.service.email.EmailService;
import com.zaxxer.hikari.HikariDataSource;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@PropertySources({
  @PropertySource("classpath:application.properties"),
  @PropertySource("file:${CCTNG_HOME}/application.properties")
})
@ComponentScan({"com.company"})
@EnableWebMvc
@EnableTransactionManagement
public class ApplicationContext {

  private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
  private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
  private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
  private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
  private static final String PROPERTY_NAME_DATABASE_MIGRATE_USERNAME = "db.migrate.username";
  private static final String PROPERTY_NAME_DATABASE_MIGRATE_PASSWORD = "db.migrate.password";

  private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
  private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
  private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
  private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
  private static final String PROPERTY_NAME_HIBERNATE_DDL_AUTO = "hibernate.hbm2ddl.auto";
//  private static final String PROPERTY_NAME_HIBERNATE_IMPORT_FILES = "hibernate.hbm2ddl.import_files";

  private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";

  private static final String PROPERTY_NAME_LDAP_URL = "ldap.url";
  private static final String PROPERTY_NAME_LDAP_USERNAME = "ldap.principal";
  private static final String PROPERTY_NAME_LDAP_PASSWORD = "ldap.password";

  private static final String PROPERTY_NAME_EMAIL_USERNAME = "email.username";
  private static final String PROPERTY_NAME_EMAIL_APPPASSWORD = "email.apppassword";

  @Resource
  private Environment environment;

  @Bean(initMethod = "migrate")
  public Flyway flyway() {
    Flyway flyway = new Flyway();
//    flyway.setBaselineOnMigrate(true);
//    flyway.setDataSource(dataSource());
    flyway.setDataSource(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL), environment.getRequiredProperty(PROPERTY_NAME_DATABASE_MIGRATE_USERNAME),
            environment.getRequiredProperty(PROPERTY_NAME_DATABASE_MIGRATE_PASSWORD), new String[]{});
    return flyway;
  }

//  @Value("classpath:schema-postgresql.sql")
//  private org.springframework.core.io.Resource schemaScript;
  @Bean
  public DataSource dataSource() {
    HikariDataSource dataSource = new HikariDataSource();

    dataSource.setDriverClassName(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
    dataSource.setJdbcUrl(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
    dataSource.setUsername(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
    dataSource.setPassword(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));

    return dataSource;
  }

  @Bean
  public PlatformTransactionManager transactionManager() throws ClassNotFoundException {
    JpaTransactionManager transactionManager = new JpaTransactionManager();

    transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());

    return transactionManager;
  }

  @Bean(name = "entityManagerFactory")
  @DependsOn("flyway")
  public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() throws ClassNotFoundException {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();

    entityManagerFactoryBean.setDataSource(dataSource());
    entityManagerFactoryBean.setPackagesToScan(environment.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
    entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);

    Properties jpaProterties = new Properties();
    jpaProterties.put(PROPERTY_NAME_HIBERNATE_DIALECT, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
    jpaProterties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
    jpaProterties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
    jpaProterties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
    jpaProterties.put(PROPERTY_NAME_HIBERNATE_DDL_AUTO, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DDL_AUTO));
//    jpaProterties.put(PROPERTY_NAME_HIBERNATE_IMPORT_FILES, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_IMPORT_FILES));

//    jpaProterties.put("spring.jpa.properties.hibernate.jdbc.batch_size", "25");
//    jpaProterties.put("spring.jpa.properties.hibernate.order_inserts", "true");
//    jpaProterties.put("spring.jpa.properties.hibernate.order_updates", "true");
//    jpaProterties.put("spring.jpa.properties.hibernate.generate_statistics", "true");
    entityManagerFactoryBean.setJpaProperties(jpaProterties);

    return entityManagerFactoryBean;
  }

  @Bean
  public LdapContextSource ldapContextSource() {
    LdapContextSource contextSource = new LdapContextSource();

    contextSource.setUrl(environment.getRequiredProperty(PROPERTY_NAME_LDAP_URL));
    contextSource.setUserDn(environment.getRequiredProperty(PROPERTY_NAME_LDAP_USERNAME));
    contextSource.setPassword(environment.getRequiredProperty(PROPERTY_NAME_LDAP_PASSWORD));

    return contextSource;
  }

  @Bean
  public LdapTemplate ldapTemplate() {
    return new LdapTemplate(ldapContextSource());
  }

  @Bean(name = "emailService")
  public EmailService email() {
    Properties props = new Properties();
    props.put("mail.smtp.host", "mailrelay.xxx.com");
    props.put("mail.smtp.port", "25");
    props.put("mail.smtp.auth", "false");
    props.put("mail.smtp.connectiontimeout", "10000");

    EmailService email = new EmailService(
            environment.getRequiredProperty(PROPERTY_NAME_EMAIL_USERNAME),
            environment.getRequiredProperty(PROPERTY_NAME_EMAIL_APPPASSWORD),
//            environment.getRequiredProperty(PROPERTY_NAME_EMAIL_APPROOT),
            props);

    return email;

  }
}

But for some reason the repositories are not initiated.
Thanks for any hint!


text:
Q: how to change user's TimeZone Need to change domain user TimeZone.
A Windows Service is running under X user's context, at runtime the Application takes X-user's TimeZone and generates "messages" with a different DateTime to local machine DateTime. need to run Windows Service as this user, so, Need to change this specific user's TimeZone to match machine's DateTime.
Setting / Time and Languages / Time zone was changed but it only aplies to local machine level, this is assumed by the following test (On a different server, different domain):
1.- Log on as A1 to server
2.- Change Settings / Time and Languages / Time zone to TZ1 (Hour on taskbar changed)
3.- Log on as B1, check Time zone property and this is TZ1
Maybe on Active Directory?
DateTime on "messages" can't be changed manually, those messages are generated on a third party dll.


text:
Q: looking for WCF basicHttpBinding https tutorial or samples I am using VSTS 2008 + .Net 3.5 + C# to develop a console application as a WCF cient, and host WCF service in IIS 7.0 at server side (server using Windows Vista x64).
Currently, my WCF client and server works quite well with http. Now I want to add https support and still use basicHttpBinding. Any easy to learn tutorials? I do not want to make too much modification to my WCF client/server and want to find a way which involves minimal code change. :-)
BTW: for IIS server certificate, I want client side to accept all server certificate. And I just use https encryption feature.
thanks in advance,
George

A: See those excellent articles:

*

*Fundamentals of WCF Security

*p&p WCF Security Application Scenarios

*MSDN Common Security Scenarios

*WCF Security Part 3 of 10

*WCF Security Guidance on Codeplex - basically covers everything there is, in great detail, sometimes almost a bit too much :-)

Marc

A: <bindings>
  <basicHttpBinding>
    <binding name="defaultBasicHttpBinding">
      <security mode="Transport">
        <transport clientCredentialType="None"/>
      </security>
    </binding>
  </basicHttpBinding>
</bindings>

<system.serviceModel>
  <services>
    <service behaviorConfiguration="MyServiceBehavior" name="MyServiceName">
      <endpoint address="https://XYZ.com/MyService.svc"
                binding="basicHttpBinding"
                bindingConfiguration="defaultBasicHttpBinding"
                contract="Axis.IServiceContract" />
      <behaviors>
        <serviceBehaviors>
          <behavior name="MyServiceBehavior">
            <serviceMetadata httpsGetEnabled="true"/>
            <serviceDebug includeExceptionDetailInFaults="false"/>
          </behavior>
        </serviceBehaviors>
      </behaviors>
    </service>
  </services>
</system.serviceModel>


text:
Q: How do they give fake load given to the cloud instances? Link to the video
In any case i'll explain what is happening in the video:
A single eucalyptus instance is running and he gives some type of load to the instance and it reaches a point where he automatically deploys another instance to help maintain the load.
After a while, he increases the load even further when a ec2 instance is created and i also help in maintaining the load. When he decreases the load, the instances gets terminated to save cose etc.,
My question is, what does he use to give fake load to the instances running and any pointers on how to determine it?
Is it possible to do it in python?

A: You can use Siege to test server performance. You can emulate HTTP load on an instance from the command line, with options like concurrent users (-c) and the duration of the connection (-t):
siege -c20 -t30 http://www.yoururl.com/

If you just want to generate load on the server, use a tool like Stress to create CPU/IO/memory load.
Use Siege responsibly.


text:
Q: sendmail messages not delivered after fixing name resolution On my server, sendmail was taking 60s to send a simple message. After some googling, I found out that it was due to a DNS problem. I had this log:

Sep 13 08:00:01 myserver sm-msp-queue[1493]: My unqualified host name (myserver) unknown; sleeping for retry
  Sep 13 08:01:01 myserver sm-msp-queue[1493]: unable to qualify my own domain name (myserver) -- using short name

The solution was to edit /etc/hosts and add names with a dot at the end

127.0.0.1 localhost locahost.
  127.0.0.1 myserver myserver.

Now sendmail runs very quickly, but the messages as not delivered anymore. I'm sending just a "hello" to my gmail account.

echo "hello" | sendmail -v "xxx@gmail.com"

I've seen some people saying that the remote server may reject messages, but I don't understand, because they were being delivered before altering the hosts file. I don't want to host a mail server. I just need to send messages to myself. Here's the output from the command line above:
220 myserver. ESMTP Sendmail 8.14.4/8.14.4/Debian-4.1ubuntu1; Fri, 18 Sep 2015 13:50:45 -0300; (No UCE/UBE) logging access from: localhost(OK)-localhost [127.0.0.1]
>>> EHLO myserver.
250-myserver. Hello localhost [127.0.0.1], pleased to meet you
...
250 2.0.0 Verbose mode
>>> MAIL From:<www-data@myserver> SIZE=3 AUTH=www-data@myserver
250 2.1.0 <www-data@myserver>... Sender ok
>>> RCPT To:<xxx@gmail.com>
>>> DATA
553 5.1.8 <xxx@gmail.com>... Domain of sender address www-data@myserver does not exist
503 5.0.0 Need RCPT (recipient)
>>> RSET
250 2.0.0 Reset state
>>> RSET
250 2.0.0 Reset state
www-data@myserver... Using cached ESMTP connection to [127.0.0.1] via relay...
>>> MAIL From:<> SIZE=1027
250 2.1.0 <>... Sender ok
>>> RCPT To:<www-data@myserver>
>>> DATA
250 2.1.5 <www-data@myserver>... Recipient ok
354 Enter mail, end with "." on a line by itself
>>> .
050 <www-data@myserver>... Connecting to local...
050 <www-data@myserver>... Sent
250 2.0.0 t8IGojKw022539 Message accepted for delivery
www-data@myserver... Sent (t8IGojKw022539 Message accepted for delivery)
Closing connection to [127.0.0.1]
>>> QUIT
221 2.0.0 myserver. closing connection

Messages are delivered when I specify a real sender address:

echo "hello" | sendmail -vf "sender@realdomain.com" "xxx@gmail.com"

But why messages were delivered when it couldn't resolve it's own name, and not now?

A: Ok. I hate when it happens. I just found the solution after posting it. @thrig is right. It must be a fully qualified name. I've changed my "hosts" file to:

127.0.0.1 localhost localhost.local
  127.0.0.1 myserver myserver.local

Now it works fine. Thank you all.


text:
Q: PHP object json_encode giving NULL values when echoing? I am currently trying to learn JSON and it is kicking my proverbial behind at the moment.
With a normal variable I was able to encode it fine and then echo to see the JSON string.
However I am wanting to encode an object but its not working:
Class tariff
{

    var $preset_name;
    var $name;
    var $net;
    var $inclusive;
    var $length;
    var $data;

        function __construct()
        {
            $preset_name = "Orange-1gb-ECL";
            $name = array ("1312" => "Orange 1gb Eclipse");
            $net = array ("12312" => "Orange");
            $inclusive = array ("1312" => "1GB");
            $length = array ("12312" => "12 Months");
            $data = array ("12312" => "12p per mb");
        }

}
        $tariff = new tariff();
        $tariff = json_encode($tariff);

    echo $tariff;
    return 0;

My output is:

{"preset_name":null,"name":null,"net":null,"inclusive":null,"length":null,"data":null}

Ive tried googling and searching on here but can't find my answer!
Help me Obi Wan, your my only hope!

A: Oh, you have some wrong usages at the constructor,
Should be like this :-
$this->preset_name = "Orange-1gb-ECL"; <-- assign to object property

Instead of
$preset_name = "Orange-1gb-ECL"; <-- assign local variable

A: Elaborating on another answer,
$preset_name = "Orange-1gb-ECL";

in a member function is actually initializing a local variable to the scope of that function. The $this keyword is your reference to your current instance of your current class, for the purpose of accessing constructs such as properties in the class-instance scope.


text:
Q: (java) My prime number generator works only up to 200 I'm using Eratosthenes' sieve as my framework. It works from 2-199 but it just stops printing values beyond that.
Here's my code:
import java.util.ArrayList;
public class Scratchpad
{
    public Scratchpad()
    {

    }

    public ArrayList<Integer> makeList(int max)
    {
        ArrayList<Integer> arrList = new ArrayList<Integer>();
        for (int i = 2; i <= max; i++)
        {
            arrList.add(i);
        }
        return arrList;
    }

    public ArrayList<Integer> removeMult(ArrayList<Integer> arrList, int n)
    {
        for (int i = 0; i < arrList.size(); i++)
        {
            if ((arrList.get(i) % n == 0) && arrList.get(i) != n)
            {
                arrList.remove(i);
                i--;
            }
        }
        return arrList;
    }

    public ArrayList<Integer> primesOnly(ArrayList<Integer> arrList)
    {
        for (int i = 0; i < arrList.size(); i++)
        {
            removeMult(arrList, arrList.get(i));
            System.out.println(arrList.get(i));
        }
        return arrList;
    }
}

It works for all primes 2-199.
cmd screen cap (sorry for shitty crop)

A: Code works fine with the following main:
public static void main (String[] args) {

    Scratchpad s = new Scratchpad();

    ArrayList nums = s.makeList(500);

    System.out.println(nums);
    System.out.println(s.primesOnly(nums));

}

I think you probably just only generated a list of numbers up to 200.


text:
Q: organize oracle records in a specific way i have this oracle sql table arrange like this (name and department they belong to)
george bush,sale
george bush,payroll
george bush,finance
other bush,sale
other bush,payroll
other bush,finance
other bush,marketing
I want to write sql so that the above records can be shown as
george bush,sale,payroll,finance,sale
other bush,sale,payroll,finance,sale,marketing


text:
Q: How to remove blanks and reorder words I have .replace(' ', ', ')
What I want is:
Hanks, Tom

What I am getting is :
Hanks,Tom

How do you do this?
Input string is Tom Hanks.
I want Hanks, Tom

A: You can split the string into an array and reorder the bits.
var str = "Tom Hanks";
var arr = str.split(' ');

console.log(arr[0] + ', ' + arr[1]);


text:
Q: Minimal installation requirements for compiling WP7 projects on a build server I'm attempting to find the minimum installation requirements for getting WP7 projects compiling on a Windows 2008 R2 build server. I'll be looking into automated testing using the emulator at a later point, but right now I'm stuck on the build side.
I realise this approach won't be supported and I'm willing to trash the VM at a later date if an update proves to be incompatible (assuming I get it to work at all)
I'm also aware of the workaround for installing the entire SDK on Windows 2008 R2, but I'm trying to avoid installation of Visual Studio (it's now become a curiosity more than anything else)
As it stands, I've installed the following from the SDK ISO:

*

*WCU\Silverlight4\silverlight_sdk.msi

*WCU\WindowsPhone\WindowsPhoneExtensions.msi

*WCU\WindowsPhone\VS_SDEProLightup-enu.msi

At this point, it is able to locate all the required MSBuild target files and even compiles the project. The problem appears at the end of the process during the XapPackager target, when it errors with:

Xap packaging failed. Unable to load DLL 'zlib114.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

Using Process Monitor, I can see that MSBuild finds the dll in the WP7 MSBuild targets directory that installs with the SDK with the only error being "FILE LOCKED WITH ONLY READERS" error to a CreateFileMapping+SyncTypeCreateSection, which it then falls back to a SyncTypeOther, which succeeds. Despite this, MSBuild still continue to look for the dll is all the other standard locations (Framework directory, SysWOW64, etc).
Any thoughts to why it might be failing?

A: If you're using TFS, Justin Angel has a great post on TFS2010 WP7 Continuous Integration. Given that TFS is just wrapping around MSBuild, you may find this a particularly useful resource. When it comes to doing the unit test integration, Deyan Ginev from Telerik has a series of posts that covers this.

A: FYI, I ended up fixing the zlib problem by using the dll from the Silverlight SDK, rather than the WP SDK.


text:
Q: Deriving the expected value of the sum of square residuals for linear regression I have a question regarding the following derivation (copied from page 11 here) for $E[\hat\sigma^2]$ where $\hat\sigma^2=\frac{1}{n}e^Te$ is the sum of square residuals in linear regression. The notes define $H = X(X^TX)^{-1}X^T$ and $e=y-X\hat\beta=(I-H)y=(I-H)\epsilon$ if $Y = X\beta+\epsilon$ (in pages 1-2).
I think there's a typo from equation 31 and onwards, because I can't see how equation 30 and 34 can be equal. I think every $e$ from equations 31 to 35 should be replaced with $\epsilon$, then equation 36 would be $\frac{1}{n}tr((I-H)\sigma^2)$ (using the fact that $\epsilon$ ~ $N(0,\sigma^2I)$) which gives the same result as equation 38. Is this correct?


text:
Q: ImportRow() not copying DataRows to DataTable in C# I have two tables that I want to "join" together. The first one has all columns that the second one has but the data is incomplete. Both tables have an ID which I will use to stitch them together. A merge doesn't work since the second table has more rows and it contains identical ID's various times.
This example will explain it better:
OldTable1:
+----+-------+---------+--------+
| ID | Name  | PhoneNr | Address|
+----+-------+---------+--------+
| 1  | Tim   | 0       |        |
+----+-------+---------+--------+
| 2  | Frank | 0       |        |
+----+-------+---------+--------+

OldTable2
+----+---------+--------+
| ID | PhoneNr | Address|
+----+---------+--------+
| 1  | 12345   | Avenue |
+----+---------+--------+
| 1  | 67890   | Street |
+----+---------+--------+
| 2  | 55555   | Alley  |
+----+---------+--------+

NewTable:
+----+-------+---------+---------+
| ID | Name  | PhoneNr | Address |
+----+-------+---------+---------+
| 1  | Tim   | 12345   | Avenue  |
+----+-------+---------+---------+
| 1  | Tim   | 67890   | Street  |
+----+-------+---------+---------+
| 2  | Frank | 55555   | Alley   |
+----+-------+---------+---------+

Here is my code:
DataTable newTable = oldTable1.Clone();

    foreach (DataRow drOld1 in oldTable1.Rows)
    {
        foreach (DataRow drOld2 in oldTable2.Rows)
        {
            if (drOld1["ID"].Equals(drOld2["ID"]))
            {
                DataRow newRow = oldTable1.NewRow();
                newRow.ItemArray = drOld1.ItemArray.Clone() as object[];

                newRow["PhoneNr"] = drOld2["PhoneNr"];
                newRow["Address"] = drOld2["Address"];
                newTable.ImportRow(newRow);
            }
        }
    }

I can't tell what is wrong. Everything seems to work until I get to the line with the ImportRow. The newRow includes all the correct information, it just doesn't add the row to newTable. I looked through several related questions and none of the answers solve my problem. I can't replace ImportRow() with Add() since it is another DataTable. OldTable1 and newTable have the exact same columns because I created newTable cloning the scheme from OldTable1. What am I missing here?
SOLUTION:
As pointed out correctly by aguertin the reason it wasn't working was the following:

The method NewRow() detaches the row which will cause the ImportRow()
  method to be ignored and no exception will be thrown either.

My personal solution was using the old rows of the first table instead of creating a new one. Everything works now as intended.
DataTable newTable = oldTable1.Clone();

        foreach (DataRow drOld1 in oldTable1.Rows)
        {
            foreach (DataRow drOld2 in oldTable2.Rows)
            {
                if (drOld1["ID"].Equals(drOld2["ID"]))
                {
                    drOld1["PhoneNr"] = drOld2["PhoneNr"];
                    drOld1["Address"] = drOld2["Address"];
                    newTable.ImportRow(drOld1);
                }
            }
        }

A: The method NewRow()  detaches the row which will cause the ImportRow() method to be ignored and no exception will be thrown either.
Use Add().... even though you say can't just create a temporary dictionary/table and store the values in there.


text:
Q: Updating a value in a random row through java in a sql table Image of my table as it is when I start this program.
What I have is a mostly empty table and I am trying to assign a value to a fixed number of elements. The column I am trying to edit is "Geschlecht" and the number of rows I want to edit is "copyMaen" (~50.000 entries). I would like to only select the rows where the value of "Geschlecht" was NULL before and I would like to select the rows randomly.
I am using SQLite through a JDBC driver.
This is the first time for me working with sql. This is how I tried to do it.
                try {
        Statement stmt = DBController.connection.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT Geschlecht FROM individuen WHERE Geschlecht IS NULL;");
        PreparedStatement ps = DBController.connection.prepareStatement("UPDATE individuen");
        while (copyMaen != 0) {
            if (rs.getRowId((int) (Math.random() * ReadCSV.sumBev)) == null) {
                ps.setInt(2, 0);
                ps.executeUpdate();
                copyMaen--;
            }
        }
        rs.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }

Obviosly this throws me Errors and I am not really sure how to go on from there. Could somebody point me in the right direction?

A: For anybody interested this is the solution:
try {
        Statement stmt = DBController.connection.createStatement();
        String select = "SELECT ID FROM individuen WHERE Geschlecht is NULL ORDER BY RANDOM()" +
        " LIMIT " + Integer.toString(copyMaen);
        ResultSet rs = stmt.executeQuery(select);
        PreparedStatement ps = DBController.connection.prepareStatement("UPDATE individuen set Geschlecht  = ? WHERE ID = ?;");
        // rs.beforeFirst();
        int count = 0;
        while (rs.next()) {
            ps.setInt(1, 0);
            ps.setInt(2, rs.getInt(1));
            ps.addBatch();
            if (count%100==0) {
                System.out.println(count);
            }
            count++;
        }
        DBController.connection.setAutoCommit(false);
        ps.executeBatch();
        DBController.connection.setAutoCommit(true);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

A: Try this,

Below update query is enough for update all row where Geschlecht  is
  null.

try {
        Statement stmt = DBController.connection.createStatement();
        String updateTableSQL = "UPDATE individuen set Geschlecht  = ? where Geschlecht IS NULL";
        PreparedStatement preparedStatement = dbConnection.prepareStatement(updateTableSQL);
        preparedStatement.setString(1, "0"); // set zero where Geschlecht null found
        // execute update SQL stetement
        preparedStatement.executeUpdate();
} catch (SQLException e) {
        e.printStackTrace();
}


text:
Q: Exception Handling in WebFlux publisher I'm wondering why the following way of WebFlux subscription DOESN'T cause a compilation error:
@Test public void handlingSubscriberError() {

List l = new ArrayList();
l.add("a");
    Mono.just(l)
          .subscribe(x -> {
           throw new Throwable();
           }, e -> log.error("Error occurred:", e));
}

whereas this one DOES, and suggests surrounding with a try/catch block:
    @Autowired private PersistenceService writer;

    @Test public void handlingSubscriberError() {

    List l = new ArrayList();
    l.add("A");
    Mono.just(l)
       .subscribe(x -> {
       writer.persistTo(x, "B", "C");  <== Unhandled exception type Throwable.
      }, e -> log.error("Error occurred:", e));
   }

What's the point of having an overloaded subscribe() with the error consumer as a second parameter when one is still forced to add a try-catch by the Java compiler?  Or am I missing something?  Is there a proper idiom for this in WebFlux?

A: You cannot throw checked exceptions(such as Throwable orIOException) from the subscriber. The subscribe() method takes a Consumer function, without any exception declarations. However, Reactor provides the Exceptions utility class  which can wrap any checked exception into an unchecked exception, as follows:
Mono.just("test")
    .subscribe(x -> {
        try {
            throw new Throwable("Error occurred:");
        } catch (Throwable e) {
            throw Exceptions.propagate(e);
        }
    }, e -> log.error("Error occurred: ", Exceptions.unwrap(e)));

The Exception.unwrap is used to get the original checked exception.


text:
Q: Parsing a Haskell source file without an explicit 'module M where' header with GHC 7 The guys at the Budapest Functional Programming meetup group finally convinced me to port Tandoori to GHC 7. Things are turning out OK, but I'm having a problem parsing .hs source files with no module M where header.
Here's a standalone version of the code that calls GHC's internal parser to parse source files:
module Main where

import SrcLoc
import FastString
import Outputable (showSDoc)
import Parser (parseModule)
import Lexer (unP, mkPState, ParseResult(..))
import StringBuffer (hGetStringBuffer)
import DynFlags (defaultDynFlags)
import System.Environment (getArgs)

parseMod src_filename = do
  buf <- hGetStringBuffer src_filename
  let loc = mkSrcLoc (mkFastString src_filename) 1 0
      dflags = defaultDynFlags
  case unP Parser.parseModule (mkPState dflags buf loc) of
    POk pst rdr_module -> return rdr_module
    PFailed srcspan message -> error $ showSDoc message

main = do
  args <- getArgs
  case args of
    [src_filename] -> parseMod src_filename
    _ -> error "Usage: parse-test filename.hs"

here's an input file that works:
foo = 1

here's another one that works:
module M where

foo = 1
bar = 2

and here's one that doesn't:
foo = 1
bar = 2

For this one, the output of the program above is:
*** Exception: parse error on input `='

Note that I'm using GHC's parser instead of something like haskell-src because the real code also uses the renamer from GHC.

A: We simply prepend a module header line to the source we want to get parsed by the parser of GHC. Would this help you?


text:
Q: I have issue with facebook-android-sdk * What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> Could not resolve all task dependencies for configuration ':app:debugCompileClasspath'.
   > Could not resolve com.facebook.android:facebook-android-sdk:latest.release.
     Required by:
         project :app
      > Skipped due to earlier error
      > Failed to list versions for com.facebook.android:facebook-android-sdk.
         > Unable to load Maven meta-data from https://api.mapbox.com/downloads/v2/releases/maven/com/facebook/android/facebook-android-sdk/maven-metadata.xml.
            > Could not get resource 'https://api.mapbox.com/downloads/v2/releases/maven/com/facebook/android/facebook-android-sdk/maven-metadata.xml'.
               > Could not GET 'https://api.mapbox.com/downloads/v2/releases/maven/com/facebook/android/facebook-android-sdk/maven-metadata.xml'. Received status code 403 from server: Forbidden
   > Could not resolve com.facebook.android:audience-network-sdk:6.11.0.
     Required by:
         project :app > com.google.ads.mediation:facebook:6.11.0.0
      > Skipped due to earlier error
      > Could not resolve com.facebook.android:audience-network-sdk:6.11.0.
         > Could not get resource 'https://api.mapbox.com/downloads/v2/releases/maven/com/facebook/android/audience-network-sdk/6.11.0/audience-network-sdk-6.11.0.pom'.
            > Could not GET 'https://api.mapbox.com/downloads/v2/releases/maven/com/facebook/android/audience-network-sdk/6.11.0/audience-network-sdk-6.11.0.pom'. Received status code 403 from server: Forbidden

Click on Project Structure from the icon available in the tool bar above.
Open Dependencies tab.
select
com.facebook.android:facebook-android-sdk:[4,5)
Remove the facebook dependency by clicking the minus(-) button on the extreme right side.
Now, Click on Plus(+) button on the right side above Minus button. Select Library dependency
Type Facebook on the search input box and click on the search button.
Choose com.facebook.android:facebook-login. click on Ok. Sync your Gradle.
and
 1)Remove this line from app/build.gradle ===>
 implementation 'com.facebook.android:facebook-android-sdk:[5,6)'

 2)Add this line in app/build.gradle ===>
  implementation 'com.facebook.android:facebook-android-
  sdk:latest.release'

 3)Add this in android/build.gradlew
 allprojects {
repositories {

    google()
    mavenLocal()
    maven {
        // Android JSC is installed from npm
        url("$rootDir/../node_modules/jsc-android/dist")
    }
   mavenCentral().  <====== Add this
    google()
    jcenter()
    maven { url 'https://www.jitpack.io' }
  }
}

BUT NOT WORK

A: In the app's build.gradle add
implementation 'com.facebook.android:facebook-android-sdk:12.3.0'

inside the dependencies element


text:
Q: App crashes when I try to read data from Cloud Firestore I am new to Kotlin, and I was trying to insert and read data from Cloud Firestore with the following code:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import com.google.firebase.firestore.FirebaseFirestore

class MainActivity : AppCompatActivity() {

    private val db = FirebaseFirestore.getInstance()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val insertButton = findViewById<Button>(R.id.insertButton)
        val getButton = findViewById<Button>(R.id.getButton)

        insertButton.setOnClickListener {
            db.collection("users").document("testUser").set(
                hashMapOf("name" to "test1", "username" to "test2")
            )
        }

        getButton.setOnClickListener {
            db.collection("users").document("testUser").get().addOnSuccessListener {
                findViewById<EditText>(R.id.test1TextView).setText(it.get("name") as String)
                findViewById<EditText>(R.id.test2TextView).setText(it.get("username") as
                String)
            }
        }

    }
}

Layout file:
 <?xml version="1.0" encoding="utf-8"?>
 <androidx.constraintlayout.widget.ConstraintLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity">

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:layout_marginEnd="16dp"
    android:orientation="vertical"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <TextView
        android:id="@+id/test1TextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Test1" />

    <TextView
        android:id="@+id/test2TextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Test2" />

    <Button
        android:id="@+id/insertButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="insert" />

    <Button
        android:id="@+id/getButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get" />
</LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

The app is simple, with two buttons, one to insert on the database and the other to read from it and change some TextViews with the read data. The app looks like this: https://i.stack.imgur.com/5VLXG.png
The "Insert" button works fine and creates the data on the Firestore properly (Firestore image: https://i.stack.imgur.com/anapG.png). The problem comes when  the "Get" button is clicked and the app tries to read data from the Firestore, it simply crashes.
Logcat output:
--------- beginning of crash
2022-03-15 06:04:15.889 20433-20433/com.eugenisb.testapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.eugenisb.testapp, PID: 20433
java.lang.ClassCastException: com.google.android.material.textview.MaterialTextView cannot be cast to android.widget.EditText
    at com.eugenisb.testapp.MainActivity.onCreate$lambda-2$lambda-1(MainActivity.kt:28)
    at com.eugenisb.testapp.MainActivity.$r8$lambda$dpktUtUdZqv_kK0jh4DAEzfEDP0(Unknown Source:0)
    at com.eugenisb.testapp.MainActivity$$ExternalSyntheticLambda2.onSuccess(Unknown Source:4)
    at com.google.android.gms.tasks.zzm.run(com.google.android.gms:play-services-tasks@@18.0.1:1)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:201)
    at android.os.Looper.loop(Looper.java:288)
    at android.app.ActivityThread.main(ActivityThread.java:7839)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

I do not know if the solution to this is trivial, but I tried searching for a solution to this and did not find it.
Thank you for your answers.

A: According to the crash logs you're using MaterialTextView rather than EditTextView. Change the type cast of findViewById<EditText>(R.id.test1TextView).setText(it.get("name") as String) to findViewById<MaterialTextView >(R.id.test1TextView).setText(it.get("name") as String) or what ever type of textview you are using. Perhaps show your xml layout to further confirm the type of view you are using.


text:
Q: SQL SERVER ¿Si ya existe el numero de transacción, sumarle 1? Buen día estoy elaborando un trabajo en SQL SERVER donde se me pidió sumarle un número al número de transacción que están repetidas de la tabla TRANSACCIONESREPORTAR para que este número de transacción pueda ser único.
Por ejemplo: en este trabajo el numero de transacción por reglamento interno  debe estar compuesto por:

año+mes+día+numero de sucursal+numero de agencia+numero de computadora+correlativo

Hago la consulta a la tabla TRANSACCIONESREPORTAR Y veo que hay números de transacciones que se repiten porque el correlativo se genera por default 00 en todas entonces lo que tengo que hacer es que si se repite sumarle 1, por ejemplo las transacciones que están:

2019120101540800
2019120101540800

Deben de quedar:

2019120101540800
2019120101540801

ejemplo 2:
Las transacciones que están

2019120201490300,
2019120201490300,
2019120201490300

Deben quedar :

2019120201490300,
2019120201490301,
2019120201490302

Alguna idea De como hacerlo.

A: Como ya te han comentado, no hagas un cursor si puedes evitarlo, no es porque para este caso no fuera válido, que si puede serlo, sino porque es una muy mala práctica en un lenguaje declarativo como Sql Server.
En el ejemplo que te han expuesto, hay alguna incorrección, pero es un muy buen camino.
Create table TransaccionesReportar(
CodigoCorrelativo varchar(16),
OtroCampo int
);
GO
INSERT INTO TransaccionesReportar (CodigoCorrelativo, OtroCampo)
VALUES
('2019120101540800',1),
('2019120101540800',2),
('2019120201490300',3),
('2019120201490300',4),
('2019120201490300',5);
GO
;WITH CTE
AS (SELECT CodigoCorrelativo +
        (ROW_NUMBER() OVER(PARTITION BY CodigoCorrelativo
        ORDER BY CodigoCorrelativo)-1) AS NuevoCodigo,
        CodigoCorrelativo
        FROM TransaccionesReportar)
UPDATE Cte Set CodigoCorrelativo = NuevoCodigo FROM CTE;
GO
SELECT * FROM TransaccionesReportar

El Código recoge lo que tenga tu campo CodigoCorrelativo y siempre que sea igual, row_number se irá aumentando de 1 en 1. Cuando CodigoCorrelativo cambie, row_number empezará en 1. Por tanto tu codigo, más el autonumerador -1 es igual a lo que solicitas.
Row_number Numerar Filas
Cte: Tablas de expresión comun

Ok, si tienes una letra en medio, puedes variar el código así:
;WITH CTE
AS (SELECT
RIGHT(CodigoCorrelativo,4) +
    (ROW_NUMBER() OVER(PARTITION BY CodigoCorrelativo
    ORDER BY CodigoCorrelativo)-1)  AS NuevoCodigo,
    CodigoCorrelativo
    FROM TransaccionesReportar)
    UPDATE CTE set CodigoCorrelativo =
        LEFT(CodigoCorrelativo,LEN(CODIGOCORRELATIVO)-4) --    ParteIzquierda
        +
        case
            when len(NuevoCodigo) < 4 then RIGHT('0000' +  CAST(NUEVOCODIGO AS varchar(4)),4)
        ELSE CAST(NUEVOCODIGO AS varchar(4)) END
        from cte;
GO
SELECT * FROM TransaccionesReportar

Pero este escenario es para una migración de datos. O lo que significa que vas a realizar una update una vez, o alguna vez, no es para insertar registros con esta codificación.
Básicamente el código varía en que recogemos, por partes el viejo código, solo utilizando los 4 últimos dígitos como parte entera para sumar.
Existen otras modos o maneras, pero cuanto más complejo sea tú escenario, un poco más compleja será la query.

A: Hola amigo aquí te deje un ejemplo con unas simples lineas de código y no usando un cursor como debes de saber es mas pesado y consume muchos recursos.
Claro tu lo harias con tu tabla.
DECLARE @Table TABLE(
CodigoTran nvarchar(100)
)

INSERT INTO @Table VALUES ('2019120101540800'),('2019120101540800'),('2019120101540800'),('2019120101540800')

;WITH CTE_FOR_UPDATE AS(
SELECT CodigoTran+ ROW_NUMBER() OVER(PARTITION BY CodigoTran ORDER BY CodigoTran) AS NEWCodigoTran,CodigoTran FROM @Table)
UPDATE CTE_FOR_UPDATE SET CodigoTran=NEWCodigoTran

SELECT * FROM @Table

Aqui el ejemplo funcionando.
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=fc53c1f541b28a9f40baea0dfbe61065

A: Primeramente, lo que estás haciendo es una violación a la primera regla de normalización. Ninguna columna debe contener valores compuestos. Al menos, no deberían de existir como columna física.
Tu tabla debe quedar de esta forma (añado 2 opciones una para la creación de la tabla y otra para sólo agregar la columna calculada).
CREATE TABLE TRANSACCIONESREPORTAR(
    fecha   date,
    sucursal char(2),
    agencia char(2),
    computadora char(2),
    correlativo tinyint,
    -- Otras columnas
    clave_transaccion AS CONCAT(CONVERT(char(8), fecha, 112),sucursal, agencia, computadora, RIGHT( 100 + correlativo, 2))
);

ALTER TABLE TRANSACCIONESREPORTAR ADD nueva_clave_transaccion AS CONCAT(CONVERT(char(8), fecha, 112),sucursal, agencia, computadora, RIGHT( 100 + correlativo, 2));

INSERT INTO TRANSACCIONESREPORTAR
VALUES  ( GETDATE(), '01', '54', '08', 0),
        ( GETDATE(), '01', '54', '08', 1);

GO

SELECT *
FROM TRANSACCIONESREPORTAR

Ahora, lo complicado es mantener el correlativo. Esto es porque si 2 procesos tratan de insertar al mismo tiempo, pueden generar duplicados. Sin embargo, la opción sencilla suele ser algo así:
DECLARE @fecha      date = GETDATE(),
        @sucursal   char(2) = '01',
        @agencia    char(2) = '54',
        @computadora    char(2) = '08';

INSERT INTO TRANSACCIONESREPORTAR
SELECT @fecha,
        @sucursal,
        @agencia,
        @computadora,
        ISNULL((SELECT MAX( correlativo)
                FROM TRANSACCIONESREPORTAR
                WHERE fecha = @fecha
                AND sucursal = @sucursal
                AND agencia = @agencia
                AND computadora = @computadora
                ) + 1, 0);

El 1, se debe cambiar por un ROW_NUMBER() si se van a insertar varias filas al mismo tiempo.

A: Podrías recorrer con un cursor y solo actualizar el dato que necesitas
DECLARE cursorActualiza CURSOR
    FOR SELECT * FROMTabla WHEREcampo = combinacionQueYaSabes

Open cursorActualiza

FETCH NEXT FROM cursor INTO variableTemporal;
    WHILE @@FETCH_STATUS = 0
    BEGIN
        --Logica para actualizar cada registro
    END;
    CLOSE cursorActuliza;
DEALLOCATE cursorActualiza;

Recomendaría que lo hicieras dentro de una transacción para que puedas validar que sea correcto el resultado


text:
Q: Deadlock when insert on duplicate key update sql using on multi unique key Is sql like insert ... on duplicate key update will generate gap locks on every unique key index/primary key, disordered, when the row is not in table?
I found that when using multi transactions to execute insert on duplicate key update sql on table with more than one unique key may cause deadlock.
My table was like:
| Table | Create Table
| test | CREATE TABLE `test1` (
  `c1` int(11) NOT NULL,
  `c2` int(11) DEFAULT NULL,
  `c3` int(11) DEFAULT NULL,
  PRIMARY KEY (`c1`),
  UNIQUE KEY `uk` (`c2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

After the deadlock arise,I got engine innodb status:
------------------------
LATEST DETECTED DEADLOCK
------------------------
2018-12-06 20:01:57 0x70000ee06000
*** (1) TRANSACTION:
TRANSACTION 2219555, ACTIVE 0 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 3 lock struct(s), heap size 1136, 2 row lock(s), undo log entries 1
MySQL thread id 6686, OS thread handle 123145569476608, query id 6114936 localhost 127.0.0.1 root update
INSERT INTO test1 (`c1`, `c2`, `c3`) VALUES (15538, 1213457428, 30) ON DUPLICATE KEY UPDATE `c3` = VALUES(`c3`)
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 65 page no 29 n bits 848 index cc of table `compare_db`.`test1` trx id 2219555 lock_mode X locks gap before rec insert intention waiting
Record lock, heap no 749 PHYSICAL RECORD: n_fields 2; compact format; info bits 0
 0: len 4; hex c88c97bb; asc     ;;
 1: len 4; hex 80002c42; asc   ,B;;

*** (2) TRANSACTION:
TRANSACTION 2219538, ACTIVE 0 sec inserting
mysql tables in use 1, locked 1 4 lock struct(s), heap size 1136, 3 row lock(s), undo log entries 1
MySQL thread id 6631, OS thread handle 123145551896576, query id 6114889 localhost 127.0.0.1 root update
INSERT INTO test1 (`c1`, `c2`, `c3`) VALUES (535, 1215380840, 30) ON DUPLICATE KEY UPDATE `c3` = VALUES(`c3`)
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 65 page no 29 n bits 840 index cc of table `compare_db`.`test1` trx id 2219538 lock_mode X locks gap before rec
Record lock, heap no 749 PHYSICAL RECORD: n_fields 2; compact format; info bits 0
 0: len 4; hex c88c97bb; asc     ;;
 1: len 4; hex 80002c42; asc   ,B;;

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 65 page no 29 n bits 848 index cc of table `compare_db`.`test1` trx id 2219538 lock_mode X locks gap before rec insert intention waiting
Record lock, heap no 749 PHYSICAL RECORD: n_fields 2; compact format; info bits 0
 0: len 4; hex c88c97bb; asc     ;;
 1: len 4; hex 80002c42; asc   ,B;;

*** WE ROLL BACK TRANSACTION (1)

It would be just fine when insert directly.
So I was thinking, is that because the two session both happened to locked gap (a, b) on uk, and (c, d) on primary key when deadlock arose, but with different order.
Is anyone knows the real reason?


text:
Q: VoIP one-way audio, only when call initiated from one side I am setting up some new switches and VLANs and I am getting trouble with our pre-existing Asterisk VoIP set-up.
Most calls work ok. Some get just one-way audio. I tried to narrow it down to this specific test situation:
Asterisk server is 10.0.10.10.
Call that works ok:
If phone 10.0.2.183 calls phone on 10.0.10.47, audio flows well both ways. This working call is depicted in this Wireshark diagram:

Call that gets only one-way audio:
If instead, I swap the situation and initiate from the other phone, i.e. phone 10.0.10.47 calls phone on 10.0.2.183, audio flows only one-way: 10.0.2.183 can't hear 10.0.10.47. This faulty call is depicted in this Wireshark diagram:

NAT?
I see a lot of stuff online suggesting the typical cause of one-way audio is NAT. I don't think I am using NAT. How can I check? This is all internal inside my LAN.
Firewall?
I have spent a ton of time tinkering with the iptables firewall on 10.0.10.10, opening everything up (even if just provisionally, as a test). I don't see how it could be blocking this particular bit of traffic, while letting so much through. But I humbly submit that iptables is a wild beast that I cannot fully tame. Any ideas here?
Routing?
I also suspect possible routing issues, since I am moving servers around and isolating VLANs from each other (except the VoIP VLAN, which is 10.0.10.*, and should be accessible to all other VLANs). I had to play with the routing table on 10.0.10.10 to get some traffic going the way I want:
:/home1/_locals/operator# ip route
(1) 192.168.1.248/29 dev eth1  proto kernel  scope link  src 192.168.1.250
(2) 10.0.0.0/24 dev eth0  proto kernel  scope link  src 10.0.0.1
(3) 10.0.1.0/24 dev eth3  proto kernel  scope link  src 10.0.1.1
(4) 10.0.10.0/24 dev eth2  proto kernel  scope link  src 10.0.10.10
(5) 10.0.0.0/8 via 10.0.10.1 dev eth2
(6) default via 192.168.1.254 dev eth1

I've numbered the rules so you can comment on them if you want.
Any ideas on how to troubleshoot this? Why is everything going through except some very specific bits of RTP traffic? Thanks in advance for you help.
Additional requested info
DHCP Config in 10.0.10.0/24 network:

This should provide straight-forward routing tables on the phones, only 10.0.10.10 has static IP and the altered routing table provided further above.
Simplified network topology:

In reality this is a lot more funky, I am half-way in a move between two topologies. So I have two 10.0.0.0 subnets, for example. But they are supposedly kept separate. My problem probably arises from this funkiness, but I need to pinpoint exactly which bit of configuration is missing to make it work.
Routing table on 10.0.10.1, which is Ubiquiti UDM
# ip route
10.0.0.0/24 dev br3 proto kernel scope link src 10.0.0.1
10.0.1.0/24 dev br5 proto kernel scope link src 10.0.1.1
10.0.2.0/24 dev br6 proto kernel scope link src 10.0.2.1
10.0.3.0/24 dev br4 proto kernel scope link src 10.0.3.1
10.0.10.0/24 dev br8 proto kernel scope link src 10.0.10.1
10.1.1.0/24 dev br0 proto kernel scope link src 10.1.1.1
10.2.2.0/24 dev br2 proto kernel scope link src 10.2.2.1
192.168.1.0/24 dev eth4 proto kernel scope link src 192.168.1.86

Firewall on the same host:
# iptables-save
# Generated by iptables-save v1.6.1 on Fri May  7 22:04:20 2021
*nat
:PREROUTING ACCEPT [30400:5954281]
:INPUT ACCEPT [9407:875595]
:OUTPUT ACCEPT [31671:2057109]
:POSTROUTING ACCEPT [25363:1582041]
:UBIOS_INPUT_JUMP - [0:0]
:UBIOS_OUTPUT_JUMP - [0:0]
:UBIOS_POSTROUTING_JUMP - [0:0]
:UBIOS_POSTROUTING_USER_HOOK - [0:0]
:UBIOS_PREROUTING_JUMP - [0:0]
-A PREROUTING -j LOG --log-prefix "::PREROUTING:"
-A PREROUTING -j UBIOS_PREROUTING_JUMP
-A INPUT -j LOG --log-prefix "::INPUT:"
-A INPUT -j UBIOS_INPUT_JUMP
-A OUTPUT -j LOG --log-prefix "::OUTPUT:"
-A OUTPUT -j UBIOS_OUTPUT_JUMP
-A POSTROUTING -j LOG --log-prefix "::POSTROUTING:"
-A POSTROUTING -j UBIOS_POSTROUTING_JUMP
-A UBIOS_POSTROUTING_JUMP -j UBIOS_POSTROUTING_USER_HOOK
-A UBIOS_POSTROUTING_USER_HOOK -o eth4 -m comment --comment 00000001095216660481 -j MASQUERADE
COMMIT
# Completed on Fri May  7 22:04:20 2021
# Generated by iptables-save v1.6.1 on Fri May  7 22:04:20 2021
*mangle
:PREROUTING ACCEPT [5740653266:1557524250007]
:INPUT ACCEPT [5729417629:1548285462113]
:FORWARD ACCEPT [11076849:9225341544]
:OUTPUT ACCEPT [5729656413:1548109771107]
:POSTROUTING ACCEPT [5741373562:1557359586630]
:UBIOS_FORWARD_JUMP - [0:0]
:UBIOS_FORWARD_TCPMSS - [0:0]
:UBIOS_FORWARD_USER_HOOK - [0:0]
:UBIOS_INPUT_JUMP - [0:0]
:UBIOS_INPUT_USER_HOOK - [0:0]
:UBIOS_OUTPUT_JUMP - [0:0]
:UBIOS_OUTPUT_USER_HOOK - [0:0]
:UBIOS_POSTROUTING_JUMP - [0:0]
:UBIOS_POSTROUTING_SHAPER - [0:0]
:UBIOS_POSTROUTING_USER_HOOK - [0:0]
:UBIOS_PREROUTING_JUMP - [0:0]
:UBIOS_PREROUTING_USER_HOOK - [0:0]
-A PREROUTING -j UBIOS_PREROUTING_JUMP
-A INPUT -j UBIOS_INPUT_JUMP
-A FORWARD -j UBIOS_FORWARD_JUMP
-A OUTPUT -j UBIOS_OUTPUT_JUMP
-A POSTROUTING -j UBIOS_POSTROUTING_JUMP
-A UBIOS_FORWARD_JUMP -j UBIOS_FORWARD_TCPMSS
-A UBIOS_POSTROUTING_JUMP -j UBIOS_POSTROUTING_SHAPER
COMMIT
# Completed on Fri May  7 22:04:20 2021
# Generated by iptables-save v1.6.1 on Fri May  7 22:04:20 2021
*filter
:INPUT ACCEPT [3169950958:856215960609]
:FORWARD ACCEPT [4175578:2973708433]
:OUTPUT ACCEPT [3170232928:856108555985]
:UBIOS_FORWARD_IN_USER - [0:0]
:UBIOS_FORWARD_JUMP - [0:0]
:UBIOS_FORWARD_OUT_USER - [0:0]
:UBIOS_FORWARD_USER_HOOK - [0:0]
:UBIOS_INPUT_JUMP - [0:0]
:UBIOS_INPUT_USER_HOOK - [0:0]
:UBIOS_IN_GEOIP - [0:0]
:UBIOS_LAN_IN_USER - [0:0]
:UBIOS_LAN_LOCAL_USER - [0:0]
:UBIOS_LAN_OUT_USER - [0:0]
:UBIOS_OUTPUT_JUMP - [0:0]
:UBIOS_OUTPUT_USER_HOOK - [0:0]
:UBIOS_OUT_GEOIP - [0:0]
:UBIOS_WAN_IN_USER - [0:0]
:UBIOS_WAN_LOCAL_USER - [0:0]
:UBIOS_WAN_OUT_USER - [0:0]
-A INPUT -j LOG --log-prefix "::INPUT1:"
-A INPUT -j UBIOS_INPUT_JUMP
-A FORWARD -j LOG --log-prefix "::INPUT2:"
-A FORWARD -j UBIOS_FORWARD_JUMP
-A OUTPUT -j LOG --log-prefix "::INPUT3:"
-A OUTPUT -j UBIOS_OUTPUT_JUMP
-A UBIOS_FORWARD_IN_USER -i eth4 -m comment --comment 00000001095216663481 -j UBIOS_WAN_IN_USER
-A UBIOS_FORWARD_IN_USER -i br0 -m comment --comment 00000001095216663482 -j UBIOS_LAN_IN_USER
-A UBIOS_FORWARD_IN_USER -i br2 -m comment --comment 00000001095216663483 -j UBIOS_LAN_IN_USER
-A UBIOS_FORWARD_IN_USER -i br3 -m comment --comment 00000001095216663484 -j UBIOS_LAN_IN_USER
-A UBIOS_FORWARD_IN_USER -i br4 -m comment --comment 00000001095216663485 -j UBIOS_LAN_IN_USER
-A UBIOS_FORWARD_IN_USER -i br5 -m comment --comment 00000001095216663486 -j UBIOS_LAN_IN_USER
-A UBIOS_FORWARD_IN_USER -i br6 -m comment --comment 00000001095216663487 -j UBIOS_LAN_IN_USER
-A UBIOS_FORWARD_IN_USER -i br8 -m comment --comment 00000001095216663488 -j UBIOS_LAN_IN_USER
-A UBIOS_FORWARD_JUMP -j UBIOS_FORWARD_USER_HOOK
-A UBIOS_FORWARD_OUT_USER -o eth4 -m comment --comment 00000001095216663481 -j UBIOS_WAN_OUT_USER
-A UBIOS_FORWARD_OUT_USER -o br0 -m comment --comment 00000001095216663482 -j UBIOS_LAN_OUT_USER
-A UBIOS_FORWARD_OUT_USER -o br2 -m comment --comment 00000001095216663483 -j UBIOS_LAN_OUT_USER
-A UBIOS_FORWARD_OUT_USER -o br3 -m comment --comment 00000001095216663484 -j UBIOS_LAN_OUT_USER
-A UBIOS_FORWARD_OUT_USER -o br4 -m comment --comment 00000001095216663485 -j UBIOS_LAN_OUT_USER
-A UBIOS_FORWARD_OUT_USER -o br5 -m comment --comment 00000001095216663486 -j UBIOS_LAN_OUT_USER
-A UBIOS_FORWARD_OUT_USER -o br6 -m comment --comment 00000001095216663487 -j UBIOS_LAN_OUT_USER
-A UBIOS_FORWARD_OUT_USER -o br8 -m comment --comment 00000001095216663488 -j UBIOS_LAN_OUT_USER
-A UBIOS_FORWARD_USER_HOOK -m comment --comment 00000001095216663481 -j UBIOS_FORWARD_IN_USER
-A UBIOS_FORWARD_USER_HOOK -m comment --comment 00000001095216663482 -j UBIOS_FORWARD_OUT_USER
-A UBIOS_INPUT_JUMP -j UBIOS_INPUT_USER_HOOK
-A UBIOS_INPUT_USER_HOOK -i eth4 -m comment --comment 00000001095216663481 -j UBIOS_WAN_LOCAL_USER
-A UBIOS_INPUT_USER_HOOK -i br0 -m comment --comment 00000001095216663482 -j UBIOS_LAN_LOCAL_USER
-A UBIOS_INPUT_USER_HOOK -i br2 -m comment --comment 00000001095216663483 -j UBIOS_LAN_LOCAL_USER
-A UBIOS_INPUT_USER_HOOK -i br3 -m comment --comment 00000001095216663484 -j UBIOS_LAN_LOCAL_USER
-A UBIOS_INPUT_USER_HOOK -i br4 -m comment --comment 00000001095216663485 -j UBIOS_LAN_LOCAL_USER
-A UBIOS_INPUT_USER_HOOK -i br5 -m comment --comment 00000001095216663486 -j UBIOS_LAN_LOCAL_USER
-A UBIOS_INPUT_USER_HOOK -i br6 -m comment --comment 00000001095216663487 -j UBIOS_LAN_LOCAL_USER
-A UBIOS_INPUT_USER_HOOK -i br8 -m comment --comment 00000001095216663488 -j UBIOS_LAN_LOCAL_USER
-A UBIOS_LAN_IN_USER -d 10.0.10.10/32 -j LOG
-A UBIOS_LAN_IN_USER -d 10.0.10.10/32 -m comment --comment 00000001095216662480 -j RETURN
-A UBIOS_LAN_IN_USER -s 10.0.10.10/32 -j LOG
-A UBIOS_LAN_IN_USER -s 10.0.10.10/32 -m comment --comment 00000001095216662481 -j RETURN
-A UBIOS_LAN_IN_USER -s 10.0.2.0/24 -m comment --comment 00000001095216666481 -j RETURN
-A UBIOS_LAN_IN_USER -s 10.0.3.0/24 -m comment --comment 00000001095216666482 -j RETURN
-A UBIOS_LAN_IN_USER -s 10.0.1.0/24 -m comment --comment 00000001095216666483 -j RETURN
-A UBIOS_LAN_IN_USER -s 10.2.2.0/24 -m comment --comment 00000001095216666484 -j RETURN
-A UBIOS_LAN_IN_USER -s 10.0.10.0/24 -m comment --comment 00000001095216666485 -j RETURN
-A UBIOS_LAN_IN_USER -s 10.1.1.0/24 -m comment --comment 00000001095216666486 -j RETURN
-A UBIOS_LAN_IN_USER -s 10.0.0.0/24 -m comment --comment 00000001095216666487 -j RETURN
-A UBIOS_LAN_IN_USER -j LOG
-A UBIOS_LAN_IN_USER -m comment --comment 00000001097364144127 -j RETURN
-A UBIOS_LAN_LOCAL_USER -j LOG
-A UBIOS_LAN_LOCAL_USER -m comment --comment 00000001097364144127 -j RETURN
-A UBIOS_LAN_OUT_USER -d 10.0.2.0/24 -m comment --comment 00000001095216666481 -j RETURN
-A UBIOS_LAN_OUT_USER -d 10.0.3.0/24 -m comment --comment 00000001095216666482 -j RETURN
-A UBIOS_LAN_OUT_USER -d 10.0.1.0/24 -m comment --comment 00000001095216666483 -j RETURN
-A UBIOS_LAN_OUT_USER -d 10.2.2.0/24 -m comment --comment 00000001095216666484 -j RETURN
-A UBIOS_LAN_OUT_USER -d 10.0.10.0/24 -m comment --comment 00000001095216666485 -j RETURN
-A UBIOS_LAN_OUT_USER -d 10.1.1.0/24 -m comment --comment 00000001095216666486 -j RETURN
-A UBIOS_LAN_OUT_USER -d 10.0.0.0/24 -m comment --comment 00000001095216666487 -j RETURN
-A UBIOS_LAN_OUT_USER -j LOG
-A UBIOS_LAN_OUT_USER -m comment --comment 00000001097364144127 -j RETURN
-A UBIOS_WAN_IN_USER -m conntrack --ctstate RELATED,ESTABLISHED -m comment --comment 00000001095216663481 -j RETURN
-A UBIOS_WAN_IN_USER -m conntrack --ctstate INVALID -m comment --comment 00000001095216663482 -j DROP
-A UBIOS_WAN_IN_USER -m comment --comment 00000001097364144127 -j DROP
-A UBIOS_WAN_LOCAL_USER -m conntrack --ctstate RELATED,ESTABLISHED -m comment --comment 00000001095216663481 -j RETURN
-A UBIOS_WAN_LOCAL_USER -m conntrack --ctstate INVALID -m comment --comment 00000001095216663482 -j DROP
-A UBIOS_WAN_LOCAL_USER -m comment --comment 00000001097364144127 -j DROP
-A UBIOS_WAN_OUT_USER -m comment --comment 00000001097364144127 -j RETURN
COMMIT

I don't have any port forwarding configured. I am not versed in NAT so if there's any other place I should be checking, please advise in the comments.

A: Just to leave some information regarding how I eventually solved this...
My reasoning was: if the SIP negotiation was successful, as made obvious by the packet captures, then it really wasn't a routing or firewall problem. I mean, it could still be a firewall problem, if it was letting some things through but not others (like other ports etc). But since I knew my rules were generic enough, if these devices could find routes to each other and talk to each other, this wasn't the cause of my issue.
This was made obvious by starting the call from the other phone instead. The RTP traffic flows, it routes, it passes the firewall.
So I should be focusing on SIP issues, how the choices for RTP traffic destinations are made. Eventually I had a break-through by thinking the packets are getting sent somewhere, so where are they getting sent to?. I went looking  (with tcpdump) and I found them reaching the UDM on 10.0.0.1 instead of 10.0.10.10.
Inspecting the contents of those SIP INVITE packets you see in the Wireshark diagrams above, I actually found references to 10.0.0.1. Why? Because my Asterisk server thinks it's both 10.0.0.1 and 10.0.10.10 (two interfaces) but that is only true on the old topology, not on the new. So, despite me having configured both phones to use 10.0.10.10 as their SIP server, and despite the fact that they obey when starting the call from one side, and despite the fact that when starting it from the other side they are able to obey for SIP negotiation, one side still (!!!) ends up sending RTP traffic to the wrong address.
How to fix this properly: fix Asterisk configuration. I don't know how, and since this is a server about to go deprecated, and to which I don't have full access, I decided not to try this route.
How I actually fixed it: during the time when this asterisk server is going to be progressively phased out, I am re-routing UDP traffic on these specific RTP ports from
10.0.0.1 to 10.0.10.10. This was hard to achieve, but it works! Read about it here: Routing traffic for specific port range


text:
Q: In wordpress video attachment mkv format not playing .How to play them? I have added video as attachment , its automatically playing mp4 videos but not others as mkv. Please help!

A: It's playing MP4 because the browsers support natively MP4 files; for different video format the best way is to decode your MKV videos in MP4 format.
For other info:
https://wordpress.org/support/topic/how-do-i-embed-mkv-videos/
For more info about the media supported natively by the browsers:
https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats#Browser_compatibility


text:
Q: How can I view the contents of each partition in GParted? In GParted, I'm trying to remove a partition that I'm not using (to make space for another operating system). The partition to remove is either dev/dev6 or dev/dev7. How can I view the contents of either partition (to make sure that I'm not accidentally deleting the wrong partition)?
I tried using the command cd /dev/sda6 to view the partition sda6, but then I got the following output: bash: cd: /dev/sda6: Not a directory. Is there another way to view the contents of a specific partition?

A: *

*You can use MiniTool® Partition Wizard Bootable CD 7.6.
It can explore volumes through its GUI.

(I for myself needed that option last week but I can't remember what software we were using.
It has the same ability. I think it was Paragon Partition Manager)

A: GPartEd is made for dealing with partitions, not files. :)
Why not look at dev6 and dev7 in a terminal window instead of trying to do it in GPartEd?
More info on the terminal window included in the GPartEd LiveCD see the GPartEd documentation.
for info on navigating in Linux, check out:

*

*Changing Drive In Linux

*Change Directory in Terminal?


text:
Q: How to create PDF preview in Angular 9 I'm using the PdfViewerModule from ng2-pdf-viewer. I just wanted to have a display of the pdf file before or after it was uploaded. Is there are a way for me to get file which I uploaded on my web-application as a URL and paste that as the source of the pdf-viewer? Thanks!
        <pdf-viewer
            [src]="tmpPdfUrl" // paste here the URL of the uploaded file for preview
            [render-text]="true"
            [original-size]="false"
            [zoom]="1"
        ></pdf-viewer>


text:
Q: How to debounce a function inside modelChange function using lodash debounce? I have a function which invokes whenever the model changed. I want to use debounced function inside the modelChange function.
I am using lodash debounce but it is not invoking the function what am i doing wrong?
modelChange Function:
 onModelChange(model) {
    _.debounce(function() {
      alert('debouned');
    }, 2000)
  }

Here is link to Stackbiltz

A: Creating method for debouncing and calling it inside of onModelChange should do the trick:
debouncedOnChange = _.debounce(function() {
  alert('debounced');
}, 2000);

onModelChange(model) {
  // alert('model has been changed');
  this.debouncedOnChange();
}

stackblitz


text:
Q: Making background of a png picture transparent on a Frame in Tkinter I have a png picture which I show on a Frame as follows:
self.aaa = PhotoImage(file="some.png")
self.lbl1 = Label(self, image=self.aaa)
self.lbl1.pack()

The background of the picture is white and the background the Frame is darker. Can I somehow make the background of the Picture transparent without editing the picture, doesn't Tkinter allow that?


text:
Q: Android notification click to open app only works 1st time I have a foreground service with a notification. I create the notification like this:
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setOngoing(true)
            .setContentTitle("App name")
            .setContentText(Utility.getNotificationContentText())
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setContentIntent(pendingIntent)
            .setOnlyAlertOnce(true)
            .build();

On the notification I set a pending intent like so:
    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

When I click the notification the first time, it works as expected. It opens the app. However, when I click the notification the second time, nothing happens.
For what it's worth, I open the MainActivity.class, but my app has different fragments. I would like to open a specific fragment, but I am not sure if I can pass FragmentName.class into the intent.
Any help for getting the notification click to work every time?

A: Set the below flags of the PendingIntet so that you can update if there is a current pending intent with the new PendingIntent.
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
              PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);

A: I managed to fix it. The problem was that I was updating the notification with a intent that had the wrong class.


text:
Q: My discord bot turn offline but my script still work My bot run on Windows, with python. It's work fine but sometime, it's turn offline. When I go to my PC to see if the programe had stop I see that it's not closed and still work, with no error. Is that a discord api error ?

A: Your computer may be going in sleep mode, and that may explain why when you turn it on it looks like it is still going. I could be wrong since you have not provided any code, but that is my understanding of the situation.


text:
Q: HapiJS view file not found despite locations searched including the location of the file? When attempting to access my route at localhost:82/view I receive the following error:
Debug: internal, implementation, error
    Error: View file not found: `index.jsx`. Locations searched: [views\index.jsx]
    at Object.exports.create (C:\Git\react_playground\node_modules\hapi\node_modules\boom\lib\index.js:21:17)
    at Object.exports.internal (C:\Git\react_playground\node_modules\hapi\node_modules\boom\lib\index.js:254:92)
    at Object.exports.badImplementation (C:\Git\react_playground\node_modules\hapi\node_modules\boom\lib\index.js:290:23)
    at C:\Git\react_playground\node_modules\hapi\node_modules\vision\lib\manager.js:420:26
    at done (C:\Git\react_playground\node_modules\hapi\node_modules\items\lib\index.js:30:25)
    at C:\Git\react_playground\node_modules\hapi\node_modules\vision\lib\manager.js:415:20
    at Object.oncomplete (fs.js:108:15)

My file tree is like so:
react_playground
|-src
| |-views
| | |-index.jsx
| |-module1.js
|-Gruntfile.js
|-...

You can kind of see that I'm trying to set up a livereloading workflow in Grunt (something I've never done before) but that's irrelevant to the issue. I'm concerned right now purely with why my view is unable to be found despite it searching in views\index.js.
module1.js:
var Hapi = require('hapi');
var engine = require('hapi-react')();

var server = new Hapi.Server();
server.connection({host: 'localhost',port: 82});

server.views({
  defaultExtension: 'jsx',
  path: 'views',
  engines: {
    jsx: engine, // support for .jsx files
    js: engine // support for .js
  }
});

server.route({
  method: 'GET',
  path: '/' ,
  handler: function (request, reply) {
    console.log('Got a request!');
    reply('Welcome to my HAPI-React Page!');
  }
});

server.route({
  method: 'GET',
  path: '/view',
  handler: function(request, reply) {
    reply.view('index', {
      name: 'Test'
    });
  }
});

server.start();

index.js:
/** @jsx React.DOM **/

var React = require('react');
var HelloMessage = React.createClass({
  render: function() {
    return
Hello {this.props.name}
;
  }
});

module.exports = HelloMessage;

Gruntfile.js:
module.exports = function(grunt) {
  // Project configuration
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    jshint: {
      files: ['Gruntfile.js', 'src/*.js', 'src/**/*.js']
    },
    concurrent: {
      dev: {
        tasks: ['nodemon', 'node-inspector', 'watch'],
        options: {
          logConcurrentOutput: true
        }
      }
    },
    nodemon: {
      dev: {
        script: './src/module1.js',
        options: {
          nodeArgs: ['--debug'],
          env: {
            PORT: '82'
          },
          // omit this property if you aren't serving HTML files and
          // don't want to open a browser tab on start
          callback: function (nodemon) {
            nodemon.on('log', function (event) {
              console.log(event.colour);
            });

            // opens browser on initial server start
            nodemon.on('config:update', function () {
              // Delay before server listens on port
              setTimeout(function() {
                require('open')('http://localhost:82');
              }, 1000);
            });

            // refreshes browser when server reboots
            nodemon.on('restart', function () {
              // Delay before server listens on port
              setTimeout(function() {
                require('fs').writeFileSync('.rebooted', 'rebooted');
              }, 1000);
            });
          }
        }
      }
    },
    watch: {
      files: ['.rebooted'],
      options: {
        livereload: true
      }
    },
    inject: {
      single: {
        scriptSrc: 'build/devscript.js',
        files: {
          // TODO: specify file to inject devScript into
        }
      }
    }
  });

  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-nodemon');
  grunt.loadNpmTasks('grunt-inject');
  grunt.loadNpmTasks('grunt-open');

  // Default task(s).
  grunt.registerTask('default', ['nodemon', 'open', 'watch']);
};


text:
Q: Remove values from subarrays javascript Having some difficulty removing the row 0 in all my subarrays
Tried splice as well but can't seem to find a good example that remove values from subarrays.
Arr1
// This is how my main Arr1 looks like
(3) [Array(2), Array(2), ...]
0: (2) ["2021-07-06T00:00:00Z", {…}]
1: (2) ["2021-07-06T00:00:00Z", {…}]
...

// Which will have multiple subarrays when the main array is expanded
0: Array(2)
0: "2021-07-06T00:00:00Z"
1: {type: "meeting", id: "123"}

1: Array(2)
0: "2021-07-06T00:00:00Z"
1: {type: "call", id: "456"}

....

End result - Remove row 0, which is the date & time from each array and combine all of them together
0: {type: "meeting", id: "123"}
1: {type: "call", id: "456"}

A: Since you have nested arrays you will have to combine map and filter. Map to iterate the top level and filter or splice (depending on your logic) - on the sub to remove or filter out items.
topArray.map(subArray => subArray.filter(item => ...))
or
topArray.map(subArray => subArray.splice(start, deleteCount)
If you then want to "flatten" the results you can add .flat() or .flatMap() to the end (depending on your logic)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

If you know that you just want to grab the first item on each sub-array, you can:
topArray.map(subArray => subArray[0])

A: I would personnaly recommand using map which here takes for each element in your array, the second element (which is your object)

const arr = [
    ["2021-07-06T00:00:00Z", {type:"meeting",id:"123"}],
    ["2021-08-06T00:00:00Z", {type: "call", id: "456"}],
    ["2021-09-06T00:00:00Z", {type: "zoom", id: "789"}]
];

console.log(arr.map(item => item[1]))

A: Here's how you can do it:
let result = [];
let arr = [
    ["2021-07-06T00:00:00Z", {type:"meeting",id:"123"}],
    ["2021-07-06T00:00:00Z", {type: "call", id: "456"}]
];
result = arr.map((item)=>{
    return item[1];
})
console.log(result);

A: You can use a slice to remove the first element of each subarray. And a flatMap to join all the filtered subarrays into one single array.
Here's how I would do it:
const filteredArray = array.flatMap((subarray) => subarray.slice(1));

A: use Map with filter
var a = [[1,2], [3,4]]

console.log(a.map((b) => b.filter((c, i) => i != 0)))

Result
[[2], [4]]


text:
Q: Embedded Parser Memory Use XML vs JSON vs? I have an embedded weberver which is currently used to administer various bits of hardware over a network.
Currently it has a browser type web interface, but I need to enhance it to provide a REST API so that its functions can be automated and the obvious choice would be to use XML or JSON.
The device only has 8MB of RAM and 4MB of flash so code size and memory usage are critical.
The obvious choices are JSON and XML for the interface and I would be interested to know which you think would be the most efficient approach (or something else) and best library. (It's coded in C)
An additional constraint I should mention is that whatever I spec I will be documenting and providing to customers to build against so human readable is better.
This is the JSON library I've been looking at: http://zserge.bitbucket.org/jsmn.html
and this is the XML: http://expat.sourceforge.net/

A: JSON is generally more light weight and efficient than xml (e.g. less  rules, less corner cases, shorter data, more similar to actual datatypes, ...)
Or if you want it to be really efficient, you could uses a binary format like BSON.


text:
Q: Limit Text and make sure there are no tags open So i have a list of articles, and I have a page in which shows 4 articles at a time and then shortens the description of the article to 1000 characters and allows users to "read more", my problem is within each post there could be tags IE:  or    etc, how when truncating the text can I see if there are any open tags within the div or within the called upon text?
Here is how it looks for now
$sum = strip_tags($article, '
');
    if (strlen($sum) > 1000) {
        $sumCut = substr($sum, 0, 1000);
        $sum = substr($sumCut, 0, strrpos($sumCut, ' ')).'...
Read More
';
}

 echo $sum;

For example
If I have...
Quisque imperdiet imperdiet fringilla. Quisque sit amet nibh odio. Fusce sit amet massa vitae mi faucibus viverra.
The code fo that would be Quisque imperdiet imperdiet fringilla. Quisque sit amet nibh odio. Fusce sit amet massa vitae mi faucibus viverra.
but if I were to set my truncating number to say 10, it would leave that tag open and thus everything afterwords would be in italics

A: so dynamic got me close, but using strpos() was the key, I added this to my code if ((strpos($sum, '')) && (!strpos($sum, ''))) { echo ""; } and one similar for each tag that I allow, next thing to do is to figure out how to make sure that there are no images or iframes near the end of the post, I will edit this to explain how I did that, but for now here is my code...
$sum = strip_tags($article, '
');
if (strlen($sum) > 1000) {
    $sumCut = substr($sum, 0, 1000);
    $sum = substr($sumCut, 0, strrpos($sumCut, ' '));
    $cut = 1;
}else{
    $cut = 0; }

echo $sum;
if ((strpos($sum, '')) && (!strpos($sum, ''))) { echo ""; }

if ($cut==1) { echo '...
Read More
'; }

EDIT:
Okay, I figured out a better solution than making sure there were no images at the end of the post, I simply made the divs overflow: hidden; in which it would resize for the images
EDIT:
I also had an issue with breaking the middle of a
 tag, it was leaving me with <br a temporary fix seems to be to add another
 after everything which in these cases leaves the bad code <br
 but atleast everything works and isnt visible, but if anybody has a more viable solution please let me know
I hope this helps

A: Using strpos(), search for open tags within the first X characters (where X is the truncating number.) Then if true, add to a string.
Basically, (pseudocode)
if(first10chars.contains[use strpos here] "" and !.contains "") {
$endstr .= "";
}

and do the same for the others. A pretty bad way but it'll work