text:
Q: Dismiss modal when navigating to another screen I have an App with Home Screen, in this screen I'm rendering a Modal which opens on button press, inside the Modal I have a button that is supposed to navigate me to another screen, it's navigating correctly but when I navigate to another screen the modal doesn't disappear, how can i hide it?
Adding the code to demonstrate
Home:
import React, { Component } from 'react';
import Modal from './Modal';

class Home extends Component {
  state = {
    isModalVisible: false
  };

  toggleModal = () =>
    this.setState({ isModalVisible: !this.state.isModalVisible });

  render() {
    const { navigate } = this.props.navigation;

    <Modal
    visible={this.state.isModalVisible}
    navigation={this.props.navigation}
    />
    );
  }
}

export default Home;

Modal:
import React, { Component } from "react";
import Modal from "react-native-modal";

class Modal extends Component {

  render() {
    const { navigate } = this.props.navigation;

    return (
        <Modal
        isVisible={this.props.visible}>
          <Button onPress={() => {navigate('Main')}}>
            >Button</Text>
          </Button>
        </Modal>
    );
  }
}

export default Modal;

A: Ideally you should wait for the setState to finish inside the callback and then navigate to the screen, since the methods are async and may disrupt the state if navigate is called before setState has finished completing.
Also parent should control the state of the child.
Home
onNavigate = () => {
  this.setState({isModalVisible: false}, () => this.props.navigation.navigate('Main')
}

<Modal
    visible={this.state.isModalVisible}
    onNavigate={this.onNavigate}
 />

Modal
<Modal
  isVisible={this.props.visible}>
    <Button onPress={this.props.onNavigate}>
      <Text>Button</Text>
    </Button>
</Modal>

A: You should provide a reference to the variable that defines the visibility state of the modal component. You'll need to define a function hides the modal and pass the function reference to the modal component and execute it on press of the button along side with the navigation action.
Something on the lines of -
Your home screen should have a function like -
onModalClose = () => {this.setState({isModalVisible: false})}

then pass this as reference to the modal component like -
  <Modal
visible={this.state.isModalVisible}
navigation={this.props.navigation}
onModalClose={this.onModalClose}
/>

and call it on the onPress() method of the <Button/> component like-
          <Button onPress={() => {this.props.onModalClose(); navigate('Main')}}>

EDIT
Just noticed, since you already have a function that toggles the visibility of your modal, you need not define a new function. You can pass that function reference to the modal component itself.
  <Modal
visible={this.state.isModalVisible}
navigation={this.props.navigation}
onModalClose={this.toggleModal}
/>

A: I took Pritish Vaidya answer and made it usable for any screen.
Home
import React, { Component } from 'react';
import Modal from './Modal';

class Home extends Component {
  state = {
    isModalVisible: false
  };

  toggleModal(screenName) {
    this.setState({isModalVisible: !this.state.isModalVisible });
    if (screenName && screenName != '') {
       this.props.navigation.navigate(screenName);
    }
  }

  render() {
    <Modal
      visible={this.state.isModalVisible}
      onDismiss={(screenName) => { this.toggleModal(screenName); }}
    />
    );
  }
}

export default Home;

Modal:
class Modal extends Component {

    dismissScreen(screenName) {
        const dismissAction = this.props.onDismiss;
        dismissAction(screenName);
    }

    render() {
      return(
        <View style={{ flex: 1, padding: 20 }}>
            <Button
            title="Dismiss Modal"
            onPress={() => {this.dismissScreen();}}
            />
            <Button
            title="Navigate to Other Screen"
            onPress={() => {this.dismissScreen('ScreenName');}}
            />
        </View>
      );
    }
}


text:
Q: Using Restet with Guice DI & GWT I've got a fairly simple GWT app set up using GWT-RPC and Guice.  At the moment I'm serving two things, the GWT-RPC service and an applet that accepts uploads.  It looks something like this:
public class MyGuiceModule extends ServletModule {
@Override
protected void configureServlets() {
        serve("/path/to/service").with(MyGWTServiceImpl.class);
        serve("/path/to/upload").with(MyUploadServlet.class);
        //bunch of bindings follow...
    }
}

I'd like to be able to serve restlet resources or a restlet application from the same application and configure them in my guice module rather than the web.xml.  Previously I've set up REST backed GWT apps using Restlet but it didn't use DI so I'm a bit lost as to how this should work.
eta: here's my web.xml
  <?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE web-app
      PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
      "http://java.sun.com/dtd/web-app_2_3.dtd">

  <web-app>

    <filter>
      <filter-name>guiceFilter</filter-name>
      <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
    </filter>

    <filter-mapping>
      <filter-name>guiceFilter</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
      <listener-class>com.whatever.MyGuiceBootstrap</listener-class>
    </listener>

    <!-- Default page to serve -->
    <welcome-file-list>
      <welcome-file>home.html</welcome-file>
    </welcome-file-list>

  </web-app>

update
This solves the problem, cheers!
    bind(ServerServlet.class).in(Singleton.class);
    Map<String,String> initParams = new HashMap<String,String>();
    initParams.put("org.restlet.application", "path.to.your.RestletApplication");
    serve("/api/*").with(ServerServlet.class,initParams);

update2
Finally went with a solution I adapted from http://hpehl.info/google-appengine-restlet-guice.html which allows me to using injection within my resources and a single line to bind in the guicemodule.

A: Restlet offers a Restlet -> Servlet adapter with the org.restlet.ext.servlet.ServerServlet class. You should bind this to the desired path, and let it know the name of your Application like this:
serve("/api/*").with(ServerServlet.class);
getServletContext().setAttribute(
    "org.restlet.application", "com.you.MyApplication");

Where com.you.MyApplication should be replaced with your actual implementation of the org.restlet.Application class.

A: Well, i tought you add your old web.xml. But this should solve your problem.
serve("/api/*").with(ApiServlet.class);

If you are not using plain Servlet as implementation of your REST api, it will be a bit tricky. Jersey can be integrated with Guice either.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Batch File how to run all files in folder I am trying to find a batch file command that will allow me to run all .lnk or .html files with in a folder. I tried using the wildcards (*.lnk) but this wouldn't work. Any ideas?

A: Based upon further comments, this should help - you don't need recursion to process a single folder, and this will handle long filenames.
@echo off
for %%v in ("C:\Users\username\Desktop\Test\*.lnk") do start "" "%%~v"

It will open every .lnk file in the folder.

A: You can use this:
for /r %%v in (*.lnk) do start %%v
Note:
Don't put spaces on shortcut filenames.


text:
Q: Server disk full, Mysql service can't start, how can i shrink the database? I'm currently having a major issue. VPS disk is full, mysql database grew unexpectedly, and can't buy more space from the hosting because it's already maxed out.
The mysql service can't start anymore because of storage space.
Is there any way I could execute queries on the database with the service off? But I guess it would require some third party tools, and the space on the server doesn't permit that. If I'm not mistaken, even if i delete some old data from the database, it won't shrink anyway.
I can't even download the entire database files on my computer and try to rebuild it there, because it's so huge I don't have any drive where it could fit.
What options I have now? Does anyone have any idea about what i could do next?

A: MySQL doesn't run as root, so you probably still have 'reserved' free space. You can reclaim that: tune2fs -m 0 /dev/whatever.
You didn't say what OS you have, but there is probably some space you can free up elsewhere. If you have Ubuntu, try apt clean. Remove log files from /var/log/*, etc.
If you still can install something, install ncdu and do ncdu -x / to give you an easy overview of what to delete.
Also, a trick I often do, is have a dummy file of a few hundred MBs somewhere, that can be removed if you run into this situation. That, and monitoring of course.
Once you do have space, you're going to have to run OPTIMIZE TABLE on the offending table. However, this will cause a recreate, so you need extra space for that. Also, it requires running with innodb_file_per_table, which is the default nowadays.


text:
Q: How to add JCheckBox dynamically to each row retrieved from MySQL database to JTable I have data from the database on my JTable. I want to add checkboxes to each row dynamically from the database. I will later use these checkboxes to delete rows checked  from the database. I know how to delete from the database, but how to add checkboxes from the database? Any one done this before please help. I am a Java enthusiast trying to learn it. A sample code could help me understand how to do this.
Code below is for updating my JTable:
public void UpdateTable() {

    try {

        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"
                + "employee_certificate", "root", "");

        String sql = "SELECT certificate.Number, staff.Emp_Id, staff.Emp_Name, "
                + "staff.Department,  certificate.Cert_Code, certificate.Cert_Name,\n"
                + "certificate.Vendor, certificate.Date_Taken, "
                + "certificate.Expiry_Date FROM staff LEFT JOIN certificate"
                + " ON staff.Emp_Id=certificate.Emp_Id ORDER BY staff.Emp_Name\n";

        PreparedStatement pstmt = con.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        jTable1.setModel(DbUtils.resultSetToTableModel(rs));
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}

A: Starting from this complete example, I made the changes below to get the following result. In particular,

*

*Row is given an attribute Boolean checked, replacing String name.

*The default renderer uses a check box when getColumnClass() returns Boolean.class for Row.checked.

*In the corresponding JDBC and SQL, the checked attribute is of type boolean.

$ diff Original.java WorkerTest.java
48c48
<         String name;
---
>         Boolean checked;
91c91
<                     return row.name;
---
>                     return row.checked;
105a106,116
>         @Override
>         public Class<?> getColumnClass(int colIndex) {
>             switch (colIndex) {
>                 case 0:
>                     return Integer.class;
>                 case 1:
>                     return Boolean.class;
>             }
>             return null;
>         }
>
114c125
<                         r.name = rs.getString(2);
---
>                         r.checked = rs.getBoolean(2);
138c149
<             st.execute("create table city(id integer, name varchar2)");
---
>             st.execute("create table city(id integer, checked boolean)");
143,144c154
<                 ps.setString(2, (char) ('A' + r.nextInt(26))
<                     + String.valueOf(r.nextInt(1_000_000)));
---
>                 ps.setBoolean(2, Boolean.valueOf(r.nextBoolean()));

A: The problem is DBUtils returns a complete TableModel.
The easiest way is to NOT use DBUtils and to load the data from the ResultSet into the TableModel yourself.
The code is not difficult and you can use the Table From Database Example found in Table From Database as the starting point.
The code just loads the data from the ResultSet into Vectors, so you can then manually add another column to contain Boolean data.
The (two) changes to the code would be something like:
//  Get column names

for (int i = 1; i <= columns; i++)
{
    columnNames.addElement( md.getColumnName(i) );
}

columnName.addElement( "Check Mark" ); // added

//  Get row data

while (rs.next())
{
    Vector<Object> row = new Vector<Object>(columns);

    for (int i = 1; i <= columns; i++)
    {
        row.addElement( rs.getObject(i) );
    }

    row.addElement( Boolean.FALSE ); // added
    data.addElement( row );
}


text:
Q: Как сгенерировать JSON на основании списка значений (list)? У меня есть список значений.
Вот его пример:
[[[0.0002700000000000001, 90.00026999999932],
  [0.0005400000000000066, 90.00026999999932],
  [0.0002700000000000001, 90.00053999999865],
  [0.0005400000000000066, 90.00053999999865]],
 [[0.0002700000000000001, 90.00053999999865],
  [0.0005400000000000066, 90.00053999999865],
  [0.0002700000000000001, 90.00080999999795],
  [0.0005400000000000066, 90.00080999999795]],
 [[0.0002700000000000001, 90.00080999999795],
  [0.0005400000000000066, 90.00080999999795],
  [0.0002700000000000001, 90.00107999999727],
  [0.0005400000000000066, 90.00107999999727]],
 [[0.0002700000000000001, 90.00107999999727],
  [0.0005400000000000066, 90.00107999999727],
  [0.0002700000000000001, 90.00134999999659],
  [0.0005400000000000066, 90.00134999999659]]]

Т. е. в общем списке, у меня есть списки из 4-элементов, в каждом из которых по 2 значения.
С этого списка я хочу автоматически сгенерировать вот такой JSON:
{
  "type": "Feature",
  "properties": {
    "area": 1
  },
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [0.0002700000000000001, 90.00026999999932],
        [0.0005400000000000066, 90.00026999999932],
        [0.0002700000000000001, 90.00053999999865],
        [0.0005400000000000066, 90.00053999999865]
      ]
    ]
  }
}

{
  "type": "Feature",
  "properties": {
    "area": 2
  },
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [0.0002700000000000001, 90.00053999999865],
        [0.0005400000000000066, 90.00053999999865],
        [0.0002700000000000001, 90.00080999999795],
        [0.0005400000000000066, 90.00080999999795]
      ]
    ]
  }
}

Как видите, каждый элемент списка - в новом блоке "coordinates"
Кроме того, поле "area" генерится автоматически на основании номера элемента в списке. Если элемент имеет номер 1 в списке, то "area" == 1, и т. д...
Как это сделать?
Спасибо

A: import json
list = [[[0.0002700000000000001, 90.00026999999932],
  [0.0005400000000000066, 90.00026999999932],
  [0.0002700000000000001, 90.00053999999865],
  [0.0005400000000000066, 90.00053999999865]],
 [[0.0002700000000000001, 90.00053999999865],
  [0.0005400000000000066, 90.00053999999865],
  [0.0002700000000000001, 90.00080999999795],
  [0.0005400000000000066, 90.00080999999795]],
 [[0.0002700000000000001, 90.00080999999795],
  [0.0005400000000000066, 90.00080999999795],
  [0.0002700000000000001, 90.00107999999727],
  [0.0005400000000000066, 90.00107999999727]],
 [[0.0002700000000000001, 90.00107999999727],
  [0.0005400000000000066, 90.00107999999727],
  [0.0002700000000000001, 90.00134999999659],
  [0.0005400000000000066, 90.00134999999659]]]

z = 0
for key in list:
    zc = z+1
    string = '{"type": "Feature", "properties": {"area": '+str(zc)+'}, "geometry": {"type": "Polygon", "coordinates": [[['+str(list[z][0])+'],['+str(list[z][1])+'],['+str(list[z][2])+'],['+str(list[z][3])+']]]}}'
    z += 1
    json_str = json.dumps(string)
    print(json_str)

A: Пусть исходный список значений находится в переменной coordinates. Тогда решение для Вас:
result = [
    {
        "type": "Feature",
        "properties": {
            "area": index
        },
        "geometry": {
            "type": "Polygon",
            "coordinates": [coords]
        }
    }
    for index, coords in enumerate(coordinates, start=1)
]


text:
Q: minimize a matrix valued function with two unknowns Suppose I want to solve the following problem:
\begin{align*}
min_{P, V}\  \log(|PVP^T|) + \text{tr}((PVP^T)^{-1}PQP^T)
\end{align*}
such that $PS = I$, where $S$ is a known matrix of full column rank and $Q$ is a positive definite matrix.
However, I don't really want to precisely estimate $V$, it is sufficient to estimate $PVP^T$.
Can I solve the above problem letting $R = PVP^T$ so that the objective function becomes
$$log|R| + tr(R^{-1}PQP^T)$$
which is convex.
This leads $R = PQP^T$. Then plugging this solution back into the objective function, can I solve for $P$?
If so how can I ensure that the minimum has reached?


text:
Q: How do you hide carriage return and space markings in Xcode 12.1? I'm new to XCode (12). My source code editor is showing line numbers, periods marking every space and carriage returns, all displayed in light grey. I can switch off the line numbers in Preferences > TextEditing > Display. Why am I seeing markings for periods and CRs though? How do you get rid of them?

A: Choose Editor > Invisibles to toggle showing and hiding the invisible characters. You must select a source code file for the Invisibles menu item to appear in the Editor menu.


text:
Q: Botão para inserir registos na BD Estou a realizar um projeto para a minha PAP que consiste na criação de uma Base de Dados para uma empresa.
No entanto, decidi colocar um botão para adicionar registos e quando clico para adicionar, aparece o seguinte erro:

Falha ao converter o valor do parâmetro de Bitmap para Byte[].

 SqlCommand command = new SqlCommand("insert into Utilizador(IDuser, Nome, Localidade, DataDeNascimento, Idade, Email, Login, Senha,
 Telefone, TelefoneEE, Perfil, Imagem) values (@IDuser, @Nome, @Localidade, @DatadeNascimento, @Idade, @Email, @Login, @Senha, @Telefone, @TelefoneEE, @Perfil, @Imagem", sql);
              command.Parameters.Add("@IDuser", SqlDbType.VarChar).Value = iDuserTextBox.Text;
              command.Parameters.Add("@Nome", SqlDbType.VarChar).Value = nomeTextBox.Text;
              command.Parameters.Add("@Localidade", SqlDbType.VarChar).Value = localidadeTextBox.Text;
              command.Parameters.Add("@DataDeNascimento", SqlDbType.DateTime).Value = dataDeNascimentoDateTimePicker.Value;
              command.Parameters.Add("@Idade", SqlDbType.VarChar).Value = idadeTextBox.Text;
              command.Parameters.Add("@Email", SqlDbType.VarChar).Value = emailTextBox.Text;
              command.Parameters.Add("@Login", SqlDbType.VarChar).Value = loginTextBox.Text;
              command.Parameters.Add("@Senha", SqlDbType.VarChar).Value = senhaTextBox.Text;
              command.Parameters.Add("@Telefone", SqlDbType.Char).Value = telefoneTextBox.Text;
              command.Parameters.Add("@TelefoneEE", SqlDbType.Char).Value = telefoneEETextBox.Text;
              command.Parameters.Add("@Imagem", SqlDbType.Image).Value = imagemPictureBox.Image;
              command.Parameters.Add("@Perfil", SqlDbType.VarChar).Value = perfilTextBox.Text;


text:
Q: Multi-line y label in plot Is there a way to create multi-line labels for the y axis in an R plot?
I have tried adding a \n where the newline should be, but then the first line of the label gets clipped:
l <- 10
plot(0:l, (0:l), type='l',
     yaxt='n',
     xlab='Index',
     ylab='Cumulative sum\nof the sorted weights')

This happens both with the tikzDevice and inside RStudio. Also, I tried some of the par() options with no luck. How to do it properly?
(The oversized uper margin bothers me, too...)

A: You need to set the margins using mar or mgp:
l <- 10
op <- par(mar=c(5, 6, 4, 2) + 0.1)
plot(0:l, (0:l), type='l',
     yaxt='n',
     xlab='Index',
     ylab='Cumulative sum\nof the sorted weights')
par(op)

A: Like @smillig suggested, you do it with par, changing the mar or mgp parameters.
But you have to call par before you call plot.


text:
Q: Send multiple emails simultaneously I have a WebApi project with a list of scheduled emails using Quartz.Net (embedded, not Windows service) which scheduled daily at 9 am. I want it to be simultaneously. Therefore I added QueueBackgroundWorkItem.
public override async Task ExecuteJob(IJobExecutionContext context)
{
    foreach (var user in users)
    {
        HostingEnvironment.QueueBackgroundWorkItem(ct =>  EmailHelper.SendEmailAsync("reminder",user.email));
    }
}

However, the Job ran, but it doesn't send an email if I enabled QueueBackgroundWorkItem.
Any alternative way to send email simultaneously?

A: Assuming SendEmailAsync returns a Task derived result, use Task.WhenAll to run all the tasks together.
public override Task ExecuteJob(IJobExecutionContext context) {
    var tasks = users.Select(user => EmailHelper.SendEmailAsync("reminder", user.email));
    return Task.WhenAll(tasks);
}

Since nothing is actually being awaited in the function there is no need to tag it with async. Just return the task.


text:
Q: Presto-Glue-EMR integration: presto-cli giving NullPointerException I am trying to connect my Glue catalog to Presto and Hive in EMR. While running the queries in presto-cli, I am getting NullPointerException whereas the same query succeeds in hive-cli.
Started the cli like below
presto-cli --catalog hive

Exception on executing a query:
Query 20180814_174636_00003_iika5 failed: java.lang.NullPointerException: parameters is null

EMR Configuration looks like this:
[
    {
        "classification": "presto-connector-hive",
        "properties": {
            "hive.metastore": "glue"
        },
        "configurations": []
    },
    {
        "classification": "hive-site",
        "properties": {
            "hive.metastore.client.factory.class": "com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory"
        },
        "configurations": []
    }
]

EMR version: 5.16.0
Presto version: 0.203
Reference Doc: https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-presto-glue.html
Debug logs
Query 20180816_060942_00001_m9i52 failed: java.lang.NullPointerException: parameters is null
com.google.common.util.concurrent.UncheckedExecutionException: java.lang.NullPointerException: parameters is null
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2052)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3943)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3967)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4952)
    at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4958)
    at com.facebook.presto.hive.metastore.CachingHiveMetastore.get(CachingHiveMetastore.java:207)
    at com.facebook.presto.hive.metastore.CachingHiveMetastore.getPartitionNamesByParts(CachingHiveMetastore.java:499)
    at com.facebook.presto.hive.metastore.SemiTransactionalHiveMetastore.doGetPartitionNames(SemiTransactionalHiveMetastore.java:467)
    at com.facebook.presto.hive.metastore.SemiTransactionalHiveMetastore.getPartitionNamesByParts(SemiTransactionalHiveMetastore.java:445)
    at com.facebook.presto.hive.HivePartitionManager.getFilteredPartitionNames(HivePartitionManager.java:284)
    at com.facebook.presto.hive.HivePartitionManager.getPartitions(HivePartitionManager.java:146)
    at com.facebook.presto.hive.HiveMetadata.getTableLayouts(HiveMetadata.java:1305)
    at com.facebook.presto.spi.connector.classloader.ClassLoaderSafeConnectorMetadata.getTableLayouts(ClassLoaderSafeConnectorMetadata.java:73)
    at com.facebook.presto.metadata.MetadataManager.getLayouts(MetadataManager.java:346)
    at com.facebook.presto.sql.planner.iterative.rule.PickTableLayout.planTableScan(PickTableLayout.java:203)
    at com.facebook.presto.sql.planner.iterative.rule.PickTableLayout.access$200(PickTableLayout.java:61)
    at com.facebook.presto.sql.planner.iterative.rule.PickTableLayout$PickTableLayoutWithoutPredicate.apply(PickTableLayout.java:186)
    at com.facebook.presto.sql.planner.iterative.rule.PickTableLayout$PickTableLayoutWithoutPredicate.apply(PickTableLayout.java:153)
    at com.facebook.presto.sql.planner.iterative.IterativeOptimizer.transform(IterativeOptimizer.java:168)
    at com.facebook.presto.sql.planner.iterative.IterativeOptimizer.exploreNode(IterativeOptimizer.java:141)
    at com.facebook.presto.sql.planner.iterative.IterativeOptimizer.exploreGroup(IterativeOptimizer.java:104)
    at com.facebook.presto.sql.planner.iterative.IterativeOptimizer.exploreChildren(IterativeOptimizer.java:193)
    at com.facebook.presto.sql.planner.iterative.IterativeOptimizer.exploreGroup(IterativeOptimizer.java:106)
    at com.facebook.presto.sql.planner.iterative.IterativeOptimizer.exploreChildren(IterativeOptimizer.java:193)
    at com.facebook.presto.sql.planner.iterative.IterativeOptimizer.exploreGroup(IterativeOptimizer.java:106)
    at com.facebook.presto.sql.planner.iterative.IterativeOptimizer.optimize(IterativeOptimizer.java:95)
    at com.facebook.presto.sql.planner.LogicalPlanner.plan(LogicalPlanner.java:140)
    at com.facebook.presto.sql.planner.LogicalPlanner.plan(LogicalPlanner.java:129)
    at com.facebook.presto.execution.SqlQueryExecution.doAnalyzeQuery(SqlQueryExecution.java:327)
    at com.facebook.presto.execution.SqlQueryExecution.analyzeQuery(SqlQueryExecution.java:312)
    at com.facebook.presto.execution.SqlQueryExecution.start(SqlQueryExecution.java:268)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException: parameters is null
    at java.util.Objects.requireNonNull(Objects.java:228)
    at com.facebook.presto.hive.metastore.Partition.<init>(Partition.java:54)
    at com.facebook.presto.hive.metastore.Partition$Builder.build(Partition.java:180)
    at com.facebook.presto.hive.metastore.glue.converter.GlueToPrestoConverter.convertPartition(GlueToPrestoConverter.java:141)
    at com.facebook.presto.hive.metastore.glue.GlueHiveMetastore.lambda$getPartitions$8(GlueHiveMetastore.java:558)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at com.facebook.presto.hive.metastore.glue.GlueHiveMetastore.getPartitions(GlueHiveMetastore.java:558)
    at com.facebook.presto.hive.metastore.glue.GlueHiveMetastore.getPartitionNamesByParts(GlueHiveMetastore.java:541)
    at com.facebook.presto.hive.metastore.CachingHiveMetastore.loadPartitionNamesByParts(CachingHiveMetastore.java:504)
    at com.google.common.cache.CacheLoader$FunctionToCacheLoader.load(CacheLoader.java:165)
    at com.google.common.cache.CacheLoader$1.load(CacheLoader.java:188)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3524)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2273)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2156)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2046)
    ... 33 more

A: Seems like presto 0.203 has this bug, I faced it too, I switched to a newer version and it worked.
In the time I am writing this answer, EMR 5.17 is released and it has presto 0.206 which has this problem resolved.


text:
Q: How to read data from serial-connected Bluetooth headphones? My Bluetooth headphones' (connected using a USB dongle) play/pause button doesn't work with Windows 10 (the volume changers work just fine), so I tried to remap the key, it gets, to the media play/pause button.
First I tried with AHKHID, and used the examples to find out what HID device is connected. That just showed the keyboard and mouse. So I looked more into Bluetooth devices and wrote a program to get the available Bluetooth services running on the headphones. The 3 services it could find was SPP, HSP and HFP. From these, SPP looked like the most promising, as Wikipedia states

It emulates a serial cable to provide a simple substitute for existing RS-232, including the familiar control signals. It is the basis for DUN, FAX, HSP and AVRCP.

I knew that AVRCP should be the one the controls are sent with, so this must be the one the play/pause signal is coming from. I looked at the serial COM ports available on my computer and found that it uses COM3 for incoming and COM4 for outgoing communication with the headphones.
Now this is where I got stuck. I tried to connect to the SPP service running on the headphones programatically, which worked (didn't throw any errors), but the input data event didn't fire and the stream read timed out.
I also tried to inspect the serial data with Serial Port Monitor (the trial version), but it doesn't show anything except when I click open or close, it shows a bunch of setup messages.
What can the problem be? Is Windows using it and so it prevents other programs from accessing it (or empties the stream before others could see it)? Or am I doing something completely wrong?
Any ideas?
Edit:
Meanwhile I installed the native Spotify app for Windows and it detects the button presses just fine. As this was my main goal with this research, I won't look more into it, but it would be interesting to know where it gets the button presses from and why it doesn't work for other apps.


text:
Q: Laplacian on the sphere of radius $r$ I was trying as exercise to derive the Laplacian in spherical coordinates using riemannian geometry tools.

Definition If $\mathcal{M}$ is a smooth manifold of dimension $n$ and $\left\{E_1,\ldots,E_n \right\}$ is an orthonormal frame then we define for $f : \mathcal{M} \to \mathbb{R}$
$$
\text{grad} f = \sum_{i=1}^n E_i(f)E_i
$$
and
$$
\Delta f = \sum_{i=1}^n E_i(E_i(f)).
$$

Let
$$
\mathbb{S}^2(r) = \left\{ (x,y,z) \in  \mathbb{R}^3 :
\left\{
\begin{array}{l}
x = r\sin \phi \cos \theta \\
y = r\sin \phi \sin \theta \\
z = r\cos\phi
\end{array}
\right.
\;\;,0\leq \theta \leq 2\pi, 0 \leq \phi \leq \pi
\right\}
$$
So there's single chart for the sphere, name this $\varphi$ .
If I did the calculation right I have
$$
\varphi_{*,(\theta,\phi)} =
\begin{pmatrix}
-r\sin\phi \sin\theta & r\cos\phi \cos\theta \\
r\sin\phi \cos\theta & r\cos\phi \sin\theta \\
0 & -r\sin\phi
\end{pmatrix}
$$
To define an o.n. reference frame I did the following calculations
$$
\begin{array}{l}
\left\langle \frac{\partial}{\partial \theta}, \frac{\partial}{\partial \phi} \right\rangle_{\mathbb{S}^2(r),(\theta,\phi)} = \left\langle \varphi_{*,(\theta,\phi)}\frac{\partial}{\partial \theta}, \varphi_{*,(\theta,\phi)} \frac{\partial}{\partial \phi} \right\rangle_{\mathbb{R}^3,\varphi(\theta,\phi)} = 0\\
\left\langle \frac{\partial}{\partial \theta}, \frac{\partial}{\partial \theta} \right\rangle_{\mathbb{S}^2(r),(\theta,\phi)} = \left\langle \varphi_{*,(\theta,\phi)} \frac{\partial}{\partial \theta},\varphi_{*,(\theta,\phi)} \frac{\partial}{\partial \theta} \right\rangle_{\mathbb{R}^3,\varphi(\theta,\phi)} = r^2 \sin \phi \\
\left\langle \frac{\partial}{\partial \phi}, \frac{\partial}{\partial \phi} \right\rangle_{\mathbb{S}^2(r),(\theta,\phi)} = \left\langle \varphi_{*,(\theta,\phi)} \frac{\partial}{\partial \phi}, \varphi_{*,(\theta,\phi)} \frac{\partial}{\partial \phi} \right\rangle_{\mathbb{R}^3,\varphi(\theta,\phi)} = r^2
\end{array}
$$
We have then
$$
T_{(\theta,\phi)}\mathbb{S}^2(r) = \text{span} \left\{ \frac{1}{r\sin\phi} \frac{\partial}{\partial \theta}, \frac{1}{r} \frac{\partial}{\partial \phi} \right\}
$$
Which is an orthonormal frame for every $(\theta,\phi)$.
This gives me the following expression of the laplacian
$$
\Delta_{\mathbb{S}^2(r)}f = \left( \frac{1}{r^2 \sin^2\phi} \frac{\partial^2}{\partial \theta^2} + \frac{1}{r^2} \frac{\partial^2}{\partial \phi^2} \right)f
$$
According to few references I've seen around the expression is wrong. I did the calculation few times but I cannot spot the error.
Can you maybe tell me what I am doing wrong? I am assuming the metric on $\mathbb{S}^2(r)$ is the one induced by $\mathbb{R}^3$.

A: Your definition for $\text{grad}(f)$ is fine, however, the expression you gave for $\Delta f$ only works if you fix a point $p\in M$ and consider a 'geodesic frame at $p$', i.e an orthonormal frame $\{E_1,\dots, E_n\}$ defined in an open neighborhood of $p$ such that for all $i,j\in\{1,\dots, n\}$, $(\nabla_{E_i}E_j)(p)=0$. The orthonormal frame you gave doesn't satisfy the 'geodesic' condition, which is why you're not getting the right result.
The 'correct' definition for the Laplacian is as the divergence of the gradient of $f$, where the divergence of a vector field $X$ is defined as $\text{div}(X)(p):=\text{trace}\left(v_p\mapsto\nabla_{v_p}X\right)$, the trace of a linear mapping $T_pM\to T_pM$. Let us now derive the formula the divergence in terms of a geodesic frame at $p$. Say $X=\sum_{j=1}^nX^jE_j$, then
\begin{align}
(\text{div }X)(p)&=\text{trace}(v_p\mapsto\nabla_{v_p}X)\\
&=\sum_{i=1}^n\left\langle \nabla_{E_i(p)}X, E_i(p)\right\rangle\\
&=\sum_{i,j=1}^n \left\langle \nabla_{E_i(p)}(X^jE_j), E_i(p)\right\rangle\\
&=\sum_{i,j=1}^n \left\langle (E_i(X^j))(p)\cdot E_j(p)+ X^j(p)\nabla_{E_i(p)}E_j, E_i(p)\right\rangle\\
&=\sum_{i=1}^n(E_i(X^i))(p),
\end{align}
where we first used the product rule on $\nabla_{E_i(p)}(X^jE_j)$, and then used that we have an orthonormal and geodesic frame at $p$. This is the general formula for the divergence of any vector field. If you specialize to $X=\text{grad}(f)$, then $X^i=E_i(f)$, so you recover your stated formula for the Laplacian.
Now, since you're not actually using a geodesic frame in your computation, you won't get the right answer. An alternative approach to computing the Laplacian is to use the Voss-Weyl formula for the divergence of any vector field applied to the gradient:
\begin{align}
\Delta f&=\frac{1}{\sqrt{|g|}}\frac{\partial}{\partial x^{\mu}}\left(\sqrt{|g|}g^{\mu\nu}\frac{\partial f}{\partial x^{\nu}}\right).
\end{align}
You already worked out the metric components $g_{\mu\nu}$ in your post, so carrying out this summation should be trivial.


text:
Q: Check if all values in my array equals specific text I'm new to javascript. I created the following code to check if a specific value exists in an array and then show text based on whether the value exists or not:
// Get my div
ar mydiv = document.querySelector("#mydiv");

// Create Array
var mylist =  Array.from(document.getElementsByClassName('myitem'), e => e.innerText)

// Check if value exist
myanswer = mylist.includes("None");

// Output Text
if (myanswer == true) {
    mydiv.textContent = "True in list";
} else {
    mydiv.textContent = "False in list";
}

It works well, but now I want to change it so that it checks weather ALL values in my array equals "None".
I changed the following line:
myanswer = mylist.includes("None");

To be this instead:
myanswer = mylist.every.equals("None");

This doesn't work though, so how is the best way to go about doing this?

A: In your case, MyList.every is a function not a single element.
What you want instead is checking if every element is equals to None.
Then The good way of doing it is the following :
myList.every(elem => elem === 'None')

This will return true if all elems are equals to None, false otherwise

Here is a small example with an array of string where you want to check if every item is 'None'

const arr1 = ['None','None','None','None','Not None']
const arr2 = ['None','None','None','None','None']

console.log(arr1.every(elem => elem === 'None'))
console.log(arr2.every(elem => elem === 'None'))


text:
Q: Google Cloud Storage: Getting object from hiarchial / sub-folder structure I have created hierarchical structure for managing file in bucket. Planning to create folder for each month i.e. dec-2017. There will be more than 10k pdf files in each folder.
Written C# code for getting objects from bucket. This code is working fine for accessing files that are on root of bucket. I am having issues with accessing files in folder i.e. my-bucket/dec-2017/test.pdf is not accessed using code.
Refer my bucket structure here
I am using following code, Can anyone don this before?
if (_storageService == null)
{
    _storageService = CreateStorageClient();
}
ObjectsResource.GetRequest downloadRequest = null;
//string objectName = "dec-2017%2Ftest.pdf";
string objectName = "dec-2017/test.pdf";

downloadRequest = new ObjectsResource.GetRequest(_storageService, bucketName, objectName);

MemoryStream stream = new MemoryStream();
downloadRequest.Download(stream);
bytes = stream.ToArray();

A: Please check below sample code -
        using Google.Apis.Auth.OAuth2;
        using Google.Cloud.Storage.V1;

        string file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Test.csv");
        File.WriteAllText(file, "test");

        GoogleCredential credential = null;
        BucketConnector bucketConnector = new BucketConnector();
        credential = bucketConnector.ConnectStream();
        var storageClient = StorageClient.Create(credential);

        string folderPath = ConfigurationParameters.FOLDER_NAME_IN_BUCKET;
        using (FileStream file = File.OpenRead(localPath))
        {
            objectName = folderPath + Path.GetFileName(localPath);
            storage.UploadObject(bucketName, objectName, null, file);
        }


text:
Q: The position of "due to" Sometimes I don't know the natural position of some phrases because of the mother language inference.
Consider:

For example, due to their low vapor pressure, these compounds are appropriate replacement for volatile organic compounds (VOCs).

In the sentence above, I put "due to" in the front, because I feel if I don't say it there, the reader won't understand why they are appropriate in the rest of the sentence. However, maybe it is more natural to say:

For example these compounds are appropriate replacement for volatile organic compounds (VOCs) due to their low vapor pressure.

Which sentence do you think is more normal in English?
Another example is:

*

*The application of room-temperature ionic liquids (RTILs) due to their unique properties in a variety of processes, such as solvent extraction, is increasing

*The application of room-temperature ionic liquids (RTILs) is increasing due to their unique properties in a variety of processes, such as solvent extraction.

A: A lot of this depends on what "sounds good", or what flows well.
In your first two examples, both sound fairly natural, although the first one seems to put more emphasis on the reason the compounds are an appropriate replacement. That's just because you've placed that phrase up front.
Your RTIL example sentences have more clauses in them, and so they can become awkward much more quickly. So you have to be a little more careful about the ordering of the clauses to make them sound natural.
The second RTIL example sounds much more natural. I think it's because it's of the form "(something) is (doing something) due to (a reason)". In the first sentence you're saying "(something), due to (a reason), is (doing something)".
In english the verb rarely comes at the end of a complex sentence like this, and it sounds more natural if you keep the subject (the application of RTILs) next to the thing it is doing (is increasing), though I don't think that's a strict rule. It just flows better in most cases.

Also I'd like to mention that in

these compounds are appropriate replacement

There should be an article before "appropriate"

these compounds are an appropriate replacement.

I'm guessing (apologies if I'm wrong and it was just a typo) there is some confusion between

These compounds are appropriate

and

These compounds are an appropriate replacement

In the first example, the word "appropriate" is an adjective referring to the compounds, like

these flowers are beautiful

In the second example, "appropriate" is still an adjective, but it is attached to "replacement". Since it is modifying the noun "replacement", "appropriate" gets bundled up with that noun and you go from

a replacement

to

an appropriate replacement

That is, it remains a noun, so it should have an article in front of it. From

These flowers are beautiful (modifies flower)

to

These flowers are a beautiful gift (modifies the noun gift)


text:
Q: Why to use a Service on ZF2? I'm trying to understand some principles of the ZendFramework 2, and I want to know why to inject services on the ZF2 module.config.php if I can load instance a object using composer autoloader. The same thing for zend factories, why to use this if I can easily implement a Factory class and call it in a controller?

A: To be clear up front - the ServiceLocator is not a must use way for creating objects. You still can create objects directly, and in quite a few cases this is a perfectly valid approach.
With that being said, there are a few reasons why you want to use the ServiceLocator for some objects. Unfortunately the Wikipedia Page on this doesn't help much with understanding the reasons to use a service locator. I found the description and examples here much more useful.
For the remainder of this, I'll use the terms class and service interchangeable. I'll name the class/object requiring a service Consumer, the factory responsible for creating a service a factory.
There is one very important fact to know about service managers. The service name does not need to be a class name. It can be any string (e.g. the services' name).
The major reasons why you want to use a service locator are:

*

*Use the same instance of a service and many places (shared services)

*Abstract the means of service constructions from the consumer (is it created by a factory or instantiated directly)

*Decouple modules from each other

*Create abstract services (identified by any string), and let others decide on the concrete implementation of this service

*Extend service creation using delegators

Re-use services
This is probably the easiest to see. Typically you have a service and want the same instance to be used across your application. Use-cases for this could be anything from a Configuration service to Caching Service.
We sure could use a Singleton for making sure that only one instance is created globally - and this would work as well. But this doesn't provide the benefits of the other arguments following.
In Zf2, all services are shared by default. So each time you request a service by name, you will get the same instance. This can be turned of on a per-service level (that's the shared config key for in the service_manager configuration).
Abstract means of creation
Ideally, the consumer should not need to know how a required service is to be created. This makes it more decoupled from the required service. All it needs to know, is to say I require an instance of this service.
Using a service manager, you can achieve this: you ask the service manager to fetch a specific service, But you don't care how the service manager actually creates this. It could be that the service manager instantiates it directly. It could be a factory. The consumer doesn't care - all it only cares about the result, an instance of that service.
The benefit of doing so is that you can replace the mean of creating that service transparently and don't have to update the consumer code to the new way of creating that service.
Decoupling modules
Hiding the way of how a service is created leads to decoupling modules. Let's assume you have two modules Cache and User. The user module requires a Cache Service from the Cache module. Instead of having to rely on the Cache Module  and implementation directly, you hide that fact by a service named cache. The user module doesn't care at all how the Cache module creates that service. In fact we could even replace the Cache module with another module AdvancedCache providing the same service, without having to update the User module. The User module isn't tied to a particular module - only the the existence of a service named cache.
Abstract service names
In the previous example, I already introduced this concept. Each service has a global name - a simple string. In many cases that is the class name, but we are not limited to this.
To stick the the previous example of a cache service: in here we didn't specify which type of cache the User Module actually wants - it doesn't care. It could be an array (in-memory) cache, a file cache, or memcache cache.
In some other place we decide which cache we want to use globally and assign that concrete implementation to the name of cache. All modules requiring that cache service now automatically receive that implementation without needing to be updated.
In Zf2, this is used quite extensively. Take the Request Service for example. In many cases this is an instance of the Http\Request. But when using the CLI, this would be an Console\Request instead. But when requesting the Request service, we literally don't care about which one re receive, as long as they behave the same.
Another example for this would be the Renderer. Depending on the environment we want to render the output for, we receive a different implementation (HTML/Json/Console usage). But our consumer doesn't need to know which concrete implementation we are rendering for/.
Delegators
Delegators can be used to extend a factory. I'll leave this out of scope for now though as this is a more advanced use-case. So much be said, you can extend/proxy service creations upon creation time.

A: In completion of @Fge answer iI will show you an example I experimented myself on how service manager can be useful, and when it's not.
I make a dynamic form wich on a few elements I had to add some filters and some validators.
I show you my custom service's method that doi this job for me :
public function setValidators($form, $name, $validator, $nameFieldset)
{
    $optionsSpace = [
        'translator' => $this->translator,
        'type' => NotEmpty::SPACE
    ];
    $optionsString = [
        'translator' => $this->translator,
        'type' => NotEmpty::STRING
    ];
    $optionsDigits = [
        'translator' => $this->translator,
    ];
    $form->getInputFilter()->get('items')
        ->get($nameFieldset)
        ->get($name)
        ->setRequired(true)
        ->getValidatorChain()
        ->attach($validator, true, 1)
        ->attach(new NotEmpty($optionsSpace), true, 2)
        ->attach(new NotEmpty($optionsString), true, 2)
        ->attach(new Digits($optionsDigits), true, 2);
    return $form;
}

You can see that I use some arrays, and some Zend\Validators.
You also see that I use  $this->translator on each options Array that I pass to those validators. Why I pass the translator ? Let's have a look to the validator :
class NotEmpty extends AbstractValidator

And the abstract Validator
abstract class AbstractValidator implements
    Translator\TranslatorAwareInterface,
    ValidatorInterface

If you use the service manager the TranslatorAwareInterface will be instanciated by an initializer. Wich, if you declared the new validator directly in you service, will not be the case, so you have to set it in your options.


text:
Q: C++: scope of for loop? #include <iostream>
using namespace std;

int main() {
    int i;
    for(i=0; i <= 11; i+=3)
        cout << i;
    cout << endl << i << endl;
}

output is: 0 3 6 and 9 and then once it exits the loop its 12.
The addresses of i inside the loop and out appear the same
What I need to know is: Is the i inside the for loop the same as the i that was initialized outside the for loop because the variable i was first initialized before the for loops i was ever created?

A: It's de same 'i' var
#include <iostream>
using namespace std;

int i = 0;

int main() {
    int i;
    for(i=0; i <= 11; i+=3)
        cout << i;
    cout << endl << i << endl;
    cout << endl << ::i << endl;
}

i is 12
::i is 0

A: In order to create a new object (variable) in C++ (as well as in C) you have to explicitly define it. In your program you have one and only one variable definition - int i;. That immediately means that there's one and only one variable i there. There's no chance for any other i, regardless of any "scopes of for loop" or anything else.

A: Yes, the i inside the loop is the same as the i outside of the loop because you've only declared it once.
If for some reason you want it to be different (which I highly recommend against, you should choose different names for different variables) you could redeclare the i in the for loop:
for (int i = 0; i ...

A: There is only one 'i' variable. You're just assigning a value in the foor loop.

A: There is only one variable extant here - and yes, the i inside the loop is the same as the one you output after exiting the loop.  However the variable was only initialized as part of the loop, not before.

A: A for-loop of the form:
for (init condition; expression) statement

Is exactly equivalent to:
{
    init
    while (condition)
    {
        statement
        expression;
    }
}

So with your code:
    int i;
    {
        i=0;
        while (i <= 11)
        {
            cout << i;
            i += 3;
        }
    }
    cout << endl << i << endl;
}

Can you tell now? Andrey puts it best: if you didn't define it, it doesn't exist.


text:
Q: Show Results on View Im triyng to make some calculation on my View, but i cant show the result out of my @{} block
I have this table.

                CODIGO
                NOME
                PRECO
                QUANTIDADE

            @if (Model != null)
            {
                double sum = 0;
                for (int i = 0; i < Model.Item2.Count; i++)
                {

                        @using (Html.BeginForm("AddProduct", "Sale", FormMethod.Post))
                        {

                                @Html.DisplayFor(modelItem => Model.Item2[i].idProduct)

                            @Html.DisplayFor(model => Model.Item2[i].nameProduct)

R$@Html.DisplayFor(model => Model.Item2[i].pricesaleProduct)

                            @Html.DisplayFor(model => Model.Item2[i].quantityProduct)

                                <input type="submit" class="btn btn-danger" value="Deletar">

                            sum += Model.Item2[i].pricesaleProduct * Model.Item2[i].quantityProduct;
                        }

                }
            }

Total Value: @sum

I want to show "sum" out of my table, but trying several variations and a get error!
How can i make it?

A: You have declared sum inside if(){} block and hence you're not able to access it. Move it outside like this and it'll work
 double sum = 0;

 @if (Model != null)
 {

      ............
      ............
 }


text:
Q: ($object_or_class) must be an object or a valid class name after updating to 2.4.4 Magento 2.4.4
I updated from 2.3.3 to 2.4.4 and now I am getting the following error when the compilation is running:
MiBget_class_methods(): Argument #1 ($object_or_class) must be an object or a valid class name, string given#0 /vendor/magento/framework/Interception/Definition/Runtime.php(44): get_class_methods('PPBraintreeApplePayIsActivePlugin')

Any idea how to solve this? It seems to be related to Braintree?
Thanks!


text:
Q: rails deletes first 0 from zip code input in form I have a form.  One of the fields is zip code.  If I fill out the form, here are the params:
 Parameters: {"utf8"=>"✓", "authenticity_token"=>"fasdafdsafdsdsa/MKI/RGfds3=",
              "profile"=>{"title"=>"profile title", "zip_code"=>"02155"}}

As you can see, the zip code is still in tact.
I have a custom zip code validation:
VALID_ZIP_CODE_REGEX= /\A[0-9]{5}(-[0-9]{4})?\z/ #Does not work for +4
validates :zip_code, format: { :with => VALID_ZIP_CODE_REGEX },
   allow_blank: true, unless: 'dont_do_this?'

Here is the beginning of the method dont_do_this?
def dont_do_this
     puts 'self: ' + self.inspect.to_s
end

and here is the output:
self: #<Profile id: 7, created_at: "2014-05-06 16:50:14", updated_at: "2014-08-21 17:43:35",
         zip_code: 2155>

For some reason, the first zero of the zip code is stripped off.  I can't figure out why.  Does anyone know?

A: It looks like you are saving ZIP codes as integers in the database. They should be stored as strings (or from the database's point of view, VARCHARS).


text:
Q: is there a clear form field for flask?  submit = SubmitField("Submit")

the field above submits all information from a form into a DB. is there any way i can have something like a clearfield in flask whereby it clears any form input when clicked?

A: I am not sure Flask included anything like this, try making another button that redirects to the same page to get a fresh state.


text:
Q: Cannot shrink btrfs filesystem although there is still data and metadata space left : ERROR: unable to resize '/home': No space left on device I cannot shrink btrfs filesystem although there is still data and metadata space left :
$ sudo btrfs filesystem resize -11G /home;echo $?
Resize '/home' of '-11G'
ERROR: unable to resize '/home': No space left on device
1

Here are some btrfs filesystem info about /home :
$ sudo btrfs filesystem df /home | column -t
Data,           single:  total=92.01GiB,   used=80.68GiB
System,         DUP:     total=8.00MiB,    used=16.00KiB
System,         single:  total=4.00MiB,    used=0.00B
Metadata,       DUP:     total=1.00GiB,    used=631.41MiB
Metadata,       single:  total=8.00MiB,    used=0.00B
GlobalReserve,  single:  total=224.00MiB,  used=0.00B
$ sudo btrfs filesystem show /home
Label: none  uuid: c7ee56a8-ef45-46c8-86d1-13879201a1e7
    Total devices 1 FS bytes used 81.30GiB
    devid    1 size 100.00GiB used 94.04GiB path /dev/mapper/home_VG-home

$ sudo btrfs filesystem usage -T /home
Overall:
    Device size:         100.00GiB
    Device allocated:         94.04GiB
    Device unallocated:        5.96GiB
    Device missing:          0.00B
    Used:             81.91GiB
    Free (estimated):         17.29GiB  (min: 14.31GiB)
    Data ratio:               1.00
    Metadata ratio:           1.99
    Global reserve:      224.00MiB  (used: 0.00B)

             Data     Metadata Metadata  System  System
Id Path      single   single   DUP       single  DUP      Unallocated
-- --------- -------- -------- --------- ------- -------- -----------
 1 /dev/dm-0 92.01GiB  8.00MiB   2.00GiB 4.00MiB 16.00MiB     5.96GiB
-- --------- -------- -------- --------- ------- -------- -----------
   Total     92.01GiB  8.00MiB   1.00GiB 4.00MiB  8.00MiB     5.96GiB
   Used      80.68GiB    0.00B 631.41MiB   0.00B 16.00KiB

and here the output of dmesg :
$ dmesg | tail -11
[44202.411949] BTRFS info (device dm-0): new size for /dev/dm-0 is 97706311680
[44202.412156] BTRFS info (device dm-0): relocating block group 120288444416 flags 1
[44208.119721] BTRFS info (device dm-0): relocating block group 119214702592 flags 1
[44211.611669] BTRFS info (device dm-0): relocating block group 118140960768 flags 1
[44212.495603] BTRFS info (device dm-0): relocating block group 117067218944 flags 1
[44213.006830] BTRFS info (device dm-0): relocating block group 95592382464 flags 1
[44216.613870] BTRFS info (device dm-0): relocating block group 120288444416 flags 1
[44222.780073] BTRFS info (device dm-0): relocating block group 119214702592 flags 1
[44225.843279] BTRFS info (device dm-0): relocating block group 118140960768 flags 1
[44226.575236] BTRFS info (device dm-0): relocating block group 117067218944 flags 1
[44226.930918] BTRFS info (device dm-0): relocating block group 95592382464 flags 1

EDIT1 : The btrfs balance failed :
$ sudo btrfs balance start /home
ERROR: error during balancing '/home': No space left on device
There may be more info in syslog - try dmesg | tail

There nothing in dmesg | tail about it.
EDIT2 : I had to do the following to be able to start the btrfs balance :
$ sudo btrfs balance start -musage=0 -dusage=0 -v /home
Dumping filters: flags 0x7, state 0x0, force is off
  METADATA (flags 0x2): balancing, usage=0
  SYSTEM (flags 0x2): balancing, usage=0
  DATA (flags 0x2): balancing, usage=0
Done, had to relocate 0 out of 95 chunks

EDIT3 : The btrfs balance has ran for 68 minutes and then failed :
$ time sudo btrfs balance start -v /home
Dumping filters: flags 0x7, state 0x0, force is off
  DATA (flags 0x0): balancing
  METADATA (flags 0x0): balancing
  SYSTEM (flags 0x0): balancing
ERROR: error during balancing '/home': Input/output error
There may be more info in syslog - try dmesg | tail

real    68m10.221s
user    0m0.008s
sys     4m20.236s

Here is what dmesg shows :
[74421.794756] ata2.00: exception Emask 0x0 SAct 0xc00 SErr 0x0 action 0x0
[74421.794766] ata2.00: irq_stat 0x40000001
[74421.794773] ata2.00: failed command: READ FPDMA QUEUED
[74421.794783] ata2.00: cmd 60/08:50:48:96:f8/00:00:25:00:00/40 tag 10 ncq 4096 in
[74421.794783]          res 41/40:08:48:96:f8/00:00:25:00:00/40 Emask 0x409 (media error) <F>
[74421.794788] ata2.00: status: { DRDY ERR }
[74421.794791] ata2.00: error: { UNC }
[74421.794794] ata2.00: failed command: READ FPDMA QUEUED
[74421.794802] ata2.00: cmd 60/10:58:40:af:ed/00:00:20:00:00/40 tag 11 ncq 8192 in
[74421.794802]          res 41/40:58:48:96:f8/00:00:25:00:00/40 Emask 0x9 (media error)
[74421.794806] ata2.00: status: { DRDY ERR }
[74421.794809] ata2.00: error: { UNC }
[74421.798253] ata2.00: configured for UDMA/100
[74421.798303] sd 1:0:0:0: [sdb] tag#10 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE
[74421.798315] sd 1:0:0:0: [sdb] tag#10 Sense Key : Medium Error [current] [descriptor]
[74421.798326] sd 1:0:0:0: [sdb] tag#10 Add. Sense: Unrecovered read error - auto reallocate failed
[74421.798337] sd 1:0:0:0: [sdb] tag#10 CDB: Read(10) 28 00 25 f8 96 48 00 00 08 00
[74421.798344] blk_update_request: I/O error, dev sdb, sector 637048392
[74421.798366] BTRFS error (device dm-0): bdev /dev/dm-0 errs: wr 38, rd 451, flush 0, corrupt 0, gen 0
[74421.798425] sd 1:0:0:0: [sdb] tag#11 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE
[74421.798435] sd 1:0:0:0: [sdb] tag#11 Sense Key : Medium Error [current] [descriptor]
[74421.798444] sd 1:0:0:0: [sdb] tag#11 Add. Sense: Unrecovered read error - auto reallocate failed
[74421.798453] sd 1:0:0:0: [sdb] tag#11 CDB: Read(10) 28 00 20 ed af 40 00 00 10 00
[74421.798459] blk_update_request: I/O error, dev sdb, sector 552447808
[74421.798523] ata2: EH complete

EDIT 4 : I'm actually using /dev/sdb :
$ sudo smartctl -a /dev/sdb
smartctl 6.2 2013-07-26 r3841 [x86_64-linux-4.4.0-143-generic] (local build)
Copyright (C) 2002-13, Bruce Allen, Christian Franke, www.smartmontools.org

=== START OF INFORMATION SECTION ===
Model Family:     Toshiba 2.5" HDD MQ01ABD...
Device Model:     TOSHIBA MQ01ABD100
Serial Number:    84EWT2U5T
LU WWN Device Id: 5 000039 5b1f852cb
Firmware Version: AX1P4M
User Capacity:    1 000 204 886 016 bytes [1,00 TB]
Sector Size:      512 bytes logical/physical
Rotation Rate:    5400 rpm
Device is:        In smartctl database [for details use: -P show]
ATA Version is:   ATA8-ACS (minor revision not indicated)
SATA Version is:  SATA 2.6, 3.0 Gb/s (current: 3.0 Gb/s)
Local Time is:    Mon Apr  1 23:34:41 2019 CEST
SMART support is: Available - device has SMART capability.
SMART support is: Enabled

=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED

General SMART Values:
Offline data collection status:  (0x82) Offline data collection activity
                    was completed without error.
                    Auto Offline Data Collection: Enabled.
Self-test execution status:      (   0) The previous self-test routine completed
                    without error or no self-test has ever
                    been run.
Total time to complete Offline
data collection:        (  120) seconds.
Offline data collection
capabilities:            (0x5b) SMART execute Offline immediate.
                    Auto Offline data collection on/off support.
                    Suspend Offline collection upon new
                    command.
                    Offline surface scan supported.
                    Self-test supported.
                    No Conveyance Self-test supported.
                    Selective Self-test supported.
SMART capabilities:            (0x0003) Saves SMART data before entering
                    power-saving mode.
                    Supports SMART auto save timer.
Error logging capability:        (0x01) Error logging supported.
                    General Purpose Logging supported.
Short self-test routine
recommended polling time:    (   2) minutes.
Extended self-test routine
recommended polling time:    ( 243) minutes.
SCT capabilities:          (0x003d) SCT Status supported.
                    SCT Error Recovery Control supported.
                    SCT Feature Control supported.
                    SCT Data Table supported.

SMART Attributes Data Structure revision number: 16
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
  1 Raw_Read_Error_Rate     0x000b   100   100   050    Pre-fail  Always       -       0
  2 Throughput_Performance  0x0005   100   100   050    Pre-fail  Offline      -       0
  3 Spin_Up_Time            0x0027   100   100   001    Pre-fail  Always       -       1735
  4 Start_Stop_Count        0x0032   100   100   000    Old_age   Always       -       5639
  5 Reallocated_Sector_Ct   0x0033   100   100   050    Pre-fail  Always       -       0
  7 Seek_Error_Rate         0x000b   100   100   050    Pre-fail  Always       -       0
  8 Seek_Time_Performance   0x0005   100   100   050    Pre-fail  Offline      -       0
  9 Power_On_Hours          0x0032   080   080   000    Old_age   Always       -       8259
 10 Spin_Retry_Count        0x0033   212   100   030    Pre-fail  Always       -       0
 12 Power_Cycle_Count       0x0032   100   100   000    Old_age   Always       -       5623
191 G-Sense_Error_Rate      0x0032   100   100   000    Old_age   Always       -       563
192 Power-Off_Retract_Count 0x0032   100   100   000    Old_age   Always       -       203
193 Load_Cycle_Count        0x0032   099   099   000    Old_age   Always       -       17892
194 Temperature_Celsius     0x0022   100   100   000    Old_age   Always       -       23 (Min/Max 10/46)
196 Reallocated_Event_Count 0x0032   100   100   000    Old_age   Always       -       0
197 Current_Pending_Sector  0x0032   100   100   000    Old_age   Always       -       9200
198 Offline_Uncorrectable   0x0030   001   001   000    Old_age   Offline      -       255
199 UDMA_CRC_Error_Count    0x0032   200   200   000    Old_age   Always       -       0
220 Disk_Shift              0x0002   100   100   000    Old_age   Always       -       0
222 Loaded_Hours            0x0032   080   080   000    Old_age   Always       -       8117
223 Load_Retry_Count        0x0032   100   100   000    Old_age   Always       -       0
224 Load_Friction           0x0022   100   100   000    Old_age   Always       -       0
226 Load-in_Time            0x0026   100   100   000    Old_age   Always       -       177
240 Head_Flying_Hours       0x0001   100   100   001    Pre-fail  Offline      -       0

SMART Error Log Version: 1
ATA Error Count: 1029 (device log contains only the most recent five errors)
    CR = Command Register [HEX]
    FR = Features Register [HEX]
    SC = Sector Count Register [HEX]
    SN = Sector Number Register [HEX]
    CL = Cylinder Low Register [HEX]
    CH = Cylinder High Register [HEX]
    DH = Device/Head Register [HEX]
    DC = Device Command Register [HEX]
    ER = Error register [HEX]
    ST = Status register [HEX]
Powered_Up_Time is measured from power on, and printed as
DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes,
SS=sec, and sss=millisec. It "wraps" after 49.710 days.

Error 1029 occurred at disk power-on lifetime: 8257 hours (344 days + 1 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  40 41 50 48 96 f8 40  Error: UNC at LBA = 0x00f89648 = 16291400

  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  60 10 58 40 af ed 40 00      03:13:20.172  READ FPDMA QUEUED
  60 08 50 48 96 f8 40 00      03:13:16.469  READ FPDMA QUEUED
  60 08 48 40 96 f8 40 00      03:13:16.469  READ FPDMA QUEUED
  60 08 40 38 96 f8 40 00      03:13:16.469  READ FPDMA QUEUED
  60 08 38 30 96 f8 40 00      03:13:16.469  READ FPDMA QUEUED

Error 1028 occurred at disk power-on lifetime: 8257 hours (344 days + 1 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  40 41 70 48 96 f8 40  Error: UNC at LBA = 0x00f89648 = 16291400

  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  60 10 70 78 90 f8 40 00      03:13:11.731  READ FPDMA QUEUED
  60 d0 68 a8 89 f8 40 00      03:13:11.731  READ FPDMA QUEUED
  61 e0 60 60 aa 0b 40 00      03:13:11.727  WRITE FPDMA QUEUED
  61 00 58 60 a2 0b 40 00      03:13:11.723  WRITE FPDMA QUEUED
  61 00 50 60 9a 0b 40 00      03:13:11.625  WRITE FPDMA QUEUED

Error 1027 occurred at disk power-on lifetime: 8133 hours (338 days + 21 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  40 41 c0 f8 bd 51 40  Error: UNC at LBA = 0x0051bdf8 = 5357048

  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  60 58 e0 70 fa 40 40 00      00:18:59.971  READ FPDMA QUEUED
  61 08 d8 d8 45 2b 40 00      00:18:59.971  WRITE FPDMA QUEUED
  61 08 d0 d0 78 6b 40 00      00:18:59.971  WRITE FPDMA QUEUED
  61 08 c8 18 42 2b 40 00      00:18:59.971  WRITE FPDMA QUEUED
  60 08 c0 f8 bd 51 40 00      00:18:59.971  READ FPDMA QUEUED

Error 1026 occurred at disk power-on lifetime: 8133 hours (338 days + 21 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  40 41 00 f8 bd 51 40  Error: WP at LBA = 0x0051bdf8 = 5357048

  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  61 38 10 28 5f 6b 40 00      00:18:55.963  WRITE FPDMA QUEUED
  61 08 08 68 85 6f 40 00      00:18:55.963  WRITE FPDMA QUEUED
  60 00 00 f0 bd 51 40 00      00:18:55.946  READ FPDMA QUEUED
  60 00 f0 80 75 56 40 00      00:18:55.944  READ FPDMA QUEUED
  60 00 e8 80 73 56 40 00      00:18:55.930  READ FPDMA QUEUED

Error 1025 occurred at disk power-on lifetime: 8119 hours (338 days + 7 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  40 41 b8 f8 7f 48 40  Error: UNC at LBA = 0x00487ff8 = 4751352

  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  60 08 b8 f8 7f 48 40 00      01:10:35.049  READ FPDMA QUEUED
  ea 00 00 00 00 00 a0 00      01:10:35.017  FLUSH CACHE EXT
  61 08 98 88 4b cb 40 00      01:10:35.017  WRITE FPDMA QUEUED
  61 08 70 98 c1 0c 40 00      01:10:35.017  WRITE FPDMA QUEUED
  61 08 60 a0 45 cb 40 00      01:10:35.017  WRITE FPDMA QUEUED

SMART Self-test log structure revision number 1
Num  Test_Description    Status                  Remaining  LifeTime(hours)  LBA_of_first_error
# 1  Short offline       Completed without error       00%      6780         -
# 2  Short offline       Completed without error       00%         1         -

SMART Selective self-test log data structure revision number 1
 SPAN  MIN_LBA  MAX_LBA  CURRENT_TEST_STATUS
    1        0        0  Not_testing
    2        0        0  Not_testing
    3        0        0  Not_testing
    4        0        0  Not_testing
    5        0        0  Not_testing
Selective self-test flags (0x0):
  After scanning selected spans, do NOT read-scan remainder of disk.
If Selective self-test is pending on power-up, resume after 0 minute delay.

$ echo $?
64

and dmesg reports 2 bad sectors during the last btrfs balance operation :
$ dmesg | grep I/O.error.*sector
[74421.798344] blk_update_request: I/O error, dev sdb, sector 637048392
[74421.798459] blk_update_request: I/O error, dev sdb, sector 552447808

Remapped those the bad sectors :
$ dmesg | grep I/O.error.*sector | awk '/sector/{print "sudo hdparm --yes-i-know-what-i-am-doing --repair-sector "$NF" /dev/sdb"}' | sh -x
+ sudo hdparm --yes-i-know-what-i-am-doing --repair-sector 637048392 /dev/sdb

/dev/sdb:
re-writing sector 637048392: succeeded
+ sudo hdparm --yes-i-know-what-i-am-doing --repair-sector 552447808 /dev/sdb

/dev/sdb:
re-writing sector 552447808: succeeded

EDIT 5 : It seems this command was enough to have more than 11G unallocated :
$ sudo btrfs balance start -musage=0 -dusage=0 -v /home
Dumping filters: flags 0x7, state 0x0, force is off
  METADATA (flags 0x2): balancing, usage=0
  SYSTEM (flags 0x2): balancing, usage=0
  DATA (flags 0x2): balancing, usage=0
Done, had to relocate 0 out of 95 chunks

The btrfs filesystem resize succeeded. (I'm sorry, I've lost the output of the btrfs filesystem resize)

A: You're requesting the volume to shrink by 11GB, yet you only have about 6GB unallocated.
You can more efficiently use allocated extents by rebalancing the volume. Executing a command similar to btrfs balance start /home will start that process, and it may take some time to complete.
But I don't know if that will free up enough for a large amount of shrinkage.


text:
Q: how to allow only one line in rich text box I'm using WPF (C#).
I want the user to be able to only type one line in a rich text box (can't press enter key).
Could anyone tell me how can I set up this kind of rich text box property?

A: Set its AcceptsReturn property/attribute to false.


text:
Q: Finding a location of a file on Windows 10 I have a laptop running Windows 10, and I have a program running yet I can't access the location of that program. It's clear that it's on my list of programs (1.08GB) but I can't trace the location. How can I solve this? Every time I try searching it up, it leads to the appdata folder but I want the Installer.

A: One simple way to find out what processes are running is with Windows Task Manager. Press CtrlShiftEsc simultaneously, and, on the Details page, add Image path name, if not already visible, by right-clicking on the table caption line and selecting it as shown below.
SysInternals Process Explorer can be used the same way.

A: Are you looking for the Installation file or the Executable file? The installation file is NOT linked to the executable file.
To find the executable file (the file used to launch the application .exe) search under
C:\Program Files\ or C:\Program Files (x86)\


text:
Q: Is a revision of the std::allocator interface planned for future C++ versions? In a talk from 2015 Andrei Alexandrescu outlines some atrocities of the std::allocator interface, shortly highlighting how it's not in fact about allocation and proposing a different way of thinking about these allocators that would make them more usable and modular. Or, to quote from the description:

std::allocator has an inglorious past, murky present, and cheerless future. STL introduced allocators as a stop gap for the now antiquated segmented memory models of the 1990s. Their design was limited and in many ways wasn't even aiming at helping allocation that much. Because allocators were there, they simply continued being there, up to the point they became impossible to either uproot or make work, in spite of valiant effort spent by the community.

This talk discusses the full design of a memory allocator created from first principles. It is generic, componentized, and composable for supporting application-specific allocation patterns.

His main points against the current std::allocator are contained in this section of the video, but to summarize:

*

*Allocators should not care about the type being allocated, only the size and alignment.

*Allocators should not be responsible for storing size information about an allocation, allocation and deallocation should symmetrically (respectively) return and receive a Blk (ptr, size).

*Rebind<U>::other is terrible (he did not go in further detail)

*Allocators should not be stateless (since they literally give you pieces of memory, how can they be stateless?)

*Allocators should be defined around the concept of composition; if you look at real world allocators they are all composed of small little allocators that conditionally run.

Ever since I watched that talk I have expected some kind of proposal to follow from it, since the idea seemed so sound and usable. I've had to work with std::allocator in the past and it made me understand the need for C++20 concepts for the first time when my screen screamed at me in candidate function not viable.
But nothing seems to have come from it? I wasn't around back then but it seems like STL2 was in the works, but that has since been discontinued. Has it been decided somewhere that concepts would be sufficient to at least mediate the symptoms of std::allocator (if so, where/when?) or is it a backwards-compatibility problem? Is something related to this on the roadmap for a future C++ version?

A: There is no proposal for a radical re-alteration of the allocator model. This is for basically two reasons.
The C++ container library relies on allocators working a certain way, and it would be complex in the extreme to make containers that work with both kinds of allocators. So if you want a new allocator model, you're also talking about a new set of containers, which is a huge can of worms that the committee balked at opening.
Most of the deficiencies in allocator creation and usage are pretty avoidable these days. Writing an allocator even in C++17 is not exactly a challenge. You don't need to understand the gory details of the thing; you just need to implement a couple of functions and a few member aliases. std::allocator_traits fills in most of the blanks for you.
At the end of the day, there are significant deficiencies in the C++ language and library that are more important than an allocator model that's more difficult to use than is strictly necessary.

A: We already have std::pmr built on top of allocators that addresses all listed concerns.


text:
Q: Erro de diretório com spl_autoload_register Estou com um erro usando o autoloader.
Arquivo autoloader.php:
<?php

function carregarClasses($classe) {
    require_once __DIR__ . '/' . $classe . '.php';
}

spl_autoload_register('carregarClasses');

Erro:

Warning:
  require_once(/home/neowix/public_html/erp/pages/classes/Conexao.php):
  failed to open stream: No such file or directory in
  /home/neowix/public_html/erp/pages/classes/autoload.php on line 4
Fatal error: require_once(): Failed opening required
  '/home/neowix/public_html/erp/pages/classes/Conexao.php'
  (include_path='.:/opt/php56/lib/php') in
  /home/neowix/public_html/erp/pages/classes/autoload.php on line 4

A: A constante __DIR__ retorna o diretório do arquivo corrente, do arquivo onde script está sendo executado.  No seu caso,  /home/neowix/public_html/erp/pages/classes/autoload.php
Ao montar o path para autocarregar (autoload) os arquivos contendo as classes, o caminho será:
/home/neowix/public_html/erp/pages/classes/NomeDaClasse.php

Se o caminho estiver montando corretamente, certifique-se de que os arquivos possuem a nomenclatura correta. Em ambiente Linux, a nomenclatura é case sensitive. Exemplo, se o arquivo existir com nome "conexao.php", não será encontrado.


text:
Q: Validate xml with multiple xsd files I am creating an xml pendant to Couchdb, with validation of the documents using xsd.
Right now the embedding of project:project is not working and gives a validation error.
How can I change my xsd, so my xml file is valid?
I want the following xml layout:
 <document:document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns:document="urn:JCouch.Document"
                   xmlns:attachment="urn:JCouch.Attachment"
                   xmlns:project="urn:JCouch.Project"
                   xsi:schemaLocation="
                   urn:JCouch.Document document.xsd
                   urn:JCouch.Project project.xsd
                   ">
    <document:meta>
        <document:id>123</document:id>
        <document:revision>12321</document:revision>
        <document:deleted>false</document:deleted>
        <document:md5>md5 of everything including</document:md5>
    </document:meta>
    <!-- Auto generated based on files attached -->
    <document:attachments>
        <attachment:attachment>
            <attachment:path></attachment:path>
            <attachment:length>1</attachment:length>
            <attachment:md5></attachment:md5>
        </attachment:attachment>
    </document:attachments>
    <!-- The actual document content -->
    <document:content>
        <project:project>
            <project:name>dsa</project:name>
            <project:projectNumber>123</project:projectNumber>
        </project:project>
    </document:content>
    </document:document>

I have 3 xsd files. 1 for document, 1 for attachment and 1 for project.
Have in mind project is just an example. I would later want to add blog:blog blog:entry and so forth.
Document.xsd:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       targetNamespace="urn:JCouch.Document"
       xmlns="urn:JCouch.Document"
       xmlns:attachment="urn:JCouch.Attachment"
       xmlns:project="urn:JCouch.Project"
       xsi:schemaLocation="
       urn:JCouch.Attachment attachment.xsd
       urn:JCouch.Project project.xsd"
       elementFormDefault="qualified"
    >

<xs:element name="document" type="documentType"/>

<xs:complexType name="documentType">
    <xs:sequence>
        <xs:element name="meta" minOccurs="1" maxOccurs="1">
            <xs:complexType>
                <xs:sequence>
                    <xs:element minOccurs="1" maxOccurs="1" name="id" type="xs:string"/>
                    <xs:element minOccurs="1" maxOccurs="1" name="revision" type="xs:string"/>
                    <xs:element minOccurs="1" maxOccurs="1" name="deleted" type="xs:boolean"/>
                    <xs:element minOccurs="1" maxOccurs="1" name="md5" type="xs:string"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
        <xs:element name="attachments" minOccurs="1" maxOccurs="1" type="attachment:attachmentType"/>
        <xs:element name="content" minOccurs="1" maxOccurs="1" type="contentType">
        </xs:element>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="contentType">
    <xs:sequence>
        <xs:element ref="project:project" minOccurs="0" maxOccurs="1"/>
    </xs:sequence>
</xs:complexType>
</xs:schema>

project.xsd:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
       targetNamespace="urn:JCouch.Project"
       elementFormDefault="qualified">

<xs:complexType name="projectType">
    <xs:sequence>
        <xs:sequence>
            <xs:element name="name" type="xs:string"/>
            <xs:element name="projectNumber" type="xs:string"/>
        </xs:sequence>
    </xs:sequence>
</xs:complexType>

<xs:element name="project" type="projectType"/>

</xs:schema>

and lastly attachment.xsd, though this part works!
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
       targetNamespace="urn:JCouch.Attachment"
       elementFormDefault="qualified">

<xs:complexType name="attachmentType">
    <xs:sequence>
        <xs:element name="attachment">
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="path" type="xs:anyURI"/>
                    <xs:element name="length" type="xs:integer"/>
                    <xs:element name="md5" type="xs:string"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
    </xs:sequence>
</xs:complexType>
</xs:schema>

Any help will be greatly appreciated.
Best regards
Kresten Kjaer

A: Since all three schemas have different target namespaces,
you may use one of them as the main schema (or the driver schema),
which you will specify to the validator,
and all other schemas must be imported in it.
Let's Document.xsd will be the main schema (after all, it defines the root element of your XML). Then, you can write it like this:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       targetNamespace="urn:JCouch.Document"
       xmlns="urn:JCouch.Document"
       xmlns:attachment="urn:JCouch.Attachment"
       xmlns:project="urn:JCouch.Project"
       xsi:schemaLocation="
       urn:JCouch.Attachment attachment.xsd
       urn:JCouch.Project project.xsd"
       elementFormDefault="qualified"
    >

  <!-- import all other related schemas here -->
  <xs:import namespace="urn:JCouch.Project" schemaLocation="project.xsd"/>
  <xs:import namespace="urn:JCouch.Attachment" schemaLocation="attachment.xsd"/>

  <!-- all other definitions of Document.xsd -->
  ...

</xs:schema>

Now, Document.xsd should validate your XML.
(In fact, you can make a driver from any other schema by specifying in it similar imports of all other schemas.)


text:
Q: How can I install Gentoo on Virtual Box//(Ubuntu 12.04) I'm googling for a while about how can I install Gentoo on Virtual Box. The hand book provides less information about installing it on virtual box rather on a real partition.
I thought there will be a GUI tool to install Gentoo. [Now I think there is not :(]
Whenever I'm booting into gentoo Im going into a LiveDVD environment where fdisk returning "command not found !" (Not sure this is a bug or Im using a wronng command)
Now Im not a very exprienced user but do like to learn and play with Gentoo. Any help link will be appriciated.
Downloaded File: livedvd-x86-amd64-32ul-2012.iso (Do I need to use Gentoo 64 as OS version in Virtual Box ?)

A: The procedure to install an operating system in Virtual Box is practically identical to installing on real hardware. You still need to partition the virtual disk as if it was a physical one (as described in the Gentoo installation guide) with fdisk (or whatever you prefer). You're best off using the Gentoo minimal CD, but starting from any other Linux environment will also work as long as all the needed tools are available. You might be able to install fdisk (into RAM) with your current live-DVD using the distributions package installation procedure, if it isn't included.
You don't need to install the amd64 version of Gentoo, the x86 version will also work. But note that the amd64 version can provide a hybrid environment also able to run 32bit binaries.

A: Here is a straight forward blog post for installing Gentoo on a VirtualBox image for an x86 architecture but it should work for all with slight variation.
Use whichever minimal iso is compatible for your system architecture and download the corresponding portage and stage 3 tarballs.

A: We are informed (#gentoo on freenode) that the current amd64 ISO (minimal) has problems. Apparently the ISO from June is currently the best one to use.
It is up to you whether you want 64 or 32 bit guest OS.
Feel free to use this Canadian mirror:
/releases/amd64/autobuilds/20120621/