text:
Q: Leaking memory with a map using the factory pattern, solution? class Factory
{
    public:
        Base* create()              { return new Rand();}
        Base* create(double value)  { return new Op(value); }
        Base* create(const std::string& comp, Base* x, Base* y)
        {
            /*
            std::map<std::string, Base*> map_CreateFuncs = {
                { "+", new Add(x,y) },
                { "-", new Sub(x,y) },
                { "*", new Mult(x,y) },
                { "/", new Div(x,y) },
                { "**", new Pow(x,y) }
            };
            return (map_CreateFuncs.count(comp) == 1) ?  map_CreateFuncs[comp] : nullptr;
            */
                 if (comp == "+")  return new Add(x,y);
            else if (comp == "-")  return new Sub(x,y);
            else if (comp == "*")  return new Mult(x,y);
            else if (comp == "/")  return new Div(x,y);
            else if (comp == "**") return new Pow(x,y);
            else return nullptr;
        }
};

Using the if/elseif's works ~ no memory leaks.
But I'd like to use the map method that I started with.
Wondering what the proper way to implement my create(string, Base*, Base*) is, using the map.
I've read code out there that uses a typedef but I couldn't understand its implementation.

A: *

*Unless there is a very specific reason to use raw pointers, consider always using std::unique_ptr by default. Using smart pointers allows to both avoid memory leaks and clearly document the ownership model. For example, when you create Add(x, y), should the ownership of x and y be transferred to the newly created object, or the ownership might be shared with some other instances? In case of the latter, consider std::shared_ptr.

*You probably don't want to create class instances for all of your available operations every time. Instead, you could introduce lazy evaluation by storing an object that maps operations to factory functions that create appropriate class instances.
Overall, this would look somewhat like this:
class Base {
public:
    virtual ~Base() = 0;
};

class Add : public Base {
public:
    static std::unique_ptr<Base> create(std::unique_ptr<Base> x, std::unique_ptr<Base> y);

private:
    // Constructor is private so that the user can only create smart pointers holding instances of Add.
    Add(std::unique_ptr<Base> x, std::unique_ptr<Base> y);
};

class Factory
{
public:
    std::unique_ptr<Base> create(const std::string& comp, std::unique_ptr<Base> x, std::unique_ptr<Base> y)
    {
        using FactoryMethod = std::function<std::unique_ptr<Base>(std::unique_ptr<Base>, std::unique_ptr<Base>)>;
        static std::map<std::string, FactoryMethod> map_CreateFuncs = {
            { std::string("+"), FactoryMethod([](std::unique_ptr<Base> x, std::unique_ptr<Base> y){
                return Add::create(std::move(x), std::move(y)); })},
            // Other operations ...
        };

        const auto factory_method_it = map_CreateFuncs.find(comp);
        if (factory_method_it == map_CreateFuncs.end()) {
            return nullptr;
        }
        return (factory_method_it->second)(std::move(x), std::move(y));
    }
};

Keep in mind that std::map and std::function might introduce some overhead over simple if-else clauses.


text:
Q: Sparql exists function not working with bind if My Virtuoso is (virtuoso-t -h):
Virtuoso Open Source Edition (Column Store) (multi threaded)
Version 7.2.4.2.3217-pthreads as of Jun  3 2016
Compiled for Linux (x86_64-pc-linux-gnu)

The Sparql function exists is working fine, but not when combined with (bind if(...)).
The query:
PREFIX dbo: <http://dbpedia.org/property/>
SELECT  ?uri  ?popEstimate ?existsPopEstim ?usedExPop
WHERE {
    ?uri  a <http://dbpedia.org/ontology/Place>.

    {?uri rdfs:label "France"@fr}
    UNION {?uri rdfs:label "Brésil"@fr}
    UNION {?uri rdfs:label "Amérique"@fr}

    OPTIONAL {?uri dbo:populationEstimate ?popEstimate .}
    BIND (exists{?uri dbo:populationEstimate ?popEstimate} AS ?existsPopEstim )
    BIND (IF(?existsPopEstim , "ok", "no") AS ?usedExPop)
}
LIMIT 100

The result:
uri                                  | popEstimate | existsPopEstim | usedExPop
-------------------------------------+-------------+----------------+----------
http://dbpedia.org/resource/France   |             | 0              | ok
http://dbpedia.org/resource/Brazil   | 201032714   | 1              | ok
http://dbpedia.org/resource/Americas |             | 0              | ok

Edit 1
The example from @AKSW answer, which is also not working on https://dbpedia.org/sparql:
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX dbp: <http://dbpedia.org/property/>
SELECT *
WHERE {
    ?uri a dbo:SoccerPlayer
    OPTIONAL {?uri dbo:deathDate ?date}
    BIND (exists{?uri dbo:deathDate ?date} AS ?existsProp )
    BIND (IF(?existsProp , "ok", "no") AS ?usedExProp) }
LIMIT 1000

Edit 2
Example on dbpedia:
http://dbpedia.org/sparql/?default-graph-uri=&query=PREFIX+dbo%3A+%3Chttp%3A%2F%2Fdbpedia.org%2Fproperty%2F%3E%0D%0APREFIX+xsd%3A+%3Chttps%3A%2F%2Fwww.w3.org%2F2009%2FXMLSchema%2F%3E%0D%0APREFIX+dbo%3A+%3Chttp%3A%2F%2Fdbpedia.org%2Fontology%2F%3E%0D%0APREFIX+rdfs%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23%3E%0D%0A%0D%0ASELECT++%3Furi++%3Fpop+%3FexistsPop+%3FusedExPop%0D%0AWHERE+%7B%0D%0A%09%3Furi++a+%3Chttp%3A%2F%2Fdbpedia.org%2Fontology%2FPlace%3E.%0D%0A%09%0D%0A%09%7B%3Furi+rdfs%3Alabel+%22France%22%40en%7D%0D%0A%09UNION+%7B%3Furi+rdfs%3Alabel+%22Brazil%22%40en%7D%0D%0A%09UNION+%7B%3Furi+rdfs%3Alabel+%22Raging+River%22%40en%7D%0D%0A%0D%0A%09OPTIONAL+%7B%3Furi+dbo%3ApopulationTotal+%3Fpop+.%7D%09%0D%0A%09BIND+%28exists%7B%3Furi+dbo%3ApopulationTotal+%3Fpop%7D+AS+%3FexistsPop%29%0D%0A%09BIND+%28IF%28%3FexistsPop%2C+%22ok%22%2C+%22no%22%29+AS+%3FusedExPop%29%0D%0A%7D%0D%0ALIMIT+1000&format=text%2Fhtml&CXML_redir_for_subjs=121&CXML_redir_for_hrefs=&timeout=3000000&run=+Run+Query+

A: I notice that you are experiencing this problem via Version 7.2.4.2.3217-pthreads as of Jun  3 2016. Here's what happens with the more recent 7.2.x and 8.0 releases via live example links:

*

*DBpedia -- running 7.2.x (2017 release)

*URIBurner -- running 8.0 (2018 release), but doesn't have
complete DBpedia dataset loaded.

That said, I can recreate your problem via our LOD Cloud Cache instance. Thus, I suggest:

*

*Upgrade on your part to one of the 2017 releases used in my examples above

*We revisit our Cluster Edition which is running behind the LOD Cloud instance that I used to recreate your problem.

A: Seems to be a virtuoso datatype issue as @Kingsley said, see: https://github.com/openlink/virtuoso-opensource/issues/693

redpajama_set_name: RedPajamaStackExchange


text:
Q: Activiz (C#) VTK vs Python VTK render quality I have created a small tool in Python that shows a couple of STLs and creates a number of screenshots of them. Recently, I have converted this tool to C# using the Activiz VTK wrapper (both VTK implementations are version 5.8.0).
The quality of the screenshots created in the C# implementation is similar to that of the Python screenshots, except where STLs overlap with eachother.
This is a Python VTK screenshot
And this is the corresponding Activiz VTK screenshot
As you can see, the red objects show through the beige one in Activiz VTK, the orange (and red) objects also show through the blue object on the left.
This is the Activiz render setup:
vtkOpenGLRenderer renderer = new vtkOpenGLRenderer();
renderer.SetBackground(1, 1, 1);
vtkWin32OpenGLRenderWindow window = new vtkWin32OpenGLRenderWindow();
window.SetSize(1000, 1000);
window.AddRenderer(renderer);

STLs are added like this
vtkPolyDataMappermapper = vtkPolyDataMapper.New();
mapper.SetInput(_polydata);
vtkActor actor = vtkActor.New();
actor.SetMapper(mapper);
actor.GetProperty().SetColor((double)color.R / 255, (double)color.G / 255, (double)color.B / 255);
actor.GetProperty().SetOpacity(alpha);
actor.GetProperty().SetInterpolationToPhong();
renderer.AddActor(actor);

This is the original Python render setup
renderer = vtkOpenGLRenderer()
renderer.SetBackground(1,1,1)
window = vtkWin32OpenGLRenderWindow()
window.SetSize(1000,1000)
window.AddRenderer(renderer)

And STLs are added like this in Python
mapper = vtkPolyDataMapper()
mapper.SetInputData(polydata)
actor = vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(color)
actor.GetProperty().SetOpacity(alpha)
actor.GetProperty().SetInterpolationToPhong()
renderer.AddActor(actor)

Has anyone had a similar experience, or does anyone know what causes this difference in quality?
Kind regards

A: Maybe the cameras clipping planes (see "Perspective Projection") are set to different values. If the clipping range is too large such rendering errors can occur. Try to set it small enough so that all your objects are displayed. Haven't tried it but something like this:
renderer.GetActiveCamera().SetClippingRange(0.1, 100);

where the two arguments are the distances of the near and far clipping plane from the camera.


text:
Q: Is there a way to paste multiple lines to the left of multiple lines (keeping formatting) in libreoffice writer? If I have these lines
1
2
3
and these lines
abc
def
ghi
Is there a way to paste them so that I get
1abc
2def
3ghi
That is to say, I want that the original bold characters (and any other formatted characters) are preserved.

A: Yes, LibreOffice Writers offers a feature named "Block Selection Mode". You can enable it using the shortcut CTRL+SHIFT+F8. Then, you can copy content "vertically" and paste it the same way.
Generally, pasting the content of a "block copy" won't touch the formatting of the target lines, but maybe, the pasted content may acquire formatting of pre-existing, adjacent content. So, in your example, the "3" will most likely acquire bold formatting from the adjacent "g" letter.


text:
Q: Can no longer use Snowflake connector with Big Sur: error The library Security could not be found I just upgraded to Big Sur and can no longer connect to snowflake. Getting the following error: The library Security could not be found
I've followed these steps and the issue is not resolved. Anyone have another work around?
SnowSQL fails with "The library Security could not be found" after upgrading to mac Big Sur_

A: macOS 11 (Big Sur) is not supported for SnowSQL:
SnowSQL Documentation
Operating System    Supported Versions
================    ==================
Linux               CentOS 6, 7, 8
                    Redhat Enterprise Linux (RHEL) 6, 7, 8
                    Ubuntu 16.04, 18.04 (Support for Ubuntu 14.04 is deprecated.)
macOS               10.13, 10.14, 10.15
Microsoft Windows   Windows 8, 8.1, 10 (Support for Microsoft Windows 7 is deprecated.)
                    Windows Server 2012, 2016, 2019

A: You need to manually re-install oscrypto as Sergiu mentioned - to version 1.2.1.  This should fix the problem.


text:
Q: Elasticsearch stops working suddenly I am running Elasticsearch on a VPS and it was working perfectly for me. Initially, there were many rows indexed using Elasticsearch. When i tried to create new index, Elasticsearch stopped working. Now whenever i try to start Elasticsearch, it works for some time and then it gives me message "Killed" and it stops working. I deleted the new index that i had created and tried  to start Elasticsearch but it still gives me the same error. Any solutions to resolve this issue?

A: Most common thing which could be happening in your case is OOM (out of memory) is getting triggered for your elasticsearch java process if this is linux , trying checking /var/log/messages and dedicate Heap based on your server compute power.


text:
Q: Is a horizontal scroll bar for graphs available on Bokeh? Bokeh:
Can anyone provide some guidance on creating the horizontal scroll bar similar to the one shown in the image below such? Does anything of the like exist?  Is this feasible without fiddiling D3.js?  Graph can be viewed at
https://fred.stlouisfed.org/series/GDP#

A: Use python-highcharts instead. The graph you showed is apparently using highcharts.


text:
Q: C# SqlException was unhandled error: 26 - Error Locating Server/Instance Specified He estado desarrollando desde principios de diciembre del 2016 un proyecto para registrar vales de préstamo de herramientas para mi escuela y he echo uso de una base de datos sql para llevar el registro. Agregué una base de datos local sql siguiendo el siguiente tutorial de youtube:
"Consultas de Insertar Modificar Borrar y Buscar en VB 2010 y 2008"
(el vídeo dura 17 minutos con 45 segundos no puedo agregar el link porque tengo bajo nivel en el foro, además que en el vídeo el autor programa en C++ y yo programe en C#)
Y después de haber manejado bastante las consultas (los Queries) de la base de datos (que funcionan correctamente) quise agregarle un form para respaldar la base de datos siguiendo el siguiente tutorial:
http://www.csharp-tutorials.info/2016/03/backup-and-restore-sql-server-database.html
cuando intenté realizar un respaldo no hacia nada y entonces puse como comentario las instrucciones try y catch para ver el error al intentar de nuevo me apareció el siguiente error:

SqlException was unhandled
A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: SQL
  Network Interfaces, error: 26 - Error Locating Server/Instance
  Specified)

y les dejo la captura de pantalla del error:

a continuación les pongo el código completo del form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Base_de_datos_ITQ
{
    public partial class Respaldo_duv : Form
    {
        SqlConnection con = new SqlConnection(Base_de_datos_ITQ.Properties.Settings.Default.Base_de_datosConnectionString);
        public Respaldo_duv()
        {
            InitializeComponent();
        }

        private void button_duv_examinar_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialogo = new FolderBrowserDialog();
            if (dialogo.ShowDialog() == DialogResult.OK)
            {
                textBox_duv_dirección_respaldo.Text = dialogo.SelectedPath;
            }
        }

        private void button_duv_respaldar_Click(object sender, EventArgs e)
        {
            string database = con.Database.ToString();
            //try
            {
                if (textBox_duv_dirección_respaldo.Text == string.Empty)
                {
                    MessageBox.Show("please enter backup file location");
                }
                else
                {
                    string cmd = "BACKUP DATABASE [" + database + "] TO DISK='" + textBox_duv_dirección_respaldo.Text + "\\" + "database" + "-" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".bak'";

                    using (SqlCommand command = new SqlCommand(cmd, con))
                    {
                        if (con.State != ConnectionState.Open)
                        {
                            con.Open();//aquí es donde se marca el error
                        }
                        command.ExecuteNonQuery();
                        con.Close();
                        MessageBox.Show("database backup done successefully");
                    }
                }

            }
            //catch
            {

            }
        }
    }
}

Notese que esta escrito en lenguaje C#.
Debo agregar que estoy estudiando ingeniería electrónica y no sistemas o computación, por tanto no estoy en mi campo (normalmente lo que programo son microcontroladores con C++, es decir lenguajes de bajo nivel) y es la primera vez que utilizo bases de datos sql. doy gracias de antemano a todos los que respondan.

A: De acuerdo al comentario donde indicas la ruta de la base de datos a la cual te estas conectando, puedo deducir que estas trabajando con SQL Compact Edition, esto debido a la extensión del archivo .sdf. Esto significa que para crear la conexión no puedes utilizar SqlConnection lo correcto seria que usaras SqlCeConnection que es el controlador adecuado para este tipo de base de datos. Lo mismo pasa con la clase SqlCommand deberías utilizar SqlCeCommand.
EJEMPLO:
SqlCeConnection conn = null;

try
{
    conn = new SqlCeConnection("Data Source = MyDatabase.sdf; Password ='<pwd>'");
    conn.Open();

    SqlCeCommand cmd = conn.CreateCommand();
    cmd.CommandText = "INSERT INTO Customers ([Customer ID], [Company Name]) Values('NWIND', 'Northwind Traders')";

    cmd.ExecuteNonQuery();
}
finally
{
    conn.Close();
}

Ahora bien, creo que la instrucción BACKUP DATABASE.... que estas intentado usar para realizar el Backup tampoco te va a funcionar, por que esta es una instrucción para SQL Server o SQL LocalDB.
Para hacer Backup a un archivo .sdf basta solo con copiarlo, como se hace con cualquier otro archivo en el disco, lo único que tienes que asegurar antes de copiarlo es que no haya ningún usuario conectado a la base de datos en ese momento.
Al final de esta referencia https://technet.microsoft.com/en-us/library/ms172411(v=sql.110).aspx puedes encontrar  lo que te estoy diciendo.

A: El error que te muestra significa básicamente que no encuentra la base de datos por lo cual podemos asumir en principio que hay algo incorrecto en el connection string.
Por otra parte veo que utilizas una base de datos .sdf que corresponde a SQL Server Compact Edition por lo cual no es correcto utilizar

System.Data.SqlCommand

Esto se utiliza cuando te conectas a una base de datos que esta corriendo en el motor de MSSQL instalado en el servidor.
Para utilizar SQL Server Compact Edition tendrías que utilizar

System.Data.SqlServerCe

No entiendo como te han funcionado las otras consultas sobre una base .sdf utilizaste System.Data.SqlCommand.
De todos modos, como es un archivo de tipo .sdf, no se generan .bak para los respaldos como lo harías en un MS SQL Server tradicional es decir con una instancia de MSSQL corriendo en el servidor.
Estas bases de datos más sencillas como se corresponden simplemente con un archivo, basta con hacer una copia de este y guardarla donde sea deseado.


text:
Q: A homemade breakfast Do the  first and second   sentences sound less natural?
1."We carry/have  a cold home-made breakfast to school."
2."We have/carry a cold breakfast made at home by our parents."

*"We carry homemade breakfast to school."

The first two sentences are mine. The third sentence expresses what I mean but it's short and from the internet.

A: There are several different questions at work here: 1) can you have "a breakfast"? (yes) 2) How do you use "have" vs "carry" and 3) how do we fit "home" and "school" into the sentence? Let's take them in order:

*

*We carry a cold home-made breakfast to school — This is grammatically valid and idiomatically natural. You could also use another verb like "bring," which might be still more natural.

*We have a cold home-made breakfast to school — The only problem here is that "have" doesn't pair with "to" (at least, not in this way). You could say "we have breakfast at school," but "have breakfast" is an idiom meaning "eat breakfast," and your example seems to be more interested in talking about how you bring the food than when you eat it.

*We carry a cold breakfast made at home by our parents — This is also grammatically valid. It doesn't mention school, but maybe that's okay if it's clear from the context. For some reason, while "bring" seems like a slightly more natural verb than "carry," in the first example, it seems much more natural here.  "Carry" often focuses very directly and immediately on how you're transporting something, even thinking about how you're holding it, while "bring" simply conveys that you brought it along.

*We have a cold breakfast made at home by our parents — Since "have breakfast" idiomatically means "eat breakfast," and since this sentence doesn't mention school, this one confuses the meaning and seems to suggest that you eat your cold breakfast at home.

*We carry homemade breakfast to school — This one is short and clear, though it doesn't mention that the breakfast is cold or made by the parents. If you wanted to wrap all these points up into one option, perhaps it would be something like:

*We bring a cold breakfast to school, made at home by our parents.

A: The first sentence works only with carry:

*We have... a breakfast to school .

doesn't work at all.
For the second sentence, either have or carry works. Which you use depends on what you want to emphasize - bringing it to school, or having or eating it.


text:
Q: Can find take a file as argument from stdin? I have a list of 3,900 ID numbers and I need to find on our FTP server the matching files.
Finding one file is quite simple e.g.
find . -name "*IDNumber*" -exec ls '{}' ';' -print
but how do I do this for 3,900 IDs numbers?  I created a file with the IDs like so
028892663163
028923481973
...

but how do I pass the list of ID numbers as argument? Can you provide some pointers?
Thanks!

A: I would try to reduce the number of times you have to invoke find:
find . -type f -print | grep -f id.file | xargs cp -t target_dir

A: You may try to optimize it by running find with more than one id at a time.
With bash (100 at a time, you may try with more):
c= p=
while IFS= read -r; do
  p+=" -name '*$REPLY*' -o "
  (( ++c ))
  (( c % 100 )) || {
    eval find .  ${p% -o }
    p=
    }
done < id_list_all

[[ $p ]] &&
    eval find .  ${p% -o }

A: Figured it out.

*

*put all my 3,900 ID numbers in a file outfile

*typed the command line:

cat outfile | while read line
do
    find . -name "$line" -exec cp '{}' /target_directory ';' -print
done
Worked awesome!

A: I read your question wrong the first time... arguments from find to other things. What you want is arguments from a file passed to find. So, here's the correct answer with xargs:
xargs --max-args=1 -I X -d '\n' find . -name X -exec [...] < your_list


text:
Q: Why bootstrap 3.3.7 request size only 23.6kb, but actual size is 123 kb When I watch the request css file of the bootstrap website, it's only 23.6kb, but the actual size is 123kb, how it compress it to 23.6kb, is it the server side configuration?

*

*The request size of bootstrap.min.css

*Open the request bootstrap.min.css in new chrome tab and save as the css file

*The actual size is 123kb on disk


text:
Q: Why would JSRuntime.InvokeAsync fail when IEnumerable> is passed to it, when T is not string? Running the latest Blazor preview release, client-side, I have an application that loads an IEnumerable<MyClass<T>> data of a simple generic class:
public class MyClass<T>
{
    public string ID { get; set; }

    public T Value { get; set; }
}

I pass this IEnumerable to JSRuntime.InvokeAsync like so:
await JSRuntime.InvokeAsync<object>("renderChart", data);
When T is type string, this works as expected. When T is type double or float it fails with errors:
WASM: System.InvalidCastException: Specified cast is not valid.
WASM:   at System.Text.Json.ReflectionMemberAccessor+<>c__DisplayClass11_0`2[TClass,TProperty].<CreatePropertyGetter>b__0 (System.Object obj) <0x2951800 + 0x0000c> in <e1cfca862e6a44dbaac6737c11b98f37>:0`

The JavaScript function does nothing more than log the value:
function renderChart(data) {
    console.log("Data:", data);
}

What's wrong here?


text:
Q: Generate input type="tel" with JSF In order to make the site mobile friendly, I want to add
<input type="email">

and
<input type="tel">

But I have to use JSF like
<h:inputText  value="#{connetcionController.userName}" />

How can we generate html input type with JSF ?
I am also using primefaces and do they have a similar feature?

A: If you're using PrimeFaces, you should be able to use type with <p:inputText> in this way
<p:inputText type="email" ... />

or
<p:inputText type="tel" ... />

If you want to keep using <h:inputText>, you need to upgrade to a minimum of JSF 2.2 and add the new XML namespace xmlns:a="http://xmlns.jcp.org/jsf/passthrough", then you should be able to override type of <h:inputText> in this way
<h:inputText a:type="email" ... />

or
<h:inputText a:type="tel" ... />

A: There's a very easy way. You can use pass-through.
Add this to your html tag
xmlns:a="http://xmlns.jcp.org/jsf/passthrough"

You can then add your input type.
You have to add an a: before.
<h:inputText a:type="email" value="#{profileBean.student.privateMail}"/>

This also works with some other definitions, like placeholder
<h:inputSecret a:placeholder="Password" value="#{loginBean.credentials.password}" />

A: OmniFaces provides a solution. See this explanation on how to use omnifaces for your situation.

A: You can use a jQuery plugin to mask a normal <input id="phone" /> like that :
jQuery(function($){
   $("#phone").mask("(999) 999-9999");
});

Using this plugin : http://digitalbush.com/projects/masked-input-plugin/

A: PrimeFaces Extensions comes with pe:inputPhone which renders the input with type="tel". Besides that it offers validation, formatting and more options.
See:

*

*https://www.primefaces.org/showcase-ext/sections/inputphone/basicUsage.jsf


text:
Q: Which movies mentioned by War Machine and Ant-Man actually support their point of view? In a hilarious scene in Avengers: Endgame,

 Hulk is explaining how time travel works to War Machine and Ant-Man, who are shocked to learn that it doesn't work like it does in Back to the Future. Scott and Rhodes then take turns going through a whole list of movies to justify why they think going back and changing the past will cause changes to the present.

I don't remember all the movies they mention, but I remember one of them was

 Bill and Ted's Excellent Adventure. But that movie uses the model of Immutable Time - you can't ever change the past, and anything anyone does in the past turns out to be what already happened as part of a closed time loop all along. We see this even when the characters are interacting with their past selves!

Another movie mentioned was

 A Wrinkle in Time. I only saw that movie once and it was a while ago, but as I recall it didn't actually have any time travel at all.

So my question is,

 What movies are listed by Scott and Rhodey, and which of them actually feature the trope of "Changes to the past cause changes to the present"?

A: To answer this I'd like to refer to one of my favourite things on the Internet, A Guide to SF Chronophysics.
In the Type Summaries section, it describes four general models of time travel:

*

*Deterministic/Permanent

*Elastic/Resilient

*Overwriting/Contingent

*Quantum-forking/Multi-divergent

Avengers: Endgame follows

 Type 4 (Quantum-forking), though it's significant to note that when a traveller returns to the future they return to their original timeline, and not to a timeline they have created due to branching.

Here's some of the movies mentioned by Rhodey and Lang and the Chronophysics model they follow:

*

*Back to the Future: most often interpreted as Type 3, but could also be Type 4

*Star Trek: Type 3 (occasionally Type 1 when it suits them)

*Terminator: Terminator (1) is Type 1, Terminator 2: Judgment Day revises that to Type 3, Terminator 3: Rise of the Machines revises that further to Type 2, Terminator Genysis kind of suggests Type 4 but doesn't actually make any sense... ultimately the franchise is a mess.

*Timecop: Type 3

*Hot Tub Time Machine: Type 3 and for some parts Type 1 (inconsistent)

*Bill and Ted's Excellent Adventure: Type 1

Others I'm not familiar enough to assign a type.
So to answer the original question, not all the movies listed by Rhodey and Lang actually support the idea that the present will be changed if you change the past. Terminator (1) and Bill and Ted's Excellent Adventure follow the Type 1 (Deterministic/Permanent) model where time travel to the past cannot alter the present.
However, none of them really follow the model that Avengers: Endgame does either...

 except (perhaps ironically) Back to the Future matches it most closely if you interpret it as Type 4.

However there are some important differences:

 In Avengers: Endgame, when a visitor to the past returns to the future, they return to their original timeline, not to any branched timeline they may have created. Possibly this is the purpose of the big time machine in Avengers HQ: it works as a beacon to bring the travellers back to their original timeline. In Back to the Future, a visitor returning to the future will arrive in a branched alternate timeline when attempting to return to the future, as Marty did when returning to 1985 from 1955 in the first movie. Travel to the past from a branched timeline can land you in an alternate timeline, as Marty and Doc did when travelling back from 2015 to alternate 1985. However Old Biff's return to 2015 after delivering the almanac to Young Biff contradicts this somewhat... he should have returned to an alternate 2015 he created. This may be why he phases out after arriving.

Also,

 in Avengers: Endgame a traveller can exist in a timeline that is not their original timeline if their past self is killed or ceases to exist, or if the events that sent them to the past are altered. In Back to the Future they cannot: in part one, once the timeline diverges to a future where Marty doesn't exist, he begins to phase out of that timeline. Notably the alternate 1985 that Marty and Doc visit still has an alternate Marty and Doc elsewhere that they do not meet, which allows them to exist in the alternate timeline.


text:
Q: check if username is not taken between two tables Well i have a problem. I have a registration for for legal users and natural users, but i need to write a validation in each php file for username checking, i have no idea how to combine two table checking.
one table is called users_legal, 2nd one is users_natural. In both forms name for input field is "username".
So far i have a code that checks passwords :
if ($password == $password_re)
{
    // insert into table
    $sql = $db->prepare("INSERT INTO users_legal(name, reg_number, address, phone, email, username, password) VALUES(?, ?, ?, ?, ?, ?, ?);");
    $sql->bind_param("sssssss", $name, $reg_number, $address, $phone, $email, $username, $password);
    $sql->execute();
    $sql->close();
}

After makeing a validation in register forms, i also need it in login page. I figured out how to check if there is only and only one user with that username and that password, but i have no idea how to search them between tables.
login.php code :
if($_SERVER["REQUEST_METHOD"] == "POST") {
  // username and password sent from form

  $myusername = mysqli_real_escape_string($db,$_POST['username']);
  $mypassword = mysqli_real_escape_string($db,$_POST['password']);
  $sql = "SELECT id FROM login WHERE username = '$myusername' and password = '$mypassword'";
  $result = mysqli_query($db,$sql);
  $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
  $active = $row['active'];
  $_SESSION['username'] = $myusername;
  $count = mysqli_num_rows($result);

  if($count == 1) {
     session_register("myusername");
     $_SESSION['username'] = $myusername;
     $_SESSION['loggedin'] = true;
     header("location: www.goole.lv");
  }else {
     $error = "Your Login Name or Password is invalid";
  }
}

One more thing : i set my mysql to utf format, var_dump says  that input is allright, but in mysql it saves in unbelievuble forms, like Ķegums or Skrīvelis.
Thnx for any examples, tips or whateva u got.

A: When I got you right, you have two tables with users. To validate if an user has logged in successfully you look up their login credentials in the related database table.
You are asking for 'combining' these two tables. But I don't think that that's what you want. You have two separate user tables. They do not belong to each other. If you join those tables, you might have dulicate unique user ids when combining these tables.
What you could do instead is check both tables separately, first for users_legal and second for users_natural.
You should also think about using password hashes instead of plain passwords in your db. And use pdo ;)
Good luck

A: To solve the problem of having two different types of users I would just put them in the same table and add a value that represents the user type for example 0 = legal and 1 = natural. This will also automatically prevent two users from sharing the same username. (This will only work for sure if the database is still empty, if not you might end up with two users with the same name). For the character encoding try setting mysql to utf-8 if you haven't done it already (instead of just utf). Also you should never save passwords in plaintext. Use the sha1 function in php to convert them to their hash value before storing them. That way even if someone gets unauthorized access to the database they still won't know the passwords. You should also append some user specific information to the password before hashing so that even if two users share the same password their hash values will be different. To verify if it's correct you just apply the same procedure to the input before comparing it with the hash value you have stored.


text:
Q: Repeat for different sets of times I have a data frame with 25 values, and I'd like to repeat 1:3, each value 10 times (so first 10 values have 1, next 10 have 2, next 5 have 3).
But, since my 3rd set of values is not a full 10, I am getting the error that my replacement has more rows than my data. I'm wondering why length handles this with no problem, but times doesn't.
Is the answer as simple as I think it is?
df$y <- rep(1:3, times = 10, length = nrow(df))


text:
Q: I accidentaly enabled the UFW on my Google Cloud Computer I accidentally enabled the UFW on my Google Cloud Compute debian instance and unfortunately port 22 is blocked now. I've tried every way to go inside the VM but I can't.
I'm trying to access through the serial port but it's asking me for user and password that was never set.
Does anyone have any idea what can I do?

A: This answer shows two methods of solving this problem.
The first method is to create a startup-script that disables UFW. The second method attaches the boot disk to another instance and modifies the file  /etc/ufw/ufw.conf
Method 1:
Step 1:
Login into the Google Cloud Console. Go to Compute Engine -> VM instances. Click on your instance. Click on the Edit button.
Step 2:
Scroll down to the section "Custom metadata". For Key enter startup-script. For Value enter:
#! /bin/bash
/usr/sbin/ufw disable

Click the Save button
Step 3:
Reboot your instance. During reboot the startup-script will run disabling the UFW firewall. Login to your instance using SSH.
Step 4:
Repeat Step #2 except this time, delete the startup-script. Otherwise the firewall will be disabled each time your instance boots.
Method 2:
STEP 1:
Shutdown your instance with the UFW problem. Login into the Google Cloud Console. Go to Compute Engine -> VM instances. Click on your instance and make note of the "Boot disk" name. This will be the first disk under "Boot disk and local disks".
STEP 2:
Create a snapshot of the boot disk before doing anything further. While still in Compute Engine -> Disk. Click on your boot disk. Click on "CREATE SNAPSHOT".
STEP 3:
Create a new instance in the same zone. A micro instance will work.
STEP 4:
Open a Cloud Shell prompt (this also works from your desktop if gcloud is setup). Execute this command. Replace NAME with your instance name (broken system) and DISK with the boot disk name and ZONE with the zone that the system is in:
gcloud compute instance detach-disk NAME --disk=DISK --zone=ZONE

Make sure that the previous command did not report an error.
STEP 5:
Now we will attach this disk to the new instance that you created.
Make sure that the repair instance is running before attaching the second disk. Sometimes an instance can get confused on which disk to boot from if more than one disk is bootable.
Go to Compute Engine -> VM instances. Click on your instance. Click Edit. Under "Additional disks" click "Add item". For name enter/select the disk that you detached from your broken instance. Click Save.
STEP 6:
SSH into your new instance with both disks attached.
STEP 7:
Follow these steps carefully. We will mount the second disk to the root file system. Then change the contents of /mnt/repair/etc/ufw/ufw.conf to disable the firewall.

*

*Become superuser. Execute sudo -s

*Execute df. Make sure that /dev/sdb1 is not mounted.

*Create a directory for the mountpoint: mkdir /mnt/repair

*Mount the second disk: mount /dev/sdb1 /mnt/repair

*Change directories: cd /mnt/repair/etc/ufw

*Edit ufw.conf

*Change ENABLED=yes to ENABLED=no

*Shutdown the repair system: halt

STEP 8:
Now reverse the procedure and move the second disk back to your original instance and reattach using the command below. Then start your instance and connect via SSH.
Note: To reattach the boot disk you have to use gcloud with the -boot option.
gcloud beta compute instances attach-disk NAME --disk=DISK --zone=ZONE --boot


text:
Q: Symfony 3 - There is no suitable CSPRNG I'm getting this error on my test server with PHP 5.5 (Symfony 3.0.9):

Everything is all right on my local server created with XAMPP having PHP 5.6. I know that there are two workarounds:

*

*paragonie/random_compat downgrade

*changing random_bytes() for openssl_random_pseudo_bytes().

But still, I would like to use them as a last resort. Is there any other way to FIX this problem?

A: Actually, those are 2 of the 3 unique solutions.
As the problem is only in your server (that happened to me too), you could go to your domain and add /dev/urandom to your existing open_basedir configuration property in your server configuration.
Read this article which offers 3 solutions (and according to your need only the solution #3 would work).


text:
Q: Laravel: How to define relations while the primary key of the model is changed to slug? I like to define Many To Many Polymorphic Relations like the one that is mentioned in laravel documentation, but with one difference that I like the primary key to be changed to slug. I do that in the model by protected $primaryKey = 'slug' but when I do that I can not retrieve relations anymore. I guess I must change the arguments of morphToMany and morphedByMany method to fix this. However, I don't know how should I do that.
I would appreciate your help.
posts
    id - integer
    name - string
    slug - string (primary key)

videos
    id - integer
    name - string

tags
    id - integer
    name - string

taggables
    tag_id - integer
    taggable_id - integer
    taggable_type - string

A: This is how it looks like.
// morphToMany($related, $name, $table = null, $foreignPivotKey = null,
                            $relatedPivotKey = null, $parentKey = null,
                            $relatedKey = null, $inverse = false)

So try this one in your Post model.
class Post extends Model
{
    public function tags()
    {
         return $this->morphToMany(Tag::class, 'taggable', null, null, 'taggable_id');
    }
}

Hope this will help you.


text:
Q: Publish app only for 3.2+ tablets and 2.2+ handsets? Is it possible to declare application to be compatibile for ALL handsets running 2.2+, and ALL tablets running on 3.2+ ? So actually tablets lower than 3.2 are exluded.

A: Probably the best way to do this is to publish multiple apps with different filters.  There is a quick walkthrough in the documentation that describes how to do this.  (scroll to the bottom of the page)


text:
Q: Not getting the required interface everytime i search using/admin , I am following a yt tutorial on django(https://www.youtube.com/watch?v=sm1mokevMWk)
where the tutor searches   http://127.0.0.1:8000/admin and gets the required interface
(It starts around 49:00)
everytime i search  http://127.0.0.1:8000/admin
i get a
DoesNotExist at /admin
but when i search http://127.0.0.1:8000/admin/login/?next=/admin/nw/
i get the required interface
A question exactly same as  mine has been asked before  but the thing is i did not make the same error as that person did
this is my views.py

from django.shortcuts import render
from django.http import HttpResponse

from .models import  ToDoList,Items

def index(response,name):
    ls=ToDoList.objects.get(name=name)
    item=ls.items_set.get(id=1)

    return HttpResponse("
%s

%s
"%(ls.name,str(item.text)))

# Create your views here.

this is my urls.py
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include("main.url")),
]

this is my models.py
from django.db import models
class ToDoList(models.Model):
       name=models.CharField(max_length=200)

       def __str__(self):

           return self.name

class Items(models.Model):
    todolist=models.ForeignKey(ToDoList,on_delete=models.CASCADE)
    text=models.CharField(max_length=300)
    complete=models.BooleanField()

    def __str__(self):
        return self.text

A: I shouldnt have added the '/ ' in  /admin which is  inside the urls.py file


text:
Q: get_post_types - exclude multiple post types by name I am trying to get an array of all the post types except for attachments and pages. I've been able to do this with one exclusion like this:
get_post_types(
    array(
        'name' => 'page',
        'public' => false
    ),
    'names',
    'not')
);

This returns all post types except for page as expected. However, I can't seem to get it to work if I try to exclude multiple names. I figured I could just pass in an array like this:
get_post_types(
    array(
        'name' => array('page','attachment'),
        'public' => false
    ),
    'names',
    'not')
);

But this doesn't exclude either of the post types I am trying to exclude. Any ideas?

A: The query args you're passing to get_post_types() are handled by the underlying function wp_filter_object_list(), which isn't designed to handle advanced querying operations like "if key value (not) in array".
Since you're just getting the names of post types, use the native PHP function array_diff to filter the out the ones you don't want:
$post_types = array_diff( get_post_types(), [ 'page', 'attachment' ] );

FWIW, if you were getting post type objects, you could use array_filter with something like:
$post_type_objects = array_filter( get_post_types( [], 'objects' ), function ( $post_type_object ) {
    return ! in_array( $post_type_object->name, [ 'page', 'attachment' ] );
});


text: Q: Can I give a WordPress website 644 file permissions? I have a WordPress website. If I give all files 644 permissions to have better security and prevent malware getting inside my website, will that break anything?


text:
Q: Adding Expression of JsonEqualTo to Ebean query I have a Ebean Query object and would like to add an Object of type expression to the where clause
query.where().add(Expr.jsonEqualTo(,,,))

Is there any way to do this?
query.where().add(Expr.eq(param, value))

is possible for example
I am using EbeanORM 6.8.1 by the way

A: Assuming you programatically want to add some conditions, you could write something like
ExpressionList<Customer> query = Customer.find.where().eq("name", "John");
if (condition)
    query.eq("lastName", "Doe");
query.findList();


text:
Q: Can I use the globe plugin on a Windows OS and where can I find the plugin for QGIS? I am trying to add my layers (health facilities and pertinent infrastructure within a region) to a 3D image of the landscape and someone recommended I use the Globe plugin. I can not find the Globe plugin. Does anyone know where I can find it?/ Will the plugin work for a Windows OS?

A: As of QGIS 2.16, Globe now works on Windows as well, see:

The plugin is installed by default. It only needs to be activated in the plugin manager.

A: According to http://sourcepole.ch/the-state-of-qgis-globe:

The bad news is, that the globe plugin is not working on Windows with OSGeo4W. It seems that one of the OSGeo4W libraries (GDAL?) is compiled with an incompatible MS compiler version.

So the answer is: No.
For other OS, you have to compile it for yourself, or wait until the plugin has entered a stable status. Look out for news here:
http://hub.qgis.org/wiki/17/Globe_Plugin


text:
Q: Scraping basketball-reference.com in R (XML package not fully working) I have been scraping various pages of basketball-ref for a while now in R with the XML package using "readHTMLtable" without any issues, but now I have one. When I try to scrape the splits section of a player's page, it only return the first line of the table not all.
for example:
URL="http://www.basketball-reference.com/players/j/jamesle01/splits/"
tablefromURL = readHTMLTable(URL)
table = tablefromURL[[1]]

this gives me only one row in the table, the first one. I want all the rows however. I think the problem is that there are multiple headers in the table, but I'm not sure how to fix that.
Thanks

A: Why not try the rvest library. You can accomplish this with
library(rvest)
dd <- html_session("http://www.basketball-reference.com/players/j/jamesle01/splits/") %>%
    html_node("table#stats") %>%
    html_table()

It's still a bit messy with the headers mixed in the data, but it does extract the entire table.
Tested with
R version 3.1.0 (2014-04-10)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

other attached packages:
[1] rvest_0.2.0

loaded via a namespace (and not attached):
[1] httr_0.6.1    magrittr_1.5  stringr_0.6.2

A: You can filter on the table bodies:
library(XML)
appURL <- "http://www.basketball-reference.com/players/j/jamesle01/splits/"
doc <- htmlParse(appURL)
appTables <- doc['//table/tbody']

appTables would be a list containing the 12 tables sans headers. To retrieve the headers you can get them from the thead:
myHeaders <- unlist(doc["//thead/tr[2]/th", fun = xmlValue])
myTables <- lapply(appTables, readHTMLTable, header = myHeaders)

You can put the data in one big table using something like:
bigTable <- do.call(rbind, myTables)
> head(bigTable)
Split Value   G  GS    MP   FG   FGA   3P  3PA   FT  FTA  ORB  TRB  AST  STL BLK  TOV   PF   PTS  FG%  3P%  FT%
1          Total 871 870 34364 8582 17289 1184 3462 5553 7432 1049 6239 6011 1483 698 2906 1615 23901 .496 .342 .747
2    Place  Home 441 440 17167 4201  8307  567 1627 2805 3706  507 3133 3082  711 387 1413  744 11774 .506 .348 .757
3           Road 430 430 17197 4381  8982  617 1835 2748 3726  542 3106 2929  772 311 1493  871 12127 .488 .336 .738
4 All-Star   Pre 569 568 22349 5544 11167  759 2205 3576 4791  655 4051 3966  967 456 1940 1087 15423 .496 .344 .746
5           Post 302 302 12015 3038  6122  425 1257 1977 2641  394 2188 2045  516 242  966  528  8478 .496 .338 .749
6   Result   Win 572 571 22196 5783 11094  772 2154 3749 4931  677 4241 4132 1032 496 1793 1016 16087 .521 .358 .760
TS% USG% ORtg DRtg   MP  PTS TRB AST
1 .581 31.9  116  103 39.5 27.4 7.2 6.9
2 .592 30.9  118  102 38.9 26.7 7.1 7.0
3 .571 32.8  114  105 40.0 28.2 7.2 6.8
4 .581 31.7  116  103 39.3 27.1 7.1 7.0
5 .582 32.2  117  104 39.8 28.1 7.2 6.8
6 .606 31.7  122   99 38.8 28.1 7.4 7.2

A: Have a look at the htmltab package (https://github.com/crubba/htmltab). I developed this package for more complex HTML tables where readHTMLTable() is of little use.
devtools::install_github("crubba/htmltab")
library(htmltab)
htmltab(doc = "http://www.basketball-reference.com/players/j/jamesle01/splits/", header = 1:2)


text:
Q: How Git Merge Work? Offline Or Online? I'm Using Tortoise GIT to controll my Repos.
I have 2 branch A, B:
I switch A to B > merge A into B without pull, the result show an Error that I do not pull before.
I switch A to B > merge A into B with pull before, Everything work fine.
So, without pull request, I cannot merge with another branch because source code was not up to date.
And I think merge action requried a pull request before (code must up to date). But code up to date at git, so it may cause of Merge by Tortoise must happen at local (offline)?
So, How Git Merge Work? Offline Or Online?
[Sorry I'm not good at English, please help me to improve this post. Thanks!]

A: In order to avoid any issue you will want to be online, as you are not able to push your edits to a remote branch while offline.
Starting in branch A(local):
Pull branch A(remote).
Make your edits to branch A(local).
Push your edits to branch A(remote).
Checkout branch B(local).
Pull branch B(remote).
Merge branch A(local) into branch B(local).
Push your edits to branch B(remote).
I have left out the commit message portion of it as it seems unnecessary to point out.


text:
Q: How to save settings in IntelliJ IDEA? A couple of months ago I installed IntelliJ IDEA on my Windows 7 development computer. I also installed Maven.
Unfortunately I provided IntelliJ with the wrong path to Maven. Now it seems to be impossible to correct my mistake. I can't reconfigure IntelliJ IDEA with the correct settings to Maven and make my changes persistent, i. e. there is no Save-changes button?

Just pressing OK (or Apply followed by OK) doesn't seem to make IntelliJ remember the settings when it is restarted.
Will I always be doomed to keep my original, error-prone settings, or is there any way to deal with this obstacle? How can I save my new settings?

A: I'm pretty sure the hint is on your screenshot:
"M2_HOME is used by default".
Check your System paths:

*

*Select Computer from the Start menu

*Choose System Properties from the context menu

*Click Advanced system settings > Advanced tab

*Click on Environment Variables

*Under System Variables, find PATH, and click on it.

*Click on the Edit button, find the M2_HOME entry and change the path to the directory you want it to be.


text:
Q: Powershell: Find folders with a specific name, and move contents up one level, rename if exists I've got the first two-thirds of this one accomplished, but I'm stuck on the last part. I've got a script that searches for subfolders with a specific name, and moves their contents up one level. I have another script that moves files from one place to another, and renames them if the file already exists. What I'm trying to do now is merge the two. So here's the one that moves files up:
$sourceDir="E:\Deep Storage"
$searchFolder="Draft Materials"

Get-ChildItem  -path $sourceDir -filter $searchFolder -Recurse |
    ForEach-Object {
        Get-ChildItem -File -Path $_.FullName |
            ForEach-Object {
                Move-Item -Path $_.FullName -Destination $(Split-Path -Parent $_.PSParentPath)
            }
    }

And here's the one that moves things while renaming if they already exist:
$sourceDir="E:\Test1"
$targetDir="E:\Deep Storage\Test1"

Get-ChildItem -Path $sourceDir -Filter *.* -Recurse | ForEach-Object {
    $num=1
    $nextName = Join-Path -Path $targetDir -ChildPath $_.name

    while(Test-Path -Path $nextName)
    {
       $nextName = Join-Path $targetDir ($_.BaseName + "_$num" + $_.Extension)
       $num+=1
    }

    $_ | Copy-Item -Destination $nextName -Verbose
}

And lastly, my attempt to hybridize the two:
$sourceDir="E:\Deep Storage"
$searchFolder="Draft Materials"

Get-ChildItem  -path $sourceDir -filter $searchFolder -Recurse |
    ForEach-Object {
        Get-ChildItem -File -Path $_.FullName |
            ForEach-Object {
    $num=1
    $nextName = Join-Path -Path $_.FullName -Destination $(Split-Path -Parent $_.PSParentPath)

    while(Test-Path -Path $nextName)
    {
       $nextName = Join-Path -Path $_.FullName -Destination $(Split-Path -Parent $_.PSParentPath) ($_.BaseName + "_$num" + $_.Extension)
       $num+=1
    }

    $_ | Copy-Item -Destination $nextName
}
    }

I feel like I'm on the right track, but after two hours of attempts I haven't been able to get this to work.
EDIT: providing the exact syntax I'm giving it
$sourceDir="E:\Deep Storage\Projects"
$searchFolder="Draft Materials"
$destinationPath = "$($sourceDir)\.."

Write-Host "OPERATION: Search for Folders Named" -ForegroundColor White -BackgroundColor DarkGreen -NoNewLine;
Write-Host " '$searchFolder' " -ForegroundColor Yellow -BackgroundColor DarkGreen -NoNewLine;
Write-Host "and Move Contents Up One Level" -ForegroundColor White -BackgroundColor DarkGreen;
Write-Host "SEARCHDIR: $sourceDir" -ForegroundColor White -BackgroundColor DarkGreen;

# Get all directories in specific folders inside the source directory
$folders = Get-ChildItem -Path $sourceDir -Directory | Where-Object {$_.Name -like "$searchFolder*" -or $_.FullName -like "*\$searchFolder\*"}

foreach ($folder in $folders) {
    # Get all files in the current folder
    $files = Get-ChildItem -Path $folder.FullName

    foreach ($file in $files) {
        $destinationFile = Join-Path -Path $destinationPath -ChildPath $file.Name
        if (Test-Path $destinationFile) {
            # If a file with the same name exists in the destination directory, rename it
            $name = $file.Name
            $extension = $file.Extension
            $i = 0
            while (Test-Path $destinationFile) {
                $i++
                $name = "{0}_{1}{2}" -f ($file.BaseName, $i, $extension)
                $destinationFile = Join-Path -Path $destinationPath -ChildPath $name
            }
            Write-Host "Renaming $($file.Name) to $name"
        }
        Move-Item $file.FullName $destinationFile -Verbose -WhatIf
    }

}

A: Here's what I came up with reading OP's post, code, and comments:
$sourcePath      = 'E:\Deep Storage\Projects'
$searchFolder    = 'Draft Materials'

Write-Host "OPERATION: Search for Folders Named" -ForegroundColor White -BackgroundColor DarkGreen -NoNewLine;
Write-Host " '$searchFolder' " -ForegroundColor Yellow -BackgroundColor DarkGreen -NoNewLine;
Write-Host "and Move Contents Up One Level" -ForegroundColor White -BackgroundColor DarkGreen;
Write-Host "SEARCHDIR: $sourcePath" -ForegroundColor White -BackgroundColor DarkGreen;

# Get all directories in specific folders inside the source directory
$folders = (Get-ChildItem -LiteralPath $sourcePath -Directory -Recurse) | Where-Object Name -match $searchFolder

### Check selected folders
    $Folders.FullName | Out-GridView -Title 'Selected Folders'
    Read-Host 'Paused. Check selected folders in GridView. Press <enter> to continue '
###

ForEach ($folder in $folders)
{
    # Get all files in the current folder
    $filesToCopy   = $folder | Get-ChildItem -File
    # Get list of names for exising files in target (parent folder)
    $targetPath    = $folder.Parent.FullName
    $filesInTarget = (Get-ChildItem -LiteralPath $targetPath -File).Name

    ForEach ($file in $filesToCopy)
    {
        If ($file.Name -notIn $filesInTarget)
        {
            $file | Move-Item -Destination $targetPath -Verbose -WhatIf
        }
        Else
        {
            $i = 0
            Do
            {
                $newName = '{0}_{1}{2}' -f ($file.BaseName, $i++, $file.Extension)
            } Until ( $newName -notIn $FilesInTarget )

            Write-Host ('Renaming "{0}" to "{1}"...' -f $file.Name , $newName)

            $file | Move-Item -Destination (Join-Path $targetPath $newName) -Verbose -WhatIf
        }
    }
    # Delete (hopefully empty) folder
    If (!($folder | Get-ChildItem -Force))
    {
        $folder | Remove-Item -WhatIf
    }
    Else
    {
        Write-Host ('Items still exist in "{0}". Folder not deleted.' -f $folder.FullName)
    }
}

*

*Syntax choice: For any cmdlet that has Path/LiteralPath parameter sets (gci, Copy, Move, Rename, etc.), the System.IO.FileSystemInfo | <Cmdlet> syntax succeeds with items that would fail in the <Cmdlet> -Path (System.IO.FileSystemInfo).FullNaame form becasue special characters in their name would require the -LiteralPath parameter.
In many cases replacing -Path with -LiteralPath (or its alias: -lp) will work as well. But the pipelined format reads "cleaner" (IMHO) when scanning code and, if you're just learning PowerShell, reminds you to think in terms of pipelining whenever possible and avoiding intermediate variables. Just for grins, here's a version of the above code where items are piped as much as possible, using ForEach-Object:
 (Get-ChildItem -LiteralPath $sourcePath -Directory -Recurse) |
     where Name -match $searchFolder |
 ForEach-Object {
     # Get list of names for exising files in target (parent folder)
     $targetPath    = $_.Parent.FullName
     $filesInTarget = (Get-ChildItem -LiteralPath $targetPath -File).Name

     $_ | Get-ChildItem -File | ForEach-Object {
         If ($_.Name -notIn $filesInTarget)
         {
             $_ | Move-Item -Destination $targetPath -Verbose -WhatIf
         }
         Else
         {
             $i = 0
             Do
             {
                 $newName = '{0}_{1}{2}' -f ($_.BaseName, $i++, $_.Extension)
             } Until ( $newName -notIn $FilesInTarget )

             Write-Host ('Renaming "{0}" to "{1}"...' -f $_.Name , $newName)

             $_ | Move-Item -Destination (Join-Path $targetPath $newName) -Verbose -WhatIf
         }
     }
     # Delete (hopefully empty) folder
     If (!($_ | Get-ChildItem -Force))
     {
         $_ | Remove-Item -WhatIf
     }
     Else
     {
         Write-Host ('Items still exist in "{0}". Folder not deleted.' -f $_.FullName)
     }
 }

A: please try this:
$sourcePath = "C:\temp\test\Test"
$destinationPath = "$($sourcePath)\.."

# Get all files in the source directory
$files = Get-ChildItem -Path $sourcePath

foreach ($file in $files) {
    $destinationFile = Join-Path -Path $destinationPath -ChildPath $file.Name
    if (Test-Path $destinationFile) {
        # If a file with the same name exists in the destination directory, rename it
        $name = $file.Name
        $extension = $file.Extension
        $i = 0
        while (Test-Path $destinationFile) {
            $i++
            $name = "{0}_{1}{2}" -f ($file.BaseName, $i, $extension)
            $destinationFile = Join-Path -Path $destinationPath -ChildPath $name
        }
        Write-Host "Renaming $($file.Name) to $name"
    }
    Move-Item $file.FullName $destinationFile
}

This will not delete the original location and will move everything from the sourcePath to the parent location.
To delete the original location just add at the end:
Remove-Item -Path $sourcePath -Force -Confirm:$false

UPDATE1:
$sourcePath = "C:\temp\test\Test"
$destinationPath = "$($sourcePath)\.."

# Get all directories in specific folders inside the source directory
$folders = Get-ChildItem -Path $sourcePath -Directory | Where-Object {$_.Name -like "Folder1*" -or $_.FullName -like "*\Folder2\*"}

foreach ($folder in $folders) {
    # Get all files in the current folder
    $files = Get-ChildItem -Path $folder.FullName

    foreach ($file in $files) {
        $destinationFile = "$($folder.FullName)\.."
        if (Test-Path $destinationFile) {
            # If a file with the same name exists in the destination directory, rename it
            $name = $file.Name
            $extension = $file.Extension
            $i = 0
            while (Test-Path $destinationFile) {
                $i++
                $name = "{0}_{1}{2}" -f ($file.BaseName, $i, $extension)
                $destinationFile = Join-Path -Path $destinationPath -ChildPath $name
            }
            Write-Host "Renaming $($file.Name) to $name"
        }
        Move-Item $file.FullName $destinationFile
    }

}


text:
Q: Python - How to return array for a textarea without default array annotations? In Django/Python I want to return the words in an array to display in a textarea. The only problem is how I seem to be returning the array, as I have extra annotations:

[u'[[MY | My]]', u'first', u'sentence', u'[[WITH | With]]', u'a', u'[[CAPITAL | Capital]]', u'[[LETTER | Letter]]']

This is with:
def respond_wikify(original):
    wikified = re.sub("[^\w]", " ",  original).split()

    concat = lambda word: "[[" + word.upper() + " | " + word + "]]"

    for i, word in enumerate(wikified):
        if word[0].isupper():
            wikified[i] = concat(word)

    return " ".join(wikified)

But if I do this:
return " ".join(for word in wikified)

I get this error:
Internal error:java.lang.ClassCastException: org.python.pydev.parser.jython.ast.Return cannot be cast to org.python.pydev.parser.jython.ast.exprType

Which is frustrating since I'm not using Jython, however I am using Eclipse PyDev.
How do I remove the first and last '[]' the commas and the 'u's?
Before I added the if statement this worked as expected:
def respond_wikify(original):
    wikified = re.sub("[^\w]", " ",  original).split()

    concat = lambda word: "[[" + word.upper() + " | " + word + "]]"
    return " ".join([concat(word) for word in wikified])


text:
Q: what is the difference between utf8 and utf-8? just wondering that what is the difference between utf8 and utf-8? or they are just the same? as I have read in an answer here at SO saying use utf8 for PDO as utf-8 generate errors sometimes.
EDITS
where would utf-8 be invalid to use? (as answered in another similar question)

A: There is no difference between "utf8" and "utf-8"; they are simply two names for UTF8, the most common Unicode encoding.


text:
Q: TypeError: expected string or buffer - Пытаюсь обновить запись в БД через update_or_create с использованием choices Модели
class Showtimes(models.Model):

    active_status = 1
    deactivated_status = 2

    status_choices = (
        (active_status, 'Active'),
        (deactivated_status, 'Deactivated'),
    )

    buy_ticket_url = models.URLField('Buy ticket URL', max_length=255, blank=True)
    date_time = models.DateTimeField('Show start date-time')
    status = models.IntegerField('Showtime Status', choices=status_choices, default=active_status)

    showtime_show = models.ForeignKey(Shows, on_delete=models.CASCADE, verbose_name='Show name')
    showtime_place = models.ForeignKey('app_places.Places', on_delete=models.CASCADE, verbose_name='Place')

class ShowtimeMovies(Showtimes):
    movie_format = models.CharField('Movie Format', max_length=10, blank=True)

Кусок кода, где возникает ошибка (строка status='active_status')
ShowtimeMovies.objects.update_or_create(
    showtime_place=get_cinema,
    showtime_show=get_movie,
    date_time=date_time,
    defaults=dict(
        buy_ticket_url=buy_ticket_url,
        movie_format=show_format,
        status='active_status')

Пробовал менять статус на active_status, Active, 'Active', 1 - ничего не помогает. Пробовал проимпортировать класс модели в модуль, где код выполняется. С Чёйсами первый раз имею дело. Что делаю не так?

Решение проблемы.
Шаг 1.
Ввиду того, что создается инстанс дочерней модели, то нужно было
active_status = 1
deactivated_status = 2

status_choices = (
    (active_status, 'Active'),
    (deactivated_status, 'Deactivated'),
)

перенести из Showtimes в ShowtimeMovies.
Шаг 2.
Заменить строку
status='active_status' на status=ShowtimeMovies.active_status, как и было предложено Алексеем ниже.
В итоге получаем:
ShowtimeMovies.objects.update_or_create(
    showtime_place=get_cinema,
    showtime_show=get_movie,
    date_time=date_time,
    defaults=dict(
        buy_ticket_url=buy_ticket_url,
        movie_format=show_format,
        status=ShowtimeMovies.active_status)

A: Ну во первых что за defaults? У вас нет такого поля в моделе. А атрибут default в классе Models содержит значение данного поля по умолчанию (то-есть если его не задавать при создании - в объект будет автоматически подставлено значение default)
Во вторых если вам нужно задать статус используя choise, это будет выглядеть так:
status = ShowtimeMovies.active_status

только я настоятельно рекомендую именовать константы в UPPER_CASE, то есть заменить active_status и deactivated_status на ACTIVE_STATUS и DEACTIVE_STATUS соответственно. Это будет более правильно, так вам будет проще работать с другими Python разработчиками, и избавит вас от путаницы ведь константу в lower_case можно перепутать с атрибутом или методом класса.
Весь ваш код судя по всему должен выглядеть так:
ShowtimeMovies.objects.update_or_create(
    showtime_place=get_cinema,
    showtime_show=get_movie,
    date_time=date_time,
    buy_ticket_url=buy_ticket_url,
    movie_format=show_format,
    status=ShowtimeMovies.active_status
)


text:
Q: Resource Versioning in Spring MVC 4 Can any one help me to  achieve Resource Versioning in my web application
my dispatcher-servlet.xml is
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"

    xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                            http://www.springframework.org/schema/context
                            http://www.springframework.org/schema/context/spring-context-4.0.xsd
                            http://www.springframework.org/schema/tx
                            http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
                            http://www.springframework.org/schema/mvc
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
                            http://www.springframework.org/schema/aop
                            http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <!-- Declare a view resolver -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/WEB-INF/view/" p:suffix=".jsp" p:order="1" />
    <context:annotation-config />
    <context:component-scan base-package="com.safecare" />
    <mvc:annotation-driven />
    <mvc:interceptors>
        <bean id="webContentInterceptor"
            class="org.springframework.web.servlet.mvc.WebContentInterceptor">
            <property name="cacheSeconds" value="0" />
            <property name="useExpiresHeader" value="false" />
            <property name="useCacheControlHeader" value="true" />
            <property name="useCacheControlNoStore" value="true" />
        </bean>
    </mvc:interceptors>
    <mvc:annotation-driven />

    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource"
        p:basename="Messages" />
    <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager"
        p:sessionFactory-ref="sessionFactory" />
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <!--<prop key="hibernate.hbm2ddl.auto">update</prop>-->
                <prop key="hibernate.show_sql">true</prop>
<!--                <prop key="hibernate.c3p0.min_siz">5</prop>
                <prop key="hibernate.c3p0.max_size">50</prop>
                <prop key="hibernate.c3p0.timeout">3000</prop>
                <prop key="hibernate.c3p0.max_statements">50</prop>
                <prop key="hibernate.c3p0.idle_test_period">3000</prop>-->
            </props>
        </property>
        <property name="packagesToScan" value="com.safecare"></property>
    </bean>
<bean id="dataSource"
              class="org.springframework.jdbc.datasource.DriverManagerDataSource"
              p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:8080/cortex_mcss_test1"
              p:username="root" p:password="mysql" />
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
    <bean class="org.springframework.web.servlet.view.XmlViewResolver"
        p:location="/WEB-INF/JasperReport-View.xml" p:order="0" />
</beans>

and I did add the below code in the above xml and it create an error

columnNumber: 18; cvc-complex-type.2.1: Element 'mvc:resources' must have no character or element information item [children], because the type's content type is empty.

<mvc:resources mapping="/resources/**" location="/, classpath:/META-INF/">
<mvc:cache-control max-age="3600" s-maxage="1800" cache-public="true"/>
<mvc:resource-chain resource-cache="false" auto-registration="false">
    <mvc:resolvers>
        <mvc:version-resolver>
            <mvc:fixed-version-strategy version="abc" patterns="/**/*.js"/>
            <mvc:version-strategy patterns="/**">
                <bean class="org.springframework.web.servlet.resource.ContentVersionStrategy" />
            </mvc:version-strategy>
        </mvc:version-resolver>
        <ref bean="encodedResourceResolver"/>
        <bean class="org.springframework.web.servlet.resource.PathResourceResolver"/>
    </mvc:resolvers>
    <mvc:transformers>
        <bean class="org.springframework.web.servlet.resource.CachingResourceTransformer">
            <constructor-arg name="cache" ref="resourceCache" />
        </bean>
        <bean class="org.springframework.web.servlet.resource.AppCacheManifestTransformer"/>
    </mvc:transformers>
</mvc:resource-chain>

any one know any proper document for the above

A: Add the self closing tag.
Change
 <mvc:resources mapping="/resources/**" location="/, classpath:/META-INF/">

to
 <mvc:resources mapping="/resources/**" location="/, classpath:/META-INF/" />


text:
Q: Join tables and project into a new model I am new to Linq. I have been using strongly typed data-sets but like the idea of Linq to create objects.
At the moment I use datasets to retrieve a table that joins data from tblProducts and tblProductSettings.
This is a one to many relationship as the products serve multiple websites with a unique tblSettings row for each website, however its assumed that there is always one row for tblSettings per website.
Example :
Select * from tblproducts, tblProductSettings where tblproducts.ProdID = tblProductSettings.ProdID and tblProductSettings.CreatorID = @CreatorID

The dataset will give a nice table to loop through and display the products with the settings.
Linq will give me a tblProducts object with tblProductSettings as a collection. I don't want to have to loop a collection each time to get the settings as this will, i believe create a new sql query for each product and make accesses the settings a pain.
I can create a custom object tblProductsAll, but the only way I can fill this object is...
var Product = from p in context.tblProducts
              join ps in context.tblProductSettings on p.ProdID equals ps.ProdID
              where p.CreatorID == 1 && ps.ProdCreatorDisplay == 1
              select new tblProductsAll()
              {
                   ProdTitle = p.ProdTitle,
                   ProdPrice = ps.ProdPrice
              };

I can then pass this model to the razor template.
My question is... is there a better way of setting the properties ? There are 20 or more different properties and i don't want to have to keep setting them, repeating code, every time i want the same object somehwere in the site with a differnt where clause.  Is there a way to stop this repetition ? i.e. automatically mapping the object, or reusing the select new statement.
Any help would be much appreciated.

A: Since you've tagged this sql, I'm guessing you are using Entity Framework.  In that case, you can tell linq it to load the settings for your products without explicitly specifying the join.  I'm assuming here your products has a relationship to your product settings table which is exposed via a Settings property on your product entity.
var allProducts = context.tblProducts
    .Where(p => p.CreatorID == 1 && p.Settings.ProdCreatorDisplay == 1)
    .Include(p = p.Settings)
    .Select(p => CreateViewModelFromFullyPopulatedProductModel(p))
    .ToList();

Once you have the full settings loaded, you can just write a mapping function that does the mapping for you.  Of course this will load all of the properties of the products and the settings for each of those products.  That can be a major concern depending on how many products you are loading and how many unused properties they have, but from your question, it sounds like you are loading most of these values for the view model already.

A: When there are navigation properties, use them! Your Product entity has a navigation property ProductSettings. That means that the query could look like this:
var products = from p in context.Products
               from ps in p.ProductSettings
               where p.CreatorID == 1 && ps.ProdCreatorDisplay == 1
               select new ProductsAll()
               {
                    ProdTitle = p.ProdTitle,
                    ProdPrice = ps.FirstOrDefault().ProdPrice
               };

(Note that I stubbornly refuse to use the tbl prefix)
But that does not tackle the repetitive code issue.
Enter AutoMapper. This is a nice little tool that removes boilerplate property copying statement from your code by defining and executing mappings between objects. The default mapping is based on name convention. E.g. the statement Mapper.CreateMap<Product,ProductDto>(); configures a mapping between all equally named properties of Product and ProductDto. And Mapper.Map<ProductDto>(product); would create a ProductDto object from product.
But your ProductsAll class has a property ProdPrice that comes from ProductSettings. How to deal with that?
Here a nice feature of AutoMapper can be used. It also resolves properties of nested objects based on name convention. Suppose your class Product had a property Title, AutoMapper can resolve that to a property ProductTitle in the target object. Let's use that:
class ProductsAll
{
    // ProductSetting should have a Product property.
    public string ProductTitle { get; set; }
    // Assuming ProductSetting has a property ProdPrice.
    public decimal ProdPrice { get; set; }
}

...

Mapper.CreateMap<ProductSetting,ProductsAll>(); // ProductSetting!

var q = from ps in context.ProductSettings
        where ps.Product.CreatorID == 1 && ps.ProdCreatorDisplay == 1;

// Now the magic!
var products = q.Project().To<ProductsAll>();

Project() is an extension method on IQueryable. The nice thing is that the SQL statement only contains the properties used in the projection. As you see, you can define a mapping once and for the rest use the Project().To() construct in your code.
There's much more to AutoMapper. This is a quick start.


text:
Q: WHy doesn't Netbeans also mark functions as occurences (Javascript)? The mark occurences option in Netbeans doesn't work on function names for me. I'm on version 6.9.1. Anybody know how to possibly make that work?

A: You could use functions expressions, like this:
var func;

func = function () {
    //code
};

Then Netbeans marks it too. I couldn't find another way.
Remember about declaring variables for future functions. Notice a semicolon after definition.
Also this answer should be helpful.


text:
Q: How to convert UTC datetime to different format I have a datetime string in the following format.
var datetime="Thu May 5 05:30:00 UTC+0530 2011" ;
I want to convert it in the following format. How can I do it in javascript
"Thursday, 05 May 2011"

A: The globalize plugin has date parsing and formatting features.
Here is an example from the plugin page:
Globalize.format( new Date(1955,10,5), "dddd MMMM d, yyyy" ); // "Saturday November 5, 1955"

A: The date.js library is very useful for working with Dates.
Formatting examples:
Date.today().toString("dddd MMMM d, yyyy"); // Monday November 19, 2007
Date.today().toString();                    // native .toString() functionality
Date.today().toString("M/d/yyyy");          // 11/19/2007
Date.today().toString("d-MMM-yyyy");        // 19-Nov-2007
new Date().toString("HH:mm");               // 18:45

Parsing examples:
Date.parse('today');
Date.parse('t + 5 d'); // today + 5 days
Date.parse('next thursday');
Date.parse('February 20th 1973');
Date.parse('Thu, 1 July 2004 22:30:00');


text:
Q: How to Queue/Delay a function from starting if that same function is running elsewhere I'm kinda new to threadding stuffs and want to ask how to fix this problem.
There are 3 different places to call a printing function (from a printing class).
Current pseudo-code is like this.
fun printOrderDirect(params) {
  PrintClass.execute(params) // using Rx
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(object: Subscriber<Int>() {
      override fun onNext(t: Int) { response = t }
      override fun onCompleted() {}
      override fun onError(e: Throwable?) { log(e) }
    })
}

fun printOrderRemote(params) { // called when receiving signal online
  PrintClass.execute(params).observeOn(Schedulers.immediate())
    .subscribe(object: Subscriber<Int>() {
      override fun onNext(t: Int) { response = t }
      override fun onCompleted() {
        // Do some filtering and call another print job for online order
        PrintClass.execute(params).observeOn(Schedulers.immediate())
          .subscribe(object: Subscriber<Int>() {
            override fun onNext(t: Int) { response = t }
            override fun onCompleted() {}
            override fun onError(e: Throwable?) { log(e) }
          })
      }
      override fun onError(e: Throwable) { log(e) }
    })
}

The PrintClass code:
class PrintClass {
  fun execute(params): Observable<Int> {
    return Observable.create<Int> { subscriber ->
      // do a lot of filtering, formatting stuffs
      val task = PrintTask()
      task.execute().observeOn(Schedulers.immediate())
        .subscribe(object: Subscriber<Int>() {
          override fun onNext(t: Int?) {}
          override fun onCompleted() {
            subscriber.onNext(RESPONSE_OK)
            subscriber.onCompleted()
          }
          override fun onError(e: Throwable) {
            subscriber.onNext(RESPONSE_FAIL)
            subscriber.onError(e)
          }
        })
    }
      .onBackpressureBuffer()
      .subscribeOn(Schedulers.newThread())
  }
}

For the last 2 places to call the print job, it's being chained so it's okay, the first task needs to be completed in order to run the other.
But in the case of many online orders coming at once (the order update is not realtime, just syncing once every 90 secs, but in that timeframe, there can be many orders filling in), or simply just direct order + 1 order online at once may cause congestions (the printing machine buffer or cache (idk how it's called) is pretty small I guess).
I would like to know how to block the PrintClass.execute() task from running when it's already running from another call. But not like stopping it, just delay/queue it until the previous one finished.
The printing machine dies everytime 3+ online orders coming in.
I can't use Kotlin coroutines since the current codebase Kt version is super low. I tried my best to learn Rx and migrated from AsyncTask to Rx already.
I've tried using Lock.lock() before starting the PrintClass.execute() in the two functions and Lock.unlock() in onCompleted() but it would freeze my UI and getting ANR error if the print jobs are too long.
Thanks everyone in advance.

A: You could use a global serialized PublishSubject and submit the params to it. Then a concatMap will make sure only one PrintTask.execute runs and captures the result.
Subject<Params> subject = PublishSubject.create().toSerialized();

subject.observeOn(Schedulers.io())
.concatMap(params -> {
    return PrintTask.execute(params)
           .observeOn(AndroidSchedulers.mainThread())
           .doOnNext(t -> { response = t })
           .onErrorResumeNext(e -> { log(e); return Observable.empty(); });
})
.subscribe();

fun printOrderDirect(params: Params) {
  subject.onNext(params);
}

fun printOrderRemote(params: Params) {
  subject.onNext(params);
}


text:
Q: YouTube embed not tracking views A client of mine has just launched a Youtube channel. The majority of their users are expected to watch via an on-site video embed since that's where all their marketing comms are sending them. The embedded iframe has the following code:
<iframe id="fv-111253" src="https://www.youtube.com/embed/-tbdf3_LHfA?modestbranding=1&showinfo=0&rel=0&iv_load_policy=3&origin=https%3A%2F%2Ferp.today&widget_referrer=https%3A%2F%2Ferp.today" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen=""></iframe>

A live example is here: https://erp.today/tv/
Despite 700 unique page views reported by Google Analytics, we don't seem to be seeing any views attributed to the embedded player in YouTube Analytics. External Traffic Sources list some social media sites, and Playback Location only shows "YouTube watch-page".
When watching the Realtime stats, sometimes we see a view pop in the chart after 1 to 5 minutes, that may correspond to one of us testing, but other times we don't, so we can't be sure it's not a coincidence. And still it's not attributed anywhere to the embedded player.
I've tried:

*

*Setting the origin & widget_referrer params (originally these were not in the iframe URL)

*Ensured there are full views from 18 different people via the embedded player (so it's not the >30s filter)

*It's not on autoplay

*Stopped using the nocookie domain in case that was it

The fact I cannot point to the analytics and say "look, here's the view counts from your site so they are working and your stats are low but must be correct" means I cannot confirm analytics are working correctly.
Does anyone know what I need to do, to make the website views show up in YT analytics, preferably as a separate "external source"?


text:
Q: Multitenant GraphQL Server We are exploring GraphQL server for our SaaS multi-tenant services where we have multiple microservices / services behind a single multi-tenant GraphQL server. Now we have a situation where client's can extend their GQL schema through our preferred mechanism;
so is there any way in which we can still have a single GQL server that will be serving multiple GQL schemas through multiple endpoints?
Or we will have to deploy each client's GQL server + schema in totally separate server?

A: You can have multiple schemas served by the same application. GraphQL Schemas can even be built at runtime. Maybe you could even use the fastify GraphQL middleware. For more complicated things, you will probably have to build your own middleware, but this would be totally possible.
Creating multiple endpoints with different schemas is easy. You can simply mount more GraphQL middlewares:
for (const customer of customers) {
  app.register(graphqlFastify, {
    prefix: '/' + customer.name + '/graphql',
    graphql: {
      schema: customer.schema,
    },
  });
}

But this probably does not scale very well. You might want to use a route with a parameter instead and then you execute the GraphQL function yourself. Maybe, you could combine this with graphql-helix:
import { graphql } from 'graphql';

fastify.get('/:username/graphql', (request, reply) => {
  const { queryString, variables, operationName } = getGraphQLParams(request);
  const schema = getUserSchema(request.username);

  return graphql(schema, queryString, rootVal, context, variables, operationName);
});

All code above is not tested and I don't know fastify nearly enough to create working code. But I hope this shows the possibilities.


text:
Q: Alternar cor do texto de acordo com a cor do background Como posso fazer para alternar a cor de um texto, de acordo com a cor de background em que ele está inserido?
Eu já vi isso algumas vezes. Funciona assim: se o background for claro, o texto fica preto, e se for escuro, o texto fica branco.
Eu tentei procurar o site em questão, mas já me esqueci. Era mais ou menos isso: O texto ficava em cima de uma capa de artigo, então, como a capa do artigo pode variar de cor, o texto se adaptava ao background (imagem)
Como isso é feito?

A: Voce precisa de uma função que receba o hexadecimal do background para poder quebrar ele em rgb e então calcular se a fonte deve ser escura ou clara a partir dos valores do rgb, retornando assim a cor da fonte. Segue um exemplo:
const TextColor = hex => {
    let shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, (m, r, g, b) => {
        return r + r + g + g + b + b;
    });
    let rgb = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    rgb = (rgb ? { r: parseInt(rgb[1], 16), g: parseInt(rgb[2], 16), b: parseInt(rgb[3], 16) } : { r: 0, g: 0, b: 0 });
    return '#' + (Math.round(((parseInt(rgb.r) * 299) + (parseInt(rgb.g) * 587) + (parseInt(rgb.b) * 114)) /1000) > 150 ? "555" : "FFF" );
}


text:
Q: GNU screen: how to resume my screen session reliably? I was unable to resume my screen session this morning, even after I killed the old screen -r session.
svtbuild@dvm-2:~/rfs$ screen -r 17757.pts-0.dvm-2
There is a screen on:
    17757.pts-0.dvm-2   (11/27/2012 04:49:19 PM)    (Attached)
There is no screen to be resumed matching 17757.pts-0.dvm-2.

After waiting for a while I was able to resume.  How can I do this more reliably?

A: From the screen manpage:
screen -D -R
Attach here and now. In detail this means: If a session is running, then reattach.
If necessary detach and logout remotely first. If it was not running create it
and notify the user.

As mentioned for the options -D -RR, unless you know the status of your session(s), you should check it with screen -list.


text:
Q: How to work with liquibase, a concrete example Following the quickstart on liquibase i've created a changeset (very dumb :) )
Code:
<?xml version="1.0" encoding="UTF-8"?>

<databaseChangeLog
  xmlns="http://www.liquibase.org/xml/ns/dbchangelog/1.6"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog/1.6
         http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-1.6.xsd">

    <changeSet id="1" author="me">
        <createTable tableName="first_table">
            <column name="id" type="int">
                <constraints primaryKey="true" nullable="false"/>
            </column>
            <column name="name" type="varchar(50)">
                <constraints nullable="false"/>
            </column>
        </createTable>
        <createTable tableName="new_table">
            <column name="id" type="int">
                <constraints primaryKey="true" nullable="false"/>
            </column>
        </createTable>
    </changeSet>

</databaseChangeLog>

I've created a clean schema and i've launched the migrate command.
Liquibase created the database, with the support tables databasechangelog and ..lock.
Now how i can track the changes?? i've modified the changeset adding a new createTable element but when i try the command "update" liquibase tells me this
Migration Failed: Validation Failed:
     1 change sets check sum

so i don't think to have understood the way to work with liquibase.
Someone may point me to the right direction??
Thanks

A: You should never modify a <changeSet> that was already executed. Liquibase calculates checksums for all executed changeSets and stores them in the log. It will then recalculate that checksum, compare it to the stored ones and fail the next time you run it if the checksums differ.
What you need to do instead is to add another <changeSet> and put your new createTable element in it.
QuickStart is good readin' but it is indeed quick :-) Check out the full manual, particularly its ChangeSet section.

A: If it's a change to a changeset that basically has already been done, you can manually modify the database so that its md5 for that changeset matches the new one.  Good for minor textual changes.  Or you can delete that changeset row from your table.

A: This currently accepted answer is slightly out of date based on changes in Liquibase 2.x. In the 2.x version, Liquibase will still fail if the md5 checksum has changed for a changeset, but you can specify the runOnChange attribute if you want to be able modify it.
From the documentation:

runOnChange - Executes the change the first time it is seen and each time the change set has been changed


text:
Q: Pip does not install dependencies declared in setup.py with install_requires In a Python project, I am using install_requires in my setup.py as follows.
install_requires=['numpy', 'scipy', 'matplotlib']

I then create the source, binary and wheels as follows.
python setup.py sdist bdist bdist_wheel

When I publish, I use twine.
twine upload --repository dist/testpypi mypackage-0.1.1-py2-none-any.whl

In a Python 2.7 conda environment, I then attempt to test the install.
pip install -i https://test.pypi.org/simple/ mypackage==0.1.1

However, I get the following error message:

ERROR: Could not find a version that satisfies the requirement matplotlib (from mypackage) (from versions: none)
ERROR: No matching distribution found for matplotlib (from mypackage)

When I do a pip list and conda list, indeed, there is no matplotlib package listed.
What am I doing wrong? I thought (this point is where my understanding breaks down) that install_requires would list the prerequistes and pip install would pick up on that and automatically install the requirements? However, it seems that install_requires is acting as a guard against installing a package if its declared dependencies are not already installed.
In some internet searches, they seem to suggest that I include a requirements.txt via MANIFEST.in (e.g. include requirements.txt) and then pip install will auto-install the dependencies. However, after trying that approach, I still get the same error message. I tried with requirements.txt as follows.
matplotlib

And also as follows.
matplotlib>=2.2.3

How do I configure/setup setup.py and my distribution such that pip install or conda install will auto-install the declared dependencies via install_requires?

A: The problem is that pip looks for packages in same repository as selected package. So if you provide to use https://test.pypi.org/simple/ then it looks here for packages instead on https://pypi.org/simple/.
U think that you need to use --extra-index-url parameter
--extra-index-url <url>     Extra URLs of package indexes to use in addition to --index-url. Should follow the same rules as --index-url.

So try:
pip install -i https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ mypackage==0.1.1


text:
Q: java jButton.doClick() not perform the function (but clicks the button) I'm making a calculator using a textfield to show the results and allowing the user to type the numbers and operations (without clicking buttons). In the textfield I have a problem when the user type something, if it's a valid char i want to do a .doClick() in the corresponding button. I can see the simulated click on the button, but the "cerebro" method is not executed. Where is the problem? Thanks.
This is the code which execute the doClick():
    private void campotextoKeyPressed(java.awt.event.KeyEvent evt) {
    char teclapulsada = evt.getKeyChar();

    switch(teclapulsada){
        case '0': b0.doClick();
                    break;
        case '1': b1.doClick();
                    break;
        case '2': b2.doClick();
                    break;
        case '3': b3.doClick();
                    break;
        case '4': b4.doClick();
                    break;
        case '5': b5.doClick();
                    break;
        case '6': b6.doClick();
                    break;
        case '7': b7.doClick();
                    break;
        case '8': b8.doClick();
                    break;
        case '9': b9.doClick();
                    break;
    }

}

And this method make the operations when the user clicks a button:
double operando1 = 0;
double operando2 = 0;
char operador = ' ';
private void cerebro(java.awt.event.MouseEvent evt) {
    javax.swing.JButton botonllamador = new javax.swing.JButton();
    botonllamador = (javax.swing.JButton) evt.getSource();

    try {
        int pulsacion = Integer.parseInt(botonllamador.getText());
        if (pulsacion >= 0 && pulsacion <= 9) {
            if (campotexto.getText().equals("0")) {
                campotexto.setText(botonllamador.getText());
                System.out.println("HOLE 0");
            } else {
                campotexto.setText(campotexto.getText() + botonllamador.getText());
                System.out.println("HOLA 1");
            }
        }
    } catch (Exception e) {
        //Si pulsas algo que no sea un número
        String operacion = botonllamador.getText();
        //Si ya hay un operador introducido, hacemos la operacion
        if (operacion.equals("CE")) {
            if(operador != ' '){
                int posoperador = campotexto.getText().indexOf(operador);
                campotexto.setText(campotexto.getText().substring(0, posoperador+1));
            }else{
                campotexto.setText("0");
            }
        } else if(operacion.equals("C")) {
            operando1 = 0;
            operador = ' ';
            campotexto.setText("0");
            System.out.println("CAMPOTEXTO ES "+campotexto.getText());
        } else {
            if (operador != ' ') {
                //Si es un operador, buscamos la posicion, substring para el operando 2 y hacemos la operacion
                int posoperador = campotexto.getText().indexOf(operador);
                if (posoperador != (campotexto.getText().length()-1)) {
                    operando2 = Double.parseDouble(campotexto.getText().substring(posoperador + 1));
                    if (operador == '+') {
                        System.out.println("CAMPOTEXTO TIENE "+campotexto.getText());
                        System.out.println("ENTRO EN + Y AHORA CAMPOTEXTO TIENE"+campotexto.getText()+" EL OPERADOR ES "+operador+" OPERACION ES "+operacion);
                        operando1 = operando1 + operando2;
                    } else if (operador == '-') {
                        System.out.println("ENTRO EN - Y AHORA CAMPOTEXTO TIENE"+campotexto.getText()+" EL OPERADOR ES "+operador+" OPERACION ES "+operacion);
                        operando1 = operando1 - operando2;
                    } else if (operador == '*') {
                        System.out.println("ENTRO EN * Y AHORA CAMPOTEXTO TIENE"+campotexto.getText()+" EL OPERADOR ES "+operador+" OPERACION ES "+operacion);
                        operando1 = operando1 * operando2;
                    } else if (operador == '/') {
                        System.out.println("ENTRO EN / Y AHORA CAMPOTEXTO TIENE"+campotexto.getText()+" EL OPERADOR ES "+operador+" OPERACION ES "+operacion);
                        operando1 = operando1 / operando2;
                    } else if (operador == '.'){
                        operando1 = Double.parseDouble(campotexto.getText());
                    }

                    if(operacion.charAt(0) == '.'){
                        campotexto.setText(campotexto.getText()+".");
                    }else if (operacion.charAt(0) != '=') {
                        operador = operacion.charAt(0);
                        campotexto.setText(operando1 + operacion);
                        System.out.println("ENTRO EN EL FINAL Y AHORA CAMPOTEXTO TIENE"+campotexto.getText()+" EL OPERADOR ES "+operador+" OPERACION ES "+operacion);
                    } else {

                        campotexto.setText(String.valueOf(operando1).toString());
                        System.out.println("ENTRO EN = Y AHORA CAMPOTEXTO TIENE"+campotexto.getText()+" EL OPERADOR ES "+operador+" OPERACION ES "+operacion);
                        operador = ' ';
                        operando1 = 0;
                    }
                }
            } else {
                //Si es la primera vez que se pulsa un operador
                operador = botonllamador.getText().charAt(0);
                operando1 = Double.parseDouble(campotexto.getText());
                if(operador == '='){
                    operador=' ';
                }else{
                    System.out.println("EN EL ELSE RARO ES "+campotexto.getText());
                    campotexto.setText(campotexto.getText() + operador);
                    System.out.println("FIN DEL ELSE RARO ES "+campotexto.getText());
                }
            }

        }
    }
}

A: Can you show the signature of the second method you already showed.
Normally it should be part of a class implementing an interface (ActionListener as coding.mof said) or extend a class (like MouseAdapter) and that class should be set to listen for actions on the buttons (with a method like addActionListener).


text:
Q: How to ignore not provided values and keep those provided with null, without using Optional<>? I want to know if there is a way to ignore values not provided in the request body but keep those provided with null, my restraints are:

*

*I can't use Optional<> on the object declaration.

*I'm using DTO so I can't pass the DTO from the Controller to the Service, nor pass the Service responsibility to the Controller.

*I'm using JsonView on the controller to obtain only the fields that can be Patched, so the solution needs to be compatible with this annotation or method (objectReader.readerWithView()). Or provide another solution to allow only certain fields to be patched/posted/listed, that works with the provided solutions for the null/not provided problem.

An example of what I want can be found here: Jackson serialization - ignore not set values but provide values explicitly set to null
Any ideas of what I can use? Sadly JsonInclude.Include.NON_ABSENT does not keep null values...