text:
Q: Solving Schrodinger Equation for scattering off a periodic potential I am interesting in solving the time-independent Schrodinger equation (TISE) for the scenario where we have an electron plane wave of fixed energy incident upon a potential that is infinite and periodic only the transverse plane (i.e. a very thin or monolayer crystal). This corresponds to the physical situation of transmission electron microscopy (TEM) with a thin specimen. My question relates to the assumptions we make about the form of the wave function  when solving the TISE (see below).
As some background, the TISE can be written as
$$ \{\nabla^2 + 4\pi^2 [U(\textbf{r}) + K^2]\}\Psi(\textbf{r}) = 0$$
and I believe the boundary conditions in this scenario can be roughly specified by dividing the system into three regions in the $z$ direction:

*

*Above the specimen: contains the incident plane wave plus back-scattered plane waves

*Within the specimen: contains wave functions as dictated by the potential $U(\textbf{r})$

*Below the specimen: contains only transmitted plane waves

I assume that requiring continuity in $\Psi(\textbf{r})$ across the region boundaries would fully specify this problem (up to a phase factor), although I'd appreciate any clarity on that if I'm mistaken there.
It is conventional in TEM theory that a Bloch wave ansatz is made for the functional form of the solution, for the same reason that Bloch waves are used in solid state physics, viz. the periodic nature of the crystal potential.We assume that the wave function $\Psi(\textbf{r})$ can be expanded in Bloch states $B_i(\textbf{r})$ as follows:
$$
\begin{align}
\Psi(\textbf{r}) & = \sum_i \alpha_i B_i(\textbf{r}) \\
B_i(\textbf{r}) & = \sum_\textbf{g} C_\textbf{g} \exp[2\pi i (\textbf{k}_i + \textbf{g})\cdot \textbf{r}]
\end{align}
$$
If we substitute this into the TISE we end up with a linear algebra problem in the coefficients $C_\textrm{g}$ and $\alpha_i$, which is reasonably straightforward to solve using some approximations and matrix diagonalisation.
I am comfortable with the use of the Bloch wave solutions for a crystal which is infinite in all directions, where it can be proved that the Bloch waves form a complete basis set. In my scenario however, the cystal is finite in the $z$ dimension, and so the Bloch theorem won't strictly hold. There will probably be some surface states possible and the boundary conditions in the $z$ direction will affect the bulk properties, so on a physical basis we expect some departure from the ideal Bloch states.
For moderately thick specimens where there is some periodicity in the $z$ dimension, it seems at least plausible that the Bloch wave ansatz is not a bad starting point, and might let us solve the TISE to an acceptable approximation (particularly where the incident electrons are high-energy and perhaps aren't impacted by the fine details).
But for a very thin specimen, e.g. a single plane of atoms, it doesn't seem reasonable to assume the Bloch wave ansatz, because there is no periodicity in $z$ at all. However, I could imagine we might arrive at a similar ansatz through some hand wavy argument about the high energy of the incident electron letting us have a separable solution of this form:
$$\Psi_i(\textbf{r}) = \exp(2\pi i k_i z) \sum_{\textbf{g}_\perp} C_{\textbf{g}_\perp} \exp[2\pi i {\textbf{g}_\perp} \cdot \textbf{r}]$$
which reflects the periodicity in the transverse plane and assumes that the incident plane wave is effectively just "modulated" a bit by the specimen potential. I'm not entirely confident about this ansatz though for the single layer specimen.
My question
Is there some more general approach to solving the TISE in this scenario, which doesn't involve starting with the Bloch wave ansatz, but does make it clear how we might still arrive at that functional form to a decent approximation in the case of finite and very thin specimens? I'm expecting that at some step in the solution method, the high energy of the incident electron can be explicitly introduced to simplify the equations and recover something like the Bloch wave functional form.

A:
In my scenario however, the cystal is finite in the z dimension, and so the Bloch theorem won't strictly hold.

This is wrong. Bloch theorem holds in any periodic medium, including finite ones. In particular, it's easy to prove for the case of periodic (Born—von Karman) boundary conditions: there's a well-defined translation operator that commutes with the Hamiltonian operator and thus must share eigenfunctions with it—and these are the Bloch wavefunctions. The spectrum is purely discrete in this case, though the eigenvalues do clump in sorts of bands, becoming denser as number of cells in the lattice increases.
Now, your setting isn't a periodic one. But it works the same way as the use of the free-space solutions when solving Schrödinger's equation for a finite rectangular quantum well or barrier: by matching the solutions in the piecewise intervals.
Why does it work?
Time-independent Schrödinger's equation is a linear homogeneous second-order ODE. By itself, it doesn't know anything about boundary conditions. They may not even be given. This equation has exactly two linearly independent solutions. Any other solution is a linear combination of them.
Now, suppose we have a pair of Bloch solutions (one $+k$, another $-k$) for an infinite crystal with potential $V(x)$ for $x\in\mathbb R.$ If, for $x\in(\infty,a]\cup[b,\infty),$ we replace $V(x)$ with some other potential $U(x)$, these solutions will still satisfy the Schrödinger's equation for $x\in(a,b)$. Moreover, whatever solution you find for the Schrödinger's equation with new potential, given the same energy $E,$ it'll still be (in $x\in(a,b)$) a linear combination of these two Bloch solutions. This is what lets us simply match the functions at the boundaries by providing the appropriate pairs of coefficients for the infinite-space solutions. The requirement of continuity of the wavefunction and its derivative makes sure that the equation is also satisfied at the interfaces $x=a$ and $x=b.$


text:
Q: FTP Scripting Capabilities I am looking for an FTP client that will allow me to do the following

*

*Include a GUI for setting up a number of FTP connections

*Support FTPS

*Run unattended on Windows Server 2008

*Retry failed transactions

*Support email

*Support custom scripts

I need to pull files from a few different servers and there are certain calculations that need to be done depending on which server the files come from.
I've looked at SmartFTP and it looks like pretty much what I need except I can't get it to run as a Windows Scheduled Task (I currently have some support threads open in their forum).
I've also looked at a few other FTP clients (Filezilla, RoboFTP, and AutoFTP (you can find the Windows 7 BSOD in this one!)) that haven't had the capabilities I'm looking for.
Right now, I'm looking at WS_FTP and its scripting capabilities. It appears I can create a script to run as a scheduled task, but I can't add the script to a file transfer task.
Does anyone have suggestions on how I can do post-transfer processing on the files or better yet how to integrate scripting into the file transfer task?
I'm also open to other suggestions for FTP clients as well if you have them!
If I can't find a suitable FTP client, custom scripting will just have to do the trick.

A: I ended up going with SmartFTP. Although I received timely, useful help, I was disappointed they wouldn't give me a temporary license to work with scheduled tasks to see if the behavior was appropriate for my purposes. Luckily, it all worked out in the end.

A: Try Auto FTP Manager.  It is designed for automatic file transfers on a schedule and it logs all your transfers and any errors. Download the software here:
http://www.deskshare.com/ftp-client.aspx

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to hide SMTP Auth user mail id in Nodemaile I am using nodemailer in my project . (sorry for
My english is not good )
var nodemailer = require("nodemailer");
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
   user: "agodatest@gmail.com",
   pass: "pwd"
 }
});

smtpTransport.sendMail({
 from: "James andrison <james@andr.com>", // sender address
 to: "user2 surname<receiver@receiver.com>", // comma separated list of receivers
 subject: "Hello ✔", // Subject line
 text: "Hello world ✔" // plaintext body
}, function(error, response){
 if(error){
   console.log(error);
 }else{
   console.log("Message sent: " + response.message);
 }
});

In the Above code When I receive mail. I can see Sender name with auth.user email id in the mail but cannot see Sender email id.
I got output like this --> James andrison ;
So can you tell me how to hide SMTP / Auth email id ?
Thankx in advance .


text:
Q: Text file to list in Python Suppose I have a document called test1.txt that contains the following numbers:
133213
123123
349135
345345

I want to be able to take each number and append it to the end of the URL below to make a HTTP request. How do I stuff the id's into a list and call each one? This is what I have so far.
file = open('C:\Users\Owner\Desktop\\test1.txt')
startcount = 1
endcount = len(file.readlines())

o = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
urllib2.install_opener( o )

while startcount < endcount:

    f = o.open( 'http://www.test.com/?userid=' + ID GOES HERE )
    f.close()

A: >>> from urllib import urlencode
>>> with open('C:\Users\Owner\Desktop\\test1.txt') as myfile:
...     for line in myfile:
...             params = urlencode({'userid': line.strip()})
...             f = opener.open('http://www.test.com/?' + params)
...             # do sth
...

A: Try this:
o = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(o)

file = open('C:\Users\Owner\Desktop\\test1.txt')
for line in file:
    f = o.open('http://www.test.com/?userid=' + line.rstrip())
    f.close()

A: id_file = [line.strip() for line in open('/file/path')]  # path to file
# so id_file is a list: ['133213', '123123', '349135', '345345']

url = 'http://www.test.com/?userid='                     # url
for ele in id_file:
        f = o.open(url + ele)

o being the same as in your program.

A: read all the value using file.readlines(), remove the line ending '\n' for each line, and the rest is your number.


text:
Q: angular full calendar event dosen't display I use angular full calender v4 for display events in calendar but I have error when I want to display events in timeGridDay and timeGridWeek i have error of display , is displayed or hours.
example of errors display events of week:
enter image description here
and also example of errors display events in day:
enter image description here
code html:
            <div class="col-lg-12">
        <full-calendar
            #myCalendar
            defaultView="dayGridMonth"
            [slotLabelFormat]="slotLabelFormat"
            [plugins]="calendarPlugins"
            [header]="{
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
            }"
            dir="rtl"
            [events]="listEvents"
            [eventTimeFormat]="eventTimeFormat"
            (eventClick)="handleEventClick($event)"
        >
        </full-calendar>
    </div>

code ts:
            eventTimeFormat = { hour12: false, hour: '2-digit', minute: '2-digit' };
        slotLabelFormat = [ { hour: '2-digit', minute: '2-digit', hour12: false } ]


text:
Q: Google analytics two calls on pageview I have implemented analytics with google tag manager on my website.
Can anybody explain,why there are two calls on Pageview?
First, one is for pageview, what this second call do?

A: Since the name of the page was visible (now edited out) in the image I had a look at it. There are two pageviews configured within GTM. On is configured to override the page path, that's why the two calls are different (and why you do not see duplicates in GA).
It looks like somebody tried to implement virtual pageviews (since this is a one page application without proper urls) and accidentally sends one pageview to many on the inital pageload.


text:
Q: ESLint: Error in every file in Typescript monorepo I'm working in a new TypeScript Monorepo. No matter what I do, I'm encountering the following error:
.
I've restarted my editor numerous times, removed and re-installed node_modules, but to no avail. I've also tried a separate editor, WebStorm, same results. This is rather frustrating because ESLint refuses to run on each file entirely. This makes it extremely painful to write code in this environment. Any suggestions are appreciated, I've exhausted all the tricks I'm aware of.
The monorepo has 2 main folders, apps and packages. Inside packages are a few folders. Most importantly, eslint-config-custom. This is a link to the configuration in a Github gist: https://gist.github.com/cnrstvns/c35fdb1d142d5679761f95dece1f4588.
Inside packages is a folder called lib, that contains various TypeScript files. Each file in this folder, when opened, appears with the aforementioned parsing error.
Any help is appreciated. Please let me know if there are any further details I can provide. Thanks!
Environment details:
TypeScript version 4.6.2
ESLint version 8.19.0
Visual Studio Code version 1.69.0
Yarn version 1.22.19
Turborepo version 1.2.16


text:
Q: search string and replace corresponding number in windows env I have one file and replace string :
sample file is:
DP_SESSION_ID is a sting for values
DP_SESSION_ID is aplicat
"DP_S42SETTACC_TYPE"\1\"02"
"DP_SAP_CLIENT"\1\"460"
"DP_SAP_COMM_CONNECTION"\1\"JAVA_COMM_TOOL_ANALYZER"
"DP_SAP_CONNECTION"\1\"JAVA_TOOL_ANALYZER"
"DP_SAP_TOOLBI_CONNECTION"\1\"JAVA_TOOLBI_ANALYZER"
"DP_SESSION_ID"\1\"808"
I want search this  "DP_SESSION_ID"\1\" sting and replace corresponding number like 808 in file prenatally(windows env), and i wand sing line command in windows bat command or perl command i don't want scrip or program
even i have installed  cygwin tool in my server so unix also ok but single line command
server: windows 2008,cygwin x
using tool : datastage server jobs
perl -pi -e 's{" "DP_SESSION_ID"\1\"808 '"}{' "DP_SESSION_ID"\1\"900 '"'"}g' " file name

this code is not working
Please give good solution

A: First, you can't use single-quotes in DOS the way you can in UNIX.  Second, you need to specify a backup file/extension when you use "-i" in DOS.  Third, I think you skip trying to match all those complicated quotes and go with a simpler approach.  It may not be the most efficient (using 2 regex) but it's very readable (to me).
This works for me:
perl -p -i.bak -e "m/\"DP_SESSION_ID\"/ && s/808/900/g" "filename"

Hope that helps!

A: in powershell, you can try the command as below:
get-content input.txt |foreach-object {$_ -replace '"DP_SESSION_ID"\\1\\"808"', '"DP_SESSION_ID"\1\"900"'} | set-content output.txt


text:
Q: Where does the high value loot in Emercom Medical spawn? On interchange there is a locked room called "Emercom Medical" which supposedly has high value loot in it, but I find it very difficult to find another beyond basic meds and low value tech spawns.  Are there any semi-fixed locations to expect high value tech or high value meds (LEDX?).

A: One point to note is that high tier loot spawns don't mean there is a guarantee for that loot, you could realistically run into Emercom 50 raids straight and never find a LEDX.
In this room in particular, you can search the shelves, and beds for a lot of general medical supplies and loose loot. Total lootable list (things not siting in the open) includes 2 Medbags, 1 Sport Bag, and 1 Jacket.
Things like the LEDX, Graphics Card, and Defibrillator can spawn in the metal open dishes that are on tables or on top of hospital beds. You just have to search around the room carefully, you can easily miss them.


text:
Q: Vaadin upload component - File added event Is there a way to detect that file has been added to the upload component?
There is a file-remove to detect if the file is removed, can we somehow detect if a file is added?
Simplify scenario:
When a File is added display a simple notification.

A: After reviewing https://github.com/vaadin/vaadin-upload/blob/master/src/vaadin-upload.html, this is not possible with the vaadin-upload element as is.
But you can extend UploadElement!
UploadElement has a function named _addFile, which is called whenever a file is added. You just have to confirm the same predicates (which is a bit inefficient, but is what it is), and if the file is to be added, fire a new custom event.
custom-vaadin-upload.js:
import {UploadElement} from '@vaadin/vaadin-upload/src/vaadin-upload';

class CustomUploadElement extends UploadElement {

  static get is() {
    return 'custom-vaadin-upload';
  }

  constructor() {
    super();
  }

  _addFile(file) {
    const fileExt = file.name.match(/\.[^\.]*$|$/)[0];
    const re = new RegExp('^(' + this.accept.replace(/[, ]+/g, '|').replace(/\/\*/g, '/.*') + ')$', 'i');

    if(
        !this.maxFilesReached
        && !(this.maxFileSize >= 0 && file.size > this.maxFileSize)
        && !(this.accept && !(re.test(file.type) || re.test(fileExt)))
    ) {
      this.dispatchEvent(new CustomEvent('file-accept', {detail: {file}}));
    }

    super._addFile(file);
  }

}

customElements.define(CustomUploadElement.is, CustomUploadElement);

CustomUpload.java:
@Tag("custom-vaadin-upload")
@JsModule("./src/custom-vaadin-upload.js")
public class CustomUpload extends Upload {

  public CustomUpload() {
    super();
  }

  public CustomUpload(final Receiver receiver) {
    super(receiver);
  }

  public Registration addFileAcceptListener(final ComponentEventListener<FileAcceptEvent> listener) {
    return addListener(FileAcceptEvent.class, listener);
  }

  @DomEvent("file-accept")
  public static class FileAcceptEvent extends ComponentEvent<CustomUpload> {

    private final JsonObject detail;

    private final JsonObject detailFile;

    public FileAcceptEvent(final CustomUpload source, final boolean fromClient,
        @EventData("event.detail") final JsonObject detail,
        @EventData("event.detail.file") final JsonObject detailFile) {
      super(source, fromClient);

      this.detail = detail;
      this.detailFile = detailFile;
    }

    public final JsonObject getDetail() {
      return detail;
    }

    public final JsonObject getDetailFile() {
      return detailFile;
    }

  }

}

Example usage:
final MemoryBuffer buffer = new MemoryBuffer();
final CustomUpload upload = new CustomUpload(buffer);

upload.addFileAcceptListener(System.out::println);

You can read more about extending client-side elements here and mapping DOM events to Java here.


text:
Q: no entiendo el segundo y tercer principio de solid Single Responsibility: cada objeto debe tener una única responsabilidad
Open/Close: abierto para la extensión, clausurado ante cambios
Liskov Substitution: las clases hijas deben poder ser tratadas como las clases padre
Interface Segregation: es preferible muchas interfaces con pocos métodos a pocas interfaces con muchos métodos
Dependency Inversion: los componentes deben depender de abstracciones, no de implementaciones concretas
alguien que sepa me puede explicar ?

A: Open/Close: Significa que tienes que hacer un diseño para que, al agregar nueva funcionalidad no tengas que tocar el código ya existente.
Imaginemos que tienes una aplicación de facturación y varios tipos de clientes, definidos en un enum, y para facturar haces algo como:
switch (cliente.getTipoCliente) {
case TipoClienteA:
   facturarClienteA(cliente);
   break;
case TipoClienteB:
   facturarClienteB(cliente);
   break;

Si añades un tipo de cliente, tienes que ir a todos los switches e ifs de tipoCliente y añadir la lógica, modificando código que ya funciona.
Como alternativa, imagina que defines una interface Facturador, y que en el enum de TipoCliente tienes un método que, para cada instancia, te proporciona una implementación de Facturador adecuada al tipo de cliente. Entonces el código de arriba te queda como:
Facturador facturador = cliente.getTipoCliente.getFacturador();
facturador.facturarCliente(cliente);

Si añades un nuevo cliente, sólo necesitas implementar el facturador y añadir el elemento al enum.
Otras opciones son sistemas de plugin y demás.
Dicho lo dicho, siempre he encontrado que es el criterio más complicado de implementar, y lo aplico sólo para bloques bien definidos (recuerda que SOLID son recomendaciones, no reglas absolutas).

El principio de substitución es que una instancia de una subclase siempre debe funcionar de forma coherente a como lo haría una instancia de la superclase. Por ejemplo, imagina

 public class A {

   public int valorAbsoluto(int val) {
     return val < 0 ? -val : val;
   }
 }

 public class B extends A {
   @Override
   public int valorAbsoluto(int val) {
     return 0;
   }
 }

No tiene mucho sentido, ¿no? Si pasas una instancia de B a un método x que acepte un A, puedes acabar tener un DivideByCeroError a pesar de que x haya hecho las comprobaciones correctas.
El problema es que la instancia de B no actúa como una instancia de A, a pesar de que también es instancia de A (por ser instancia de una subclase de A).
El principio de Liskov añade que, además, se tiene que tener en cuenta la historia. Imagina que cada método de B cumple la implementación de A, con la excepción de que después de llamar a cada método de B debes llamar a un método reset(), o que los métodos de B se deben de llamar en determinado orden. Un código que espere usar instancias de A no tendrá en cuenta esas restricciones, lo que volverá a dar en resultados inesperados/erróneos.

A: Single Responsibility: cada objeto debe tener una única responsabilidad Open/Close: abierto para la extensión, clausurado ante cambios
Mas o menos quiere decir que cuando vallas a crear una clase esta solo tiene que tener los metodos que que sera utilizados en x funcionalidad. y no declarar todos los metodos que se van a utilizar en el sistema.
Este principio trata de destinar cada clase a una finalidad sencilla y concreta.
Interface Segregation: Este quiere decir que si un usuario no necesita una interfaz, no lo obliges a utilizarla.
Aca te dejo un link que explica muy bien los principios de solid
http://www.codeproject.com/Articles/703634/SOLID-architecture-principles-using-simple-Csharp

A: Single Responsability o SRP Cada objeto debe de tener una unica responsabilidad, esto puede ser traducido o aplicado como: Cada objeto debe de tener una unica razón para cambiar, para poder explicar esto mejor, veamos el siguiente ejemplo, supongamos que tenemos la siguiente clase Cliente que se encarga de almacenar a un cliente en la base de datos:
public class ServicioCliente
{
    private ClienteDb _clienteAccesoADatos = new ClienteDb();

    public void GuardarCliente(Cliente entidad)
    {
         if(!ValidarCliente(entidad))
              throw new InvalidOperationException("El cliente no es válido");

         _clienteAccesoADatos.Guardar(entidad)
    }

    public bool ValidarCliente(Cliente entidad)
    {
        bool resultado = true;
        if(string.IsNullOrWhiteSpace(entidad.Nombre))
           result &= false;
        if(string.IsNullOrWhiteSpace(entidad.Apellidos))
           result &= false;

        return resultado;
   }
}

En este caso nuestra clase hace 2 cosas:

*

*Verifica que el cliente es válido.

*Almacena el cliente en la base de datos.

Lo cual significa que si deseamos cambiar algo tenemos 2 razones para cambiar la clase por lo que estamos violando el principio de Responsabilidad Única (de ahora en mas SRP) En este caso lo que podemos hacer es dividir nuestra clase en dos clases. De esta forma:
public class ServicioCliente
{
    private ClienteDb _clienteAccesoADatos = new ClienteDb();
    private ValidadorCliente _validador = new ValidadorCliente();

    public void GuardarCliente(Cliente entidad)
    {
         if(!_validador.ValidarCliente(entidad))
              throw new InvalidOperationException("El cliente no es válido");

         _clienteAccesoADatos.Guardar(entidad)
    }
}

Internal class ValidadorCliente
{
    public bool ValidarCliente(Cliente entidad)
    {
        bool resultado = true;
        if(string.IsNullOrWhiteSpace(entidad.Nombre))
           result &= false;
        if(string.IsNullOrWhiteSpace(entidad.Apellidos))
           result &= false;

        return resultado;
   }
}

De esta forma ahora tenemos dos clases que tienen una sola razón para ser cambiadas.

*

*Cambiar el método de almacenamiento para el caso de Servicio cliente

*Cambiar el la forma de validación para el caso de ValidadorCliente

Si bien este principio normalmente se aplica a clases también puede ser aplicado a los métodos en una clase. Una buena forma de detectar si se está cumpliendo con el principio SRP es agregando comentarios de lo que hace un método/clase, veamos el siguiente ejemplo:
 public void GuardarCliente(Cliente entidad)
    {
         bool esValido = true;
         // Verifica si el cliente es válido
         if(string.IsNullOrWhiteSpace(entidad.Nombre)
              esValido = false;
         if(string.IsNullOrWhiteSpace(entidad.Apellidos)
             esValido = false;
         if(entidad.edad < 18)
             esValido = false;

         // Busca en la base de datos si el cliente existe
         Cliente cliente = __clienteAccesoADatos.ObtenerPrimero(entidad.Id);
         if(cliente != null)
                throw new InvalidOperationException("El cliente ya existe");

         if(!esValido)
               throw new InvalidOperationException("El cliente es inválido");
         // guarda el cliente
         _clienteAccesoADatos.Guardar(entidad)
    }

Como podemos observar en los comentarios esté metodo actualmente tiene 3 responsabilidades:

*

*Verificar que el cliente es válido

*Verificar si el cliente se encuentra en la base de datos

*Guardar al cliente en la base de datos

Por lo que también viola el SRP, en este caso como el anterior deberemos separar el método en métodos mas pequeños que tengan una sola responsabilidad y luego hacer lo propio con la clase.
Espero con esto se clarifique el principio de responsabilidad única. Respecto a los demás principios no tengo nada que agregar.
Saludos.


text:
Q: How to change the dimension of a component in a JFrame Suppose I have a JPanel in a JFrame. When I invoke a method that changes the preferred size of that JPanel, it does not change.
The code looks something like this:
public class SomePanel extends JPanel{

    public SomePanel(){
        setPreferredSize( new Dimension( 390, 40 ) );
        setBackground( Color.BLACK );
    }

    public void expand(){
        setPreferredSize( new Dimension( 390, 200 ) );
    }

    public static void main( String args[] ){
        JFrame frame = new JFrame();
        frame.setSize( 450, 500 );
        frame.setLayout( new FlowLayout() );

        SomePanel somePanel = new SomePanel();

        frame.add( somePanel );
        frame.setVisible( true );

        somePanel.expand();
    }
}

Is there something that I have to do first? I have tried so check the size of the JPanel when expand() is invoked. The height of the JPanel before and after setting the preferred size remains at 40.
I have also tried to use a Dimension variable, and that did not work either.
    Dimension dimension;

    public SomePanel(){
        dimension = new Dimension( 390, 40 );
        ...
    }

    public expand(){
        dimension.setSize( 390, 200 );
        setPreferredSize( dimension );
    }

A: Add frame.pack(); after somePanel.expand(); in your main() method. It will be done.

A: You need to invalidate the container hierarchy to make it re-layout the components.
Simply call invalidate followed by revalidate on the component you have changed.
Here's a small example...
public class TestComponentHierarcy {

    public static void main(String[] args) {
        new TestComponentHierarcy();
    }

    public TestComponentHierarcy() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(new Test());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class Test extends JPanel {

        private Dimension size = new Dimension(10, 10);

        public Test() {

            setLayout(new GridBagLayout());
            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    size.width += 10;
                    size.height += 10;
                    invalidate();
                    revalidate();
                }
            });

        }

        @Override
        public Dimension getPreferredSize() {
            return size;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.RED);
            g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
        }

    }

}

A: +1 to all.
I usually use a combination of:
revalidate() and pack(). (see @GagandeepBali and @StanislavL answer here for more reasoning as to my choice of revalidate()) as for pack() this allows for my JFrame to be sized to fit the contents.

*

*do not call setPreferredSize rather override getPreferredSize of JPanel.

*also do not call setSize(..) on JFrame use correct LayoutManager which adjusts to all added components size and than simply call pack() before setting JFrame visible.

*And lastly but not stressed enough warp creation and manipulation of Swing components in SwingUtilities.invokeXXX block / Event Dispatch Thread
Here is an example I made:
Basically a JPanel which overrides getPreferredSize and has a method setPanelSize(int w,int h) which changes variables in JPanel instance to return new Dimensions for getPreferredSize. after that I call revalidate() and pack() on JFrame to refelect changes:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Test {

    public Test() {
        initComponents();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Test();
            }
        });
    }

    private void initComponents() {
        final JFrame frame = new JFrame();
        frame.setTitle("Test");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final MyPanel myPanel = new MyPanel();
        final JButton changeSizeButton = new JButton("Change size to 300x300");

        changeSizeButton.addActionListener(new ActionListener() {
            boolean resized = false;

            @Override
            public void actionPerformed(ActionEvent ae) {
                if (resized) {
                    myPanel.setPanelSize(200, 200);
                    resized = false;
                    changeSizeButton.setText("Change size to 300x300");
                } else {
                    myPanel.setPanelSize(300, 300);
                    resized = true;
                    changeSizeButton.setText("Change size to 200x200");
                }

                frame.revalidate();
                frame.pack();

            }
        });
        frame.add(myPanel);
        frame.add(changeSizeButton, BorderLayout.SOUTH);

        frame.pack();
        frame.setVisible(true);
    }
}

class MyPanel extends JPanel {

    private int width, height;

    public MyPanel() {
        super(true);
        width = 200;
        height = 200;
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(width, height);
    }

    public void setPanelSize(int width, int height) {
        this.width = width;
        this.height = height;
    }
}


text:
Q: C fwrite error: mcleanup Codeblocks, C. I'm trying to write characters to a .txt file, using fwrite. The first couple of characters get written correctly, but after them the file says: _mcleanup: tos ov. I think it might be a buffer overload. Any ideas?
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    FILE*p1;

    p1=fopen("Tomi.txt","w+");

    fseek(p1,0,SEEK_SET);

   // fwrite("Toth Tamas",sizeof(char),30,p1);

    while(a<10)
        {
            fwrite("Toth Tamas",sizeof("Toth Tamas"),1,p1);

            a++;

        }

    return 0;
}

A: If I add int a = 0; immediately after FILE *p1;, the while-loop version of the program compiles without complaint, even with maximum warnings, and executes without error on my computer, even under valgrind.  You want sizeof("Toth Tamas") - 1 in the fwrite call to prevent NUL bytes from being written to the file, and maybe there should be an \n after "Tamas", and see my earlier comments for other minor problems, but that code seems mostly okay.
However, the commented-out line //fwrite("Toth Tamas",sizeof(char),30,p1); does have a bug: the string constant "Toth Tamas" is only 11 bytes long (counting the terminating NUL), but you have asked fwrite to write 30 bytes, so it will access 19 more bytes beyond the end of the string, triggering undefined behavior.  In context, one would expect either a segmentation fault, or garbage written to the file.
And "_mcleanup: tos ov" is 17 bytes long, so if that is (the beginning of) the next string constant in the read-only data segment of your executable, it's a plausible thing to show up as garbage written to the file, which I think is what you are saying happened.


text:
Q: Flutter Pub Get while pub get i reach this problem:
Because salut depends on flutter_block any which doesn't exist (could not find package flutter_block at https://pub.dartlang.org), version solving failed.

how can I resolve it?

A: It seems that the flutter_block package doesn't exist anymore on pub.dev, and therefore the maintener of the package salut need to push a new update of his dependency
If it's your package, you may have made a mistake between flutter_block and flutter_bloc


text:
Q: Rearranging divs between desktop and mobile I am creating a site but want to rearrange the order of the items on the page depending on whether it is on desktop or mobile.
So for desktop it is something like this:

And then for mobile I want to do something like:

All these items are their own divs, I just want a way to rearrange them.
Edit
This is really simplified everything is being generated by PHP.
My HTML at present is like so:

I want it to be something like:

A: In my cases, I have two options to solve this problem.
1. Render both mobile and desktop version and shows only one at a time. This is somehow a fast solution but not a professional way.
2. Using jquery or javascript.
so I assume that every div knows its order for both mobile and desktop cases.
and every divs width for both mobile and desktop are defined in CSS.
 let's define a div like this for example

 Menu1

 Search Bar

...

and in resize event or documentReady reorder the divs
window.onresize = function() {
    if (window.innerHeight <= 767) { /* Reorder divs for mobile cases */ }
    if (window.innerWidth > 767) {  /* Reorder divs for desktop cases */ }
}

For reordering divs, you can reference below links.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_sort_table


text:
Q: What is the best way to change WPF layout when orientation changes? My UI have to change with the orientation of the screen. Especially i have to change the grid.rows/columns-property and the allignment of my Controls. An animation of the position-change from my Controls would be nice but it doesn't have to.
Much more important for me is that i have an short and clearly arranged code.
I have some approaches but may be there are some more or better ways.

*

*I create an extra View for each orientation-state. (This generates double Code - may be not very good, or does it?)

*Something like Storyboard where i can change the position of controls with XAML. (i don't know how to change grid.row and alignment with storyboard - is it actually possible?)

*Change it by C#-code. (but I think this is not a proper WPF-style?)

May be with an Example.
Thx Stefan

A: For example, you can use RotateTransform in order to rotate your view when the orientation changes.
Another approach:
Since you were trying to work with Grid.Row and Grid.Column swapping, I'd rather recommend to use StackPanel, where you'd just need to set the Orientation dependency property to Horizontal or Vertical.
Note: You are right, I do not recommend either to use C# code in order to solve this, since it's a situation on the View side, not on the Model one. (Separation of Concerns.)


text:
Q: How to declaration username and password of the repositories when submit spark application My private repositories need username and password to visit.
I can't find a way to declaration the username and password when submit
bin/spark-submit --repositories   http://wx.bjdv.com:8081/nexus/content/groups/bigdata/ --packages com.databricks:spark-csv_2.10:1.2.0   --class org.apache.spark.examples.SparkPi   --master local[8]   examples/jars/spark-examples_2.11-2.0.1.jar   100

The rep http://wx.bjdv.com:8081/nexus/content/groups/bigdata/ need username and password


text:
Q: Deserializing json into object and dictionary I have a json below with nested data under "dependency" this could change at anytime. so it didnt make sense to create a class with individual strings to store the data. it could end up with more and more as time go on.
Sample Json
{
    "uniqueID": 13,
    "url": "www.abcde.com",
    "dependency": {
        "package1": "v1.0.3",
        "package2": "v5.4.2",
        "package3": "v12.3"
    },
    "assets": {
        "images": [
            "a.jpg",
            "b.jpg",
            "c.jpg",
            "d.jpg"
        ]
    }
}

My question is is there a way to deserialize the results into an object at the same time by creating a dictionary structure for "dependency" so I can get rid of the class and variables entirely?
My code that currently creates an object from the json.
    public class Dependency
    {
        public string package1 { get; set; }
        public string package2 { get; set; }
        public string package3 { get; set; }
    }

    public class Assets
    {
        public List<string> images { get; set; }
    }

    public class Root
    {
        public int uniqueID { get; set; }
        public string url { get; set; }
        public Dependency dependency { get; set; }
        public Assets assets { get; set; }
    }

    static void Main(string[] args){
        string jsonInput = File.ReadAllText(args[0]);
        Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(jsonInput);
    }

A: Try to change root to this
public class Root
    {
        public int uniqueID { get; set; }
        public string url { get; set; }
        public Dictionary<string, string> Dependency{ get; set; }
        public Assets assets { get; set; }
    }


text:
Q: If $G$ is a connected planar graph then with at least three vertices, $e$ edges and $r$ regions, prove that $e \leq 3n - 6$. (source)
Lemma 5.8.4. In a planar embedding of a connected graph, each edge is traversed once by each of two different regions, or is traversed exactly twice by one region.
Lemma 5.8.5. In a planar embedding of a connected graph with at least three vertices, each region is of length at least three.
Suppose a connected planar graph has $v\geq 3$ vertices and $e$ edges. Then
$$e\leq 3v−6.$$
Proof. By definition, a connected graph is planar iff it has a planar embedding. So suppose a connected graph with v vertices and e edges has a planar embedding with r region. By Lemma 5.8.4, every edge is traversed exactly twice by the region boundaries. So the sum of the lengths of the region boundaries is exactly 2e. Also by Lemma 5.8.5, when v≥3, each region boundary is of length at least three, so this sum is at least 3r . This implies that
3r≤2e
But r=e−v+2 by Euler's formula, and substituting into the above gives
3(e−v+2)≤2e
=e−3v+6≤2e
=e≤3v−6
My question is that "sum of the lengths of the region boundaries is exactly 2e" doesn't quite makes sense. How can I understand the "2e" part according to number of edges, cause it looks like 2e should be total/maximum number of regions if we have e edges in a graph and each edge contributes to 2 regions.


text:
Q: How can I hardreset a modem or the port under Linux? I have a device (a modem) connected to a USB port (/dev/ttyACM0, Ubuntu 12.04) to dial a phone number, which only works if I perform the ultimate reset (taking device out of USB port, waiting some seconds and plug it in again).
My question: Is it possible to solve this on Linux by software, i.e. to 'reset' the modem as if it has been plugged out or to reset the USB port itself (disconnect power?), so the modem is being reset as it has been plugged out and in again?

A: I think long time ago there was a way to switch off USB devices by software only. Then people started to fiddle with power of USB disks screwing the USB driver stack. After all the kernel gods removed software switch off capabilities.
The only way I currently know about to completely power off USB devices is a hybrid hard- and software solution:
Hard Reset USB in Ubuntu 10.04


text:
Q: Adding login account My Stack Overflow account is integrated to my university account which is now blocked because I have graduated. I want to add a new email id to my current account because I can't login to new devices anymore. I use Firefox to visit Stack Overflow, but Firefox shows me an error:

Stack Overflow needs to access JavaScript from another domain. Which is not found or failed to load.

I can't post questions, etc. and can't add a new email address because some buttons here trigger JavaScript, so buttons don't work. I can't change my browser because then logging in would be a problem because my email is blocked. I'm posting the question from the Android app. What should I do?


text: Q: How to insert html file in lotus notes when a user click the image I have a image called "Send greeting card" in my HTML file. when a user clicks that image, it should open lotus notes and insert the html file. Any idea of doing this in HTML/Classic ASP.


text:
Q: How to check if file exists in Apache I've set this up successfully in IIS in the past, but i'm not sure how to do it in Apache.  I want to check to see if a file exists, whether it be:
/path/to/file.php
/path/to/file.cfm
/path/to/file.html
/path/to/

If the file does not exist, I want to redirect to /404/, where I have a file that does all 404 related handling.
Lastly, when doing this in IIS, it gave me a CGI.QUERY_STRING of something like:
404;http://example.com/prettyurl

Can apache do the same?
This is what i've tried to so far, to no success.  (I'm probably way off here...)
RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_URI} -f
RewriteRule (.*)$ /404/ [R,L,NC]

Thanks..

A: Don't use the document_root slash..., simply do REQUEST_FILENAME !-f
Exclamation mark negates the -f flag.


text:
Q: How to adjust this query to show average goals per game, rather than total goals scored? I have the following query:
select u.user_name, sum(goals)
from ((select player1_id as player, player1_goals as goals from results
where community_id = 16 )
union all (select player2_id as player, player2_goals as goals from
results where community_id = 16 ) ) p
join users u on p.player = u.id
group by player order by sum(goals)

which produces a result such as:
+----------+------------+
| user_name| sum(goals) |
+----------+------------+
| Player 1 |    9       |
| Player 2 |    7       |
| Player 3 |    4       |
+----------+------------+

This query is based on the following:
results table:
+---------------+
| results_id    |
| community_id  |
| player1_id    |
| player1_goals |
| player2_id    |
| player2_goals |
+---------------+

And users table:
+---------+
|   id    |
+---------+
|user_name|
+---------+

My issue is as follows:
Each player in the queried table has played a different number of the games, so rather than displaying how many goals each player has scored, I want to show the average number of goals scored per game.
My desired output is:
+----------+-----------+-----------------+
| user_name| sum(goals) | goals per game |
+----------+------------+----------------+
| Player 1 |    9       |       1.3      |
| Player 2 |    7       |       0.9      |
| Player 3 |    4       |       0.4      |
+----------+------------+----------------+

How can I adjust my initial query to show an average of goals per game rather than just goals scored?

A: Try this:
select u.user_name,
    sum(r.goals) total_goals,
round(  sum(r.goals)/count(1), 2) avg_goals
from (select
    community_id,
    player1_id id,
    player1_goals goals
from results
union all
select
    community_id,
    player2_id,
    player2_goals
from results) r
inner join users u
on r.id = u.id
where r.community_id = 16
group by r.id, u.user_name
order by avg_goals desc;


text:
Q: Function takes wrong variable python I need to change a variable each time the function is called.
My function counts the number of time this function has been called:
def score_chart():
    num_of_charts=+ 1
    return num_of_charts

At the beginning num_of_charts equals 0. Then I call the function and re-save num_of_charts to be equal 1.
But if I call it second time, the result is still 1, while I m expecting to get 2.
num_of_charts = 0
num_of_charts = score_chart()
print (num_of_charts)
num_of_charts = score_chart()
print(num_of_charts)

1
1

Could you please help

A: Use a parameter to get the old value.
def score_chart(num):
    return num + 1

num_of_charts = 0
num_of_charts = score_chart(num_of_charts)
print(num_of_charts)
num_of_charts = score_chart(num_of_charts)
print(num_of_charts)

A: A general and useful way to count calls to any function is to define and use a function decorator. The decorator function maintains a count of the calls and this can be accessed whenever required.
def call_counter(func):
    def keeper():
        keeper.calls += 1
        return func()
    keeper.calls = 0
    return keeper

@call_counter
def score_chart():
    pass   # function could do anything required

for i in range(4):
    score_chart()
print(score_chart.calls)

which prints 4

A: METHOD 1:
You can use global variables for them to be accessible everywhere in the code (sometimes can be a bad practice)
Code:
def score_chart():
    global num_of_charts
    num_of_charts += 1

METHOD 2:
You can use num_of_charts as a function argument and return it at the end of the function (you need to store that value in another variable outside the function)
Code:
def score_chart(num_of_charts):
    num_of_charts += 1
    return num_of_charts

new_num = score_chart( # put a number here )

After 1st function call you have to pass that new_num as an argument and overwrite it with another value (only if you don't need to go back to previous values)
new_num = score_chart( # put a number here )

new_num = score_chart(new_num)

Also keep in mind that it is += 1 and not =+ 1

A: The statement: My function counts the number of times this function has been called:
def score_chart():
    num_of_charts=+ 1
    return num_of_charts

is not true. Your function assigns to num_of_charts the value + 1.
What you actually intended to do is to increase the value by one using num_of_charts += 1 but had put the + at the right side of = instead of the left side.
This is the reason why the returned result was always 1.
In addition to this above you need to know that in Python it is important to be aware of the local and global scope of variable names used in a function (check out the docs on it). Not being aware of that leads very often to confusion and wrong expectations. stackoverflow is full of questions which resulted from this kind of confusion.
As long as you only use a variable name in a function it will represent the global value assigned outside of the function before calling it. This is the reason why:
def score_chart_1():
    return num_of_charts

is able to return the current value assigned to num_of_charts outside the function so that:
num_of_charts = 2
print(score_chart_1())
num_of_charts = 3
print(score_chart_1())

will print 2 and 3.
If you in your function try to assign a value to a variable name using num_of_charts += 1 the variable name changes its scope from global to local in the function.
Notice that num_of_charts += 1 is equivalent to num_of_charts = num_of charts + 1 and Python needs to know the value of num_of_charts to increase it by one. But usage of the assignment operator = with num_of_charts changed the scope of num_of_charts to local where num_of_charts does not yet have a value and because of that an:
UnboundLocalError: local variable 'num_of_charts' referenced before assignment

will be raised.
The Error can be avoided by declaring the scope of a variable to be global in the function using as first function statement (as first is the usual convention in Python):
global num_of_charts

With this statement above there will be no UnboundLocalError and the function will then work as expected.
Even is this changes will solve your problem this kind of solution is considered to be a bad programming style and the approach of passing a counter parameter to the function and updating it with the return value in order to pass the changed value on next function call a better one (see the answer posted by Barmar for code of this approach).
Best approach to achieve what you want would be to use a Python class where it would easily be possible to count any function calls. See code below for an example of code (choice of variable names should be sufficient as explanations what the code does):
class Charts:
    def __init__(self, list_with_charts):
         self.list_with_charts = list_with_charts
         self.list_with_scores = [0]*len(list_with_charts)

    def score_chart(self, chart_index):
        return self.list_with_scores[chart_index]

    def show_chart(self, chart_index):
        # some code to present/show the chart
        self.list_with_scores[chart_index] += 1

objCharts = Charts(['chart0.ppt', 'chart1.ppt', 'chart2.ppt'])
objCharts.show_chart(0)
objCharts.show_chart(0)
objCharts.show_chart(2)
objCharts.show_chart(2)
objCharts.show_chart(2)

print(objCharts.score_chart(2)) # gives 3

For the sake of completeness it is worth to mention two another kinds of approaching counting function calls (see the first version of the answer by user19077881 in the history of edits):

*

*using a function closure

*using a function decorator

Notice that if your intention would be to only count calls to a function somehow 'hiding' the fact of counting, the function closure would be probably the best way to go.


text:
Q: LG Ultrafine 5k -- right half is a slightly different color from left New refurbished model # 27MD5KA. I have attached a photo (apologies for the reflections).

There is a line down the exact middle of the screen, directly below the webcam. On the right side of the screen the panel is slightly lighter than the left side (or the left is slightly darker -- I'm not sure which is the 'correct' color/brightness). You can tell very clearly in Intellij IDEA in the default darcula color scheme. It's harder to tell on light backgrounds.
I'm guessing this has something to do with the dual display port 1.2 streams that the monitor uses.
Is there any way to color correct this?
Thanks!

A: I've been having this issue for quite some time. Usually, a reboot would make it go away, but recently it has become much more persistent. One workaround I found was to turn on Night Shift but set it all the way to the "Less Warm" side.
It looks like an issue with macOS. I have filed a bug report to Apple.


text:
Q: Accessing fields of created features in your PyQGIS I'm new using PyQGIS 3 and I'm wondering how to access the field information from a layer generated by script.
Inside my processAlgorithm function I have the following:
alg_params = {
    'EXPRESSION': parameters[self.IN_EXPRESSION],
    'INPUT': parameters[self.IN_SHP],
    'OUTPUT': parameters[self.OUT_SHP]
}

final_output = processing.run('native:extractbyexpression', alg_params, context=context, feedback=feedback, is_child_algorithm=True)['OUTPUT']

output_lyr = QgsVectorLayer(final_output, "output_testing", "ogr")

fields = output_lyr.fields()
fieldnames = [field.name() for field in fields]
print(fieldnames)

return {"result": final_output }

The algorithm itself is returning the right output, however I'm not able to access the fields during inside the code, the print is returning me a empty list, however my final_output DO have fields.
Someone, could give me a glimpse of what I've missed?

A: Normally, when using a vector tool, processing.run with TEMPORARY_OUTPUT returns ["OUTPUT": QgsVectorLayer]. If is_child_algorithm=True is added, it returns a temporary layer id.
The reference of a temporary layer can be obtained by means of context.temporaryLayerStore(). You can add the following lines to your processing script to get the temporary layer's reference.
import os
# ... other imports

class ExampleProcessingAlgorithm(QgsProcessingAlgorithm):
    # ... other stuffs

    def processAlgorithm(self, parameters, context, feedback):
        # ... previous lines

        final_output = processing.run('native:extractbyexpression',
                                      alg_params, context=context, feedback=feedback,
                                      is_child_algorithm=True)['OUTPUT']

        # check output type
        if isinstance(final_output, str):
            # check if a file path
            if os.path.isfile(final_output):
                output_lyr = QgsVectorLayer(final_output, "output_testing", "ogr")
            else: # if not a path, then it is a temporary layer's ID
                output_lyr = context.temporaryLayerStore().mapLayers()[final_output]
        # possible QgsVectorLayer if "is_child_algorithm=True" is not used
        elif isinstance(final_output, QgsVectorLayer):
            output_lyr = final_output
        else:
            raise ValueError('A very specific bad thing happened.')

        print([f.name() for f in output_lyr.fields()])

        return {"OUTPUT": final_output}

A: Use final_output['OUTPUT'] since the output is saved in a dictionary:
output_lyr = QgsVectorLayer(final_output['OUTPUT'], "output_testing", "ogr")


text:
Q: Storing object-graphs with class-evolution in Java with transformation (long time archiving) Abstract
A common problem is to store objects (with graph), and to load them back. This is easy as long the stored object representation matches the executing code. But as time goes by, requirements change and stored objects do not match any longer the code. The stored objects should not loose their data, and the code in the clients should work with the latest object-models.
So a transformation has to occur somehow between loading the data and returning a object to the client.
I know that there exist some libraries such as XStream, gson, protobuf and avro. They could load older objects, but afaik just ignore data that does not match any longer the fields in the class (maybe I missed something).
(When I'm talking about storing and serialization I do not mean Java's built in serialization mechanism.)
Question
So what is the question? I'm now researching for some time, and there seems no library that adresses this issue (class evolution) without data-loss. I hope to find another working solution or idea how to implement it by myself here.
I have some requirements:

*

*File-based - I want to be able to store the serialized object on disk

*Appendable - I want to append multiple objects to one file without loading the whole file in memory again and again

*Support for multiple versions in one file - A file could contain objects with different version (only of the same type)

*Transformation - Data should be accessible by using the same type, even when changed in between.

*Generic - The mechanism itself has to be generic, so I could use it for different objects (different objects do not get mixed in one file, only different versions of one type).

It would be nice if the storing format is human-readable.
Already stored objects are not updateable (at least not without huge effort). Think of an long-term archive.
Example
I could give an example for better illustration. Let's suppose we have two Pojos that we want to serialize.
public class MyPojo {
    String text;
    Long number;
    Integer[] values;
    SubPojo pojo;
}

public class SubPojo {
    List<String> items;
}

In the next version we might have renamed a field (text->content), changed a type (Integer[]->List), and have transformed a field to List (SubPojo->List) where the previous field now is the first element of the new list (not loosing data, just transforming to new representation).
public class MyPojo {
    String content;
    Long number;
    List<Integer> values;
    List<SubPojo> pojo;
}

public class SubPojo {
    List<String> items;
}

Some pseudocode how the client might take use of this:
// Write
Serializer ser = new Serializer();
MyPojo pojo = new MyPojo();
pojo.xxx = ...; // set fields
ser.store(pojo, file, append);

// Read (a version later)
Serializer ser = new Serializer();
ser.registerTransformer(new TransformerV1ToV2());
List<MyPojo> pojos = ser.load(file);

This approach has some drawbacks:

*

*The transformer have to work on some kind of intermediate format (could be the backed stored format such as json or xml)

*You don't know how the class format was at some point in time, since you're only transforming relative to the previous version and mapping to the final class, making search for errors hard

*Performance (depending on how the transformation happens)

A: I use the Externalizable interface to solve this problem.  It doesn't really meet your Appendable requirement, but it might get you started.
Externalizable lets you write each object out yourself.  What I do is include a version number for each class.  Then, when I change the class, I adjust the readExternal method so it can can read the new format as well as the old ones and change the writeExternal method to write the new format with the new version number.  The code to read old formats may need to change to fill new fields (and not fill in removed fields).  Then I'm ready to go.
There's usually some sort of object hierarchy in the graph, so if a level 2 class is seriously modified, the new write/read for that class can output/input something completely different from the old one, with completely new lower-level classes.
Some care is needed because sometimes there isn't a hierarchy.  You have to remember that, after reading, you can't set a field by pulling data from objects in fields because they may not really be there yet.  (Sometimes I add a setUp method to all my classes that gets called after the top-level objectRead so the objects in the graph can get themselves organized after the whole graph has been read.
And it sometimes helps to write out objects manually using a method that just writes out plain bytes.  (But on the read you have to know precisely what you are reading, where readExternal will read a complete object of any class.)
Code looks something like:
// version 3 -- November 16, 2013
// version 2 -- March 22, 2013
// version 1 -- April 1, 2012
public void writeExternal( ObjectOutput out )  throws IOException  {
    out.writeShort( 3 )
    out.writeLong( longData );
    out.writeObject( something );
    ....
}

public void readExternal( ObjectInput in )  throws IOException,
             ClassNotFoundException  {
    short version = in.readShort();
    if (version > 3)  {
        // Admit program is too old to read file.
    }
    else if (version == 3)  {
        longData = in.readLong();
        something = readobject();
    }
    else if (version == 2)  {
        longData = 5;
        something = readobject();
    }
    else
       ...
}

A: I decided to use the transformation approach. JSON is used as intermediate-format, this way I can ensure the correctness using Json Schema between versions (optional).
Conceptional you can think in two ways if you like: As object-mapper, or as json-format that is expressed in java-objects.
I open-sourced my solution at http://github.com/galan/verjson
The documentation will be extended in the next time. I also added support for custom-serializer/deserializer and polymorph types.

A: I would start by creating a class of general-purpose serializable objects that are capable of standing in for any object that needs to be serialized. Each object would contain a representation of every field that needs to be serialized, and the type and version of the object. You may want to use JSON or something similar for this part.
Each serializable class would need a constructor that takes a general-purpose object and throws an exception if the type, version, or fields don't match what the class needs. For the other direction each class would need a method that converts an object of that class into a general-purpose object. If you want your serialization to include multiple references to a single object then you can pass around an additional object to take care of mapping between POJOs and general-purpose objects.
Finally each serializable class needs a static method for converting from old versions to the current version. For the first version this would do nothing, but every time you modify the class you would increment the current version and add a conversion step that converts a general-purpose object for the previous version into a general-purpose object for the new version. You could have a switch statement with no breaks that switches on the version of the given object. The first case would convert an object of the first version into an object of the second version, followed by a case for converting the second version into the third version, and then you can fall all the way through until you have an object of the current version at the bottom. Each new version just requires adding a single case to the bottom of the switch statement that represents the changes that have been made.


text:
Q: Use cake to perform git commit without name and email The cake GitCommit alias wants a name and email:
public static GitCommit GitCommit(this ICakeContext context, DirectoryPath repositoryDirectoryPath, string name, string email, string message)

How can I commit without specifying them (and it would use the repo's defaults)?
For example, the same as I can do in the shell: $ git commit -m message.

A: I found a reasonable workaround:
var name  = GitConfigGet<string>(repoDirectory, "user.name"));
var email = GitConfigGet<string>(repoDirectory, "user.email");

GitCommit(repoDirectory, name, email, "message");

A: The git cli does a lot a of things other clients might or might not do.
Cake.Git uses libgit2sharp to provide access to git. libgit2sharp, in turn, uses libgit2.
libgit2 requires a username and email to be explicitly specified when adding a commit and so does Cake.Git.
You can, as you wrote in your answer, check the config for existing values, but I would strongly suggest checking them not to be empty, before using them.


text:
Q: Having a varying character in a regex with 2 options I use regex to define a URL using gorilla mux:
/v2/operations/{operation:(?:ACC00000)\\d+}/meters

This URL initially had to match ACC00000xxx where xxx is an integer. This regex is working. ( for ACC00000354 for instance)
Now the third character can also be a I. I tried replacing it with ?, or changing it with [C|I] but I can't make it match with the two options:

*

*ACC00000123

*ACI00000234
Any idea why is it failing?

A: You need this
AC[CI]00000\d+

"?" denotes that the character is present one or zero times. ? does NOT mean any character. "[CI]" means of of two characters C or I should match.  Any character is denoted by a dot ".". This would also work
AC.00000\d+

https://regex101.com/r/UKHGFo/1
https://regex101.com/r/UKHGFo/2

A: [C|I] this mean to match C or | or I
You should use (?:C|I) or (?:(?:ACC|ACI)00000))


text:
Q: Overloading generic type parameters disallowed? It's part curiosity and part because I was just trying to use this. If you have the following definitions, this is not allowed by the compiler because it says that the member is already defined. What's the reasoning behind not allowing exclusive overloads of generic type parameters?
void Get<T>() where T: struct {}
void Get<T>() where T: class {}

It seems to me that there's no inherent problem with this. One might argue that it is not always clear which the compiler should choose in cases where the definitions overlap (but a common resolution seems to be most specific match first).
Can someone help me understand  or point to a resource what the reasoning is behind disallowing this?

A: Eric Lippert already answered this one, in a blog post on generic constraints and method signatures: http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx
Constraints on generic types are not part of method signatures in the CLR, therefore you can't have two methods that differ only in generic type constraints. Without CLR support it would be quite fiddly to get C# to support these in a sensible fashion that is compatible with other .NET languages.

A: The struct constraint on Nullable<T> is IMHO really unfortunate.  Something like a Nullable<String> or a Nullable<Nullable<Nullable<int>>> might be have wasteful, but so what?  Box the former as its content; unbox it as its content and set the HasValue if the content is non-null.  Box the former as an int if all of the nullables report HasValue, and when unboxing, set HasValue of all nested items if the content was non-null.
Otherwise, I would suggest that you create a static generic class with type parameter T which contains a delegate property that accepts a T as a parameter.  The property should return the content of a private field which should be initialized to point to a method that will check the type of T and set the delegate to either the struct or class version as appropriate.
Here's a sample of what I'm talking about; this one uses various interface constraints rather than struct/class constraints, but the same principles can be used just as effectively.

        static class _FooDispatcher<T>
        {
            public static Action<T> Foo = setupFoo;

            static void doFooWithIGoodFoo<TT>(TT param) where TT : IGoodFoo
            {
                Console.WriteLine("Dispatching as IGoodFoo with {1} type {0}", typeof(TT).ToString(), typeof(TT).IsValueType ? "value" : "reference");
                param.Foo();
            }
            static void doFooWithIOkayFoo<TT>(TT param) where TT : IOkayFoo
            {
                Console.WriteLine("Dispatching as IOkayFoo with {1} type {0}", typeof(TT).ToString(), typeof(TT).IsValueType ? "value" : "reference");
                param.Foo();
            }
            static void doFooSomehow<TT>(TT param)
            {
                Console.WriteLine("Nothing exciting with {1} type {0}", typeof(TT).ToString(), typeof(TT).IsValueType ? "value" : "reference");
            }
            static void setupFoo(T param)
            {
                System.Reflection.MethodInfo mi;
                if (typeof(IGoodFoo).IsAssignableFrom(typeof(T)))
                    mi = typeof(_FooDispatcher<T>).GetMethod("doFooWithIGoodFoo", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
                else if (typeof(IOkayFoo).IsAssignableFrom(typeof(T)))
                    mi = typeof(_FooDispatcher<T>).GetMethod("doFooWithIOkayFoo", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
                else
                    mi = typeof(_FooDispatcher<T>).GetMethod("doFooSomehow", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
                Foo = (Action<T>)(@Delegate.CreateDelegate(typeof(Action<T>), mi.MakeGenericMethod(typeof(T))));
                Foo(param);
            }
        }


text:
Q: Elementarmatrices to get row-echolon-form I need to determine the Elementarmatrice(s) that satisfy:
$M_1M_2...M_nA=B$ where B is in row echolonform
but has the same dimension then A.
So basicly how do you describe swapping of lines, or substracting some with matrices?

A: Hint: Think about what happens when you multiply $A$ on the left by a row vector, i.e., a $1\times n$ matrix—the result is a linear combination of the rows of $A$. As a special case of this, multiplying by the vector that has a $1$ in the $k$th column and zeros everywhere else "picks out" the $k$th row of $A$. When you multiply $A$ by some multi-row matrix $M$, that's the same as multiplying by a series of row vectors, one for each row of $M$.


text:
Q: Why can't I run conda command even though it is slready installed in the machine? user_name@server_name:~/bbq_spatial$ pip show conda
Name: conda
Version: 4.3.16
Summary: OS-agnostic, system-level binary package manager.
Home-page: https://github.com/conda/conda
Author: Continuum Analytics, Inc.
Author-email: conda@continuum.io
License: BSD
Location: /home/user_name/.local/lib/python3.9/site-packages
Requires: pycosat, requests, ruamel.yaml
Required-by:
user_name@server_name:~/bbq_spatial$ conda update conda
conda: command not found
user_name@server_name:~/bbq_spatial$

Why can't I run conda command even though it is slready installed in the machine?
How can I run conda command?
EDIT:

Add the output of command -v pip and command -v conda to the question. – Nasir Riley

user_name@server_name:~$ command -v pip
/usr/local/bin/pip
user_name@server_name:~$ command -v conda
user_name@server_name:~$ command -v conda
user_name@server_name:~$

A: What you have installed is the conda Python module that you'd import in a Python shell like any other module.
If you want the conda binary that's used as an application, then you need install install Anaconda or Miniconda which you can get from the following sites:
https://www.anaconda.com/products/distribution#Downloads
https://docs.conda.io/en/latest/miniconda.html
There are instructions on those sites and Google for installing either one if you need help.


text:
Q: ensure embed code (iframe) is only used on customer web sites I have a service and would like clients to be able to place this service on their website. I am looking at doing this by using an iframe. I will provide the code and they can just copy and paste the code to show the functionality. Each client will be discovered by the query string.
There is a concern that anyone can look at the source of the website, copy the iframe and add it to their own website therefore using the service and charging the original client. I obviously want to stop this.
Ideally, I would like to verify that the website that is using the iframe is linked to the client who registered to use the service. Is this possible at all? I know there are issues with cross domain security.
If it isn't possible, I guess I would need to create a widget instead.

A: For each client, have a whitelist of web sites that can embed the iframe. Then check the 'referer' header against that list whenever the page inside the iframe is loaded.
Or if http headers prove to be unreliable try using javascript, via parent.document.location.href


text:
Q: Group and count over a start and end range If I have data in the following format:
[
  {
    _id: 1,
    startDate: ISODate("2017-01-1T00:00:00.000Z"),
    endDate: ISODate("2017-02-25T00:00:00.000Z"),
    type: 'CAR'
  },
  {
    _id: 2,
    startDate: ISODate("2017-02-17T00:00:00.000Z"),
    endDate: ISODate("2017-03-22T00:00:00.000Z"),
    type: 'HGV'
  }
]

Is it possible to retrieve data grouped by 'type', but also with a count of the type for each of month in a given date range e.g. between 2017/1/1 to 2017/4/1 would return:
[
  {
   _id: 'CAR',
   monthCounts: [
     /*January*/
     {
       from: ISODate("2017-01-1T00:00:00.000Z"),
       to: ISODate("2017-01-31T23:59:59.999Z"),
       count: 1
     },
     /*February*/
     {
       from: ISODate("2017-02-1T00:00:00.000Z"),
       to: ISODate("2017-02-28T23:59:59.999Z"),
       count: 1
     },
     /*March*/
     {
       from: ISODate("2017-03-1T00:00:00.000Z"),
       to: ISODate("2017-03-31T23:59:59.999Z"),
       count: 0
     },
   ]
  },
  {
   _id: 'HGV',
   monthCounts: [
     {
       from: ISODate("2017-01-1T00:00:00.000Z"),
       to: ISODate("2017-01-31T23:59:59.999Z"),
       count: 0
     },
     {
       from: ISODate("2017-02-1T00:00:00.000Z"),
       to: ISODate("2017-02-28T23:59:59.999Z"),
       count: 1
     },
     {
       from: ISODate("2017-03-1T00:00:00.000Z"),
       to: ISODate("2017-03-31T23:59:59.999Z"),
       count: 1
     },
   ]
  }
]

The returned format is not really important, but what I am trying to achieve is in a single query to retrieve a number of counts for the same grouping (one per month).  The input could be simply a start and end date to report from or more likely it could be an array of the date ranges to group by.

A: The algorithm for this is to basically "iterate" values between the interval of the two values. MongoDB has a couple of ways to deal with this, being what has always been present with mapReduce() and with new features available to the aggregate() method.
I'm going expand on your selection to deliberately show an overlapping month since your examples did not have one. This will result in the "HGV" values appearing in "three" months of output.
{
        "_id" : 1,
        "startDate" : ISODate("2017-01-01T00:00:00Z"),
        "endDate" : ISODate("2017-02-25T00:00:00Z"),
        "type" : "CAR"
}
{
        "_id" : 2,
        "startDate" : ISODate("2017-02-17T00:00:00Z"),
        "endDate" : ISODate("2017-03-22T00:00:00Z"),
        "type" : "HGV"
}
{
        "_id" : 3,
        "startDate" : ISODate("2017-02-17T00:00:00Z"),
        "endDate" : ISODate("2017-04-22T00:00:00Z"),
        "type" : "HGV"
}

Aggregate - Requires MongoDB 3.4
db.cars.aggregate([
  { "$addFields": {
    "range": {
      "$reduce": {
        "input": { "$map": {
          "input": { "$range": [
            { "$trunc": {
              "$divide": [
                { "$subtract": [ "$startDate", new Date(0) ] },
                1000
              ]
            }},
            { "$trunc": {
              "$divide": [
                { "$subtract": [ "$endDate", new Date(0) ] },
                1000
              ]
            }},
            60 * 60 * 24
          ]},
          "as": "el",
          "in": {
            "$let": {
              "vars": {
                "date": {
                  "$add": [
                    { "$multiply": [ "$$el", 1000 ] },
                    new Date(0)
                  ]
                },
                "month": {
                }
              },
              "in": {
                "$add": [
                  { "$multiply": [ { "$year": "$$date" }, 100 ] },
                  { "$month": "$$date" }
                ]
              }
            }
          }
        }},
        "initialValue": [],
        "in": {
          "$cond": {
            "if": { "$in": [ "$$this", "$$value" ] },
            "then": "$$value",
            "else": { "$concatArrays": [ "$$value", ["$$this"] ] }
          }
        }
      }
    }
  }},
  { "$unwind": "$range" },
  { "$group": {
    "_id": {
      "type": "$type",
      "month": "$range"
    },
    "count": { "$sum": 1 }
  }},
  { "$sort": { "_id": 1 } },
  { "$group": {
    "_id": "$_id.type",
    "monthCounts": {
      "$push": { "month": "$_id.month", "count": "$count" }
    }
  }}
])

The key to making this work is the $range operator which takes values for a "start" and and "end" as well as an "interval" to apply. The result is an array of values taken from the "start" and incremented until the "end" is reached.
We use this with startDate and endDate to generate the possible dates in between those values. You will note that we need to do some math here since the $range only takes a 32-bit integer, but we can take the milliseconds away from the timestamp values so that is okay.
Because we want "months", the operations applied extract the month and year values from the generated range. We actually generate the range as the "days" in between since "months" are difficult to deal with in math. The subsequent $reduce operation takes only the "distinct months" from the date range.
The result therefore of the first aggregation pipeline stage is a new field in the document which is an "array" of all the distinct months covered between startDate and endDate. This gives an "iterator" for the rest of the operation.
By "iterator" I mean than when we apply $unwind we get a copy of the original document for every distinct month covered in the interval. This then allows the following two $group stages to first apply a grouping to the common key of "month" and "type" in order to "total" the counts via $sum, and next $group makes the key just the "type" and puts the results in an array via $push.
This gives the result on the above data:
{
        "_id" : "HGV",
        "monthCounts" : [
                {
                        "month" : 201702,
                        "count" : 2
                },
                {
                        "month" : 201703,
                        "count" : 2
                },
                {
                        "month" : 201704,
                        "count" : 1
                }
        ]
}
{
        "_id" : "CAR",
        "monthCounts" : [
                {
                        "month" : 201701,
                        "count" : 1
                },
                {
                        "month" : 201702,
                        "count" : 1
                }
        ]
}

Note that the coverage of "months" is only present where there is actual data. Whilst possible to produce zero values over a range, it requires quite a bit of wrangling to do so and is not very practical. If you want zero values then it is better to add that in post processing in the client once the results have been retrieved.
If you really have your heart set on the zero values, then you should separately query for $min and $max values, and pass these in to "brute force" the pipeline into generating the copies for each supplied possible range value.
So this time the "range" is made externally to all documents, and you then use a $cond statement into the accumulator to see if the current data is within the grouped range produced. Also since the generation is "external", we really don't need the MongoDB 3.4 operator of $range, so this can be applied to earlier versions as well:
// Get min and max separately
var ranges = db.cars.aggregate(
 { "$group": {
   "_id": null,
   "startRange": { "$min": "$startDate" },
   "endRange": { "$max": "$endDate" }
 }}
).toArray()[0]

// Make the range array externally from all possible values
var range = [];
for ( var d = new Date(ranges.startRange.valueOf()); d <= ranges.endRange; d.setUTCMonth(d.getUTCMonth()+1)) {
  var v = ( d.getUTCFullYear() * 100 ) + d.getUTCMonth()+1;
  range.push(v);
}

// Run conditional aggregation
db.cars.aggregate([
  { "$addFields": { "range": range } },
  { "$unwind": "$range" },
  { "$group": {
    "_id": {
      "type": "$type",
      "month": "$range"
    },
    "count": {
      "$sum": {
        "$cond": {
          "if": {
            "$and": [
              { "$gte": [
                "$range",
                { "$add": [
                  { "$multiply": [ { "$year": "$startDate" }, 100 ] },
                  { "$month": "$startDate" }
                ]}
              ]},
              { "$lte": [
                "$range",
                { "$add": [
                  { "$multiply": [ { "$year": "$endDate" }, 100 ] },
                  { "$month": "$endDate" }
                ]}
              ]}
            ]
          },
          "then": 1,
          "else": 0
        }
      }
    }
  }},
  { "$sort": { "_id": 1 } },
  { "$group": {
    "_id": "$_id.type",
    "monthCounts": {
      "$push": { "month": "$_id.month", "count": "$count" }
    }
  }}
])

Which produces the consistent zero fills for all possible months on all groupings:
{
        "_id" : "HGV",
        "monthCounts" : [
                {
                        "month" : 201701,
                        "count" : 0
                },
                {
                        "month" : 201702,
                        "count" : 2
                },
                {
                        "month" : 201703,
                        "count" : 2
                },
                {
                        "month" : 201704,
                        "count" : 1
                }
        ]
}
{
        "_id" : "CAR",
        "monthCounts" : [
                {
                        "month" : 201701,
                        "count" : 1
                },
                {
                        "month" : 201702,
                        "count" : 1
                },
                {
                        "month" : 201703,
                        "count" : 0
                },
                {
                        "month" : 201704,
                        "count" : 0
                }
        ]
}

MapReduce
All versions of MongoDB support mapReduce, and the simple case of the "iterator" as mentioned above is handled by a for loop in the mapper. We can get output as generated up to the first $group from above by simply doing:
db.cars.mapReduce(
  function () {
    for ( var d = this.startDate; d <= this.endDate;
      d.setUTCMonth(d.getUTCMonth()+1) )
    {
      var m = new Date(0);
      m.setUTCFullYear(d.getUTCFullYear());
      m.setUTCMonth(d.getUTCMonth());
      emit({ id: this.type, date: m},1);
    }
  },
  function(key,values) {
    return Array.sum(values);
  },
  { "out": { "inline": 1 } }
)

Which produces:
{
        "_id" : {
                "id" : "CAR",
                "date" : ISODate("2017-01-01T00:00:00Z")
        },
        "value" : 1
},
{
        "_id" : {
                "id" : "CAR",
                "date" : ISODate("2017-02-01T00:00:00Z")
        },
        "value" : 1
},
{
        "_id" : {
                "id" : "HGV",
                "date" : ISODate("2017-02-01T00:00:00Z")
        },
        "value" : 2
},
{
        "_id" : {
                "id" : "HGV",
                "date" : ISODate("2017-03-01T00:00:00Z")
        },
        "value" : 2
},
{
        "_id" : {
                "id" : "HGV",
                "date" : ISODate("2017-04-01T00:00:00Z")
        },
        "value" : 1
}

So it does not have the second grouping to compound to arrays, but we did produce the same basic aggregated output.


text:
Q: Facebook App Review: confusion with share button We have Facebook Share button in our app.
However i get this review notes: "on iPhone - Your app's Login with Facebook button needs to be easily recognizable and consistent with the Facebook brand. "
App users don't need authorization in FB, they only need to share posts.
Now this is a square shaped button. It looks like Facebook logo: white letter f on dark blue background. Sorry can't post images...
We are using ShareKit.
What's wrong with our button?
Thanks.


text:
Q: Top Bar on Collection View Controller In my app, I have a collection view controller that is accessible by a modal type segue. What I am want is to have a top bar on the collection view controller. However, when I set a top bar in  attributes tab of the collection view controller, it shows on the storyboard but not in simulator?

A: I think that What you are looking for is a UICollectionReusableView.

A: You should use UINavigationController.
If you're not using it, you could also add a UIToolbar.
That Storyboard section only sets the appearance in case you're using UINavigationController.


text:
Q: How to pass variable from UIViewController to delegate UITableViewController I'm relatively new to iOS programming, so bear with me here. The requirement I'm working with is as follows:

Screen 1: User is shown a UITableView loaded with data, specifically City and State. The user taps on a selection and is
  taken to Screen 2.
Screen 2: The user is shown a "detailed" view of the item they selected for editing.

*

*The City string (selectedCity) is placed in a Text Box for editing

*An NSArray of States is loaded in a UITableView. The state for the selected City should be selected in the table on load based on the string passed from Screen 1 (selectedState). The user can select a different State here if desired.

*A 2nd UITableView will contain an array of Schools related to the city and retrieved from the database. There is a separate set of functionality for managing this list.

I have not had any issues implementing Screen 1. Here's how I passed the city and state values through to screen 2:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    //Get the City
    self.checkedCellIndex = indexPath.row;
    FSCity *selectedCity = [CityList objectAtIndex:indexPath.row];
    NSString *cityName = selectedCity.name;
    NSString *stateName = selectedCity.state;

    AdminCityView *dvController = [[AdminCityView alloc] initWithNibName:@"AdminCityView" bundle:[NSBundle mainBundle]];
    dvController.selectedCity = cityName;
    dvController.selectedState = stateName;

    [self.navigationController pushViewController:dvController animated:YES];

    dvController = nil;
}

In order to build Screen 2, however, I had to create UITableViewControllers for each UITableView (StateTable and SchoolTable) and load them in to the main UIViewController (AdminCityView), like so:
- (void)viewDidLoad
{
    [super viewDidLoad];

    txtCity.text = selectedCity;

    if (stateController == nil) {
        stateController = [[StateTable alloc] init];
    }
    if (schoolController == nil) {
        schoolController = [[SchoolTable alloc] init];
    }
    [tblState setDataSource:stateController];
    [tblSchool setDataSource:schoolController];

    [tblState setDelegate:stateController];
    [tblSchool setDelegate:schoolController];
    stateController.view = stateController.tableView;
    schoolController.view = schoolController.tableView;
}

While I can get at the selectedState variable just fine in my UIViewController and my State table loads just fine in the UIView, I'm stuck at how to pass the selectedState variable from my UIViewController (AdminCityView) to the UITableViewController (StateTable) so that I can perform operations on StateTable with the variable (such as selecting the row that matches the variable).
I've been testing with NSLog on both AdminCityView and StateTable, and the variable is definitely only accessible from AdminCityView currently. I'm not sure if I need to pass it via code in AdminCityView, or if I should just go back to Screen 1 and somehow pass it to StateTable prior to navigating to AdminCityView.
I'm happy to post any additional code that might be helpful toward reaching an answer. Thanks!

A: There are 3 ways to get this done, pick yours.
If you are using storyboard, you can just use a segue and be done with it.
From your code i can only guess that you aren't, since
viewController:initWithNibName would be unneccesary then.
So you are kind of stuck with the old ways, which turn out to be the best at some times...
You could use a notification via the NSNotificationCenter.
You subscribe your your stateTable to the notificationCenter using
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someMethodToCall:) name:@"someName" object:nil];

where observer should be self, selector is a method you must implement that will get called when the notification is send (you can choose hat name as you wish), name is the name of the notification (choose as you like), and object is the object you want to receive Notifications from (you probably dont need to specify this one, unless you send a lot of Notifications).
Also you need to implement -(void)someMethodToCall: like this:
-(void)someMethodToCall:(NSNotification *)notification{
    NSDictionary *dic = notification.userInfo;
    //you will store all the data you want transferred in this, as you will see.
    //use it as you like
}

Your AdminCityView now can send messages to your stateTable, and those can carry payloads. All you need to do is:
[self postNotificationName:@"theNameYouChoseAbove" object:yourFirstViewController  userInfo:someDictionaryThatHoldsYourValues];

Now Data from AdminCityView is transferred in a NSDictionary. Those things are really open-minded about stuff they accept, so you should be fine.
Another way is to use a protocol.
You can implement a protocol in AdminCityView like so:
@protocol yourNameHereProtocol
-(void)methodToCall:(NSString*)theData;
@end

just do it above the interface in the header file, use whatever type of data suits you.
NSString is just an example.
Now stateController needs to conform to that protocol. in stateController.h add this behind the interface:
@interface stateController (UIViewController)<yourNameHereProtocol>{
}
-(void)someMethodToCall:(NSString *)theData;

Now stateController needs to implement someMethodToCall, where you process theData and you are halfway there.
Now, do this after creating dvController:
[dvController setDelegate:stateController];

Now, dvController can call the delegate method someMthodToCall:data in stateController, transmitting the data via the data-attribute.
Oh, and you really dont need two TableViewControllers, you can just conform the surrounding view to the UITableViewDataSource and TableViewDelegate protocols and handle all the different cases in the delegate methods. But thats for another post, i guess.
If you have any questions, please comment on this, and i will answer as good as i can.
Also, i may have mixed up the denominators for your different Classes and such, feel free to change them as ist seems reasonable.
Have fun


text:
Q: Create / Add a new Document Set in Library from PowerApps Form I have just created a new PowerApp form to create a new Document Set in my library.
The Fields are mapped fine but the Save button stays put site response bar in waiting
From the Form settings i have enabled :

The Power App is opened automatically fine when the new Button and the ContentType selected.

PS: If I edit an existing DocSet it saves the records fine.
Any help appreciated!


text:
Q: Sound do not work and sound test fail HP notebook I connected my ubuntu laptop to TV via HDMI  and played movie.  After that I disconnected and the sound do not work. I have seen the sound output is on internal speakers. But no use. I uninstalled pulseaudio . But still the issue is there. Then , i upgraded system. Still there is issue. Let me know what I can do

A: This issue is solved after killing the pulseaudio using following command
killall pulseaudio
rm -r ~/.config/pulse/*
rm -r ~/.pulse*

I followed the SoundTroubleshootingProcedure in the ubuntu site for it. Thanks for all the directions.


text:
Q: Couchbase lag and views I think that Couchbase may be able to solve a lot of problems in my current project but there are a few basic things that I need to be sure of first:
1) Say I have a cluster with 10 nodes, I add a document to node A. I then ask node B for that document, will I definitely get the document back?  Is there a risk that I ask node B and it thinks the document doesn't exist?
2) Now say I write a view so that I can see all documents for a certain author.  I add a document to node A.  I know that there is a certain lag time for this document to appear in the view as it is being indexed.  What I want to know is will that lag time be very very small as I am only indexing 1 document?
Basically I have a website which manages something in the order of 100 million documents.  There are thousands of users at any one time so there are around 10 - 20 servers running.  With the current architecture, if I insert a document into node A, when I look for that document I may well be accessing node B to get it. So my overall question is:
The user inserts a document into node A, I then show them a screen of all their documents.  If I were using Couchbase, this screen would be the result of querying a view keyed on Author.  How likely is it that the user won't be able to see the document they just posted?

A: *

*You will always be able to get the document back no matter what node you ask. If you use one of the Couchbase SDK's then they will always make sure they ask the node that has the document. If you use moxi then it will do the same so you shouldn't need to worry about this.

*This depends on how heavy your write workload is. In the current architecture (2.0) a document must hit disk before it is indexed. If you have a heavy write workload then the lag will increase since there will be a longer line of items that need to be written to disk. I suggest doing benchmarking with your specific application requirements in mind for this use case and posting any problems or issues you have on the Couchbase forums.
Also, you will want to take a look at the commands that have durability requirements and doing queries with the stale query parameter set to false. The durability commands will allow you to have you application block until an item hits disk and doing a query with stale set to false will make sure your view is up to date with the latest items put into Couchbase. This process will ensure your users always see the latest results of you
EDIT: Couchbase 3.0 no longer requires items to be persisted to disk before they can be queried.

A: View updates are a tunable parameter.  By default a thread wakes up every 5 seconds, checks for changes and updates the index if it finds them.  Either tune these parameters or use the view parameter stale=false for queries.
From the docs under "Automated index updates":
In addition to a configurable update interval, you can also update all indexes automatically in the background. You configure automated update through two parameters, the update time interval in seconds and the number of document changes that occur before the views engine updates an index. These two parameters are updateInterval and updateMinChanges:

*

*updateInterval: the time interval in milliseconds, default is 5000 milliseconds. At every updateInterval the views engine checks if the number of document mutations on disk is greater than updateMinChanges. If true, it triggers view update. The documents stored on disk potentially lag documents that are in-memory for tens of seconds.

*updateMinChanges: the number of document changes that occur before re-indexing occurs, default is 5000 changes.

http://docs.couchbase.com/admin/admin/Views/views-operation.html