text:
Q: Drawing in QQuickFramebufferObject via texture taken from an Item. It fails unless I repaint/update constantly What my code does, in short:

*

*Create a simple Rectangle named rect, with layer.enabled: true.

*Pass rect to an instance of my QQuickFramebufferObject subclass called itemSnapshotter

*In synchronize, take a pointer to the texture provided by rect

*In render, draw a rectangle textured with the texture I took

*When main.qml finishes loading, call itemSnapshotter.update(); for the first and only time.

The problem is that the QQFBO draws nothing, unless I uncomment the update call at the end of render(). Any idea why?
My code:
main.cpp:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQuickFramebufferObject>
#include <QOpenGLFramebufferObject>
#include <QSGTextureProvider>
#include <QObject>
#include <QOpenGLFunctions>
#include <QOpenGLShaderProgram>
#include <QOpenGLBuffer>
#include <QQuickWindow>
#include <QOpenGLFunctions>
// propertyhelper.h is from http://syncor.blogspot.bg/2014/11/qt-auto-property.html
#include "propertyhelper.h"

class ItemSnapshotter : public QQuickFramebufferObject {
    Q_OBJECT

    AUTO_PROPERTY(QQuickItem*, sourceItem)

public:
    Renderer *createRenderer() const;
};

class ItemSnapshotterRenderer
    : public QObject
    , public QQuickFramebufferObject::Renderer
    , protected QOpenGLFunctions
{
    Q_OBJECT

public:
    ItemSnapshotterRenderer() {
        initializeOpenGLFunctions();
        initShader();
        createGeometry();
    }

    void createGeometry() {
        m_vertices << QVector2D(0, 0) << QVector2D(0, 1) << QVector2D(1, 1);
        m_vertices << QVector2D(0, 0) << QVector2D(1, 0) << QVector2D(1, 1);
    }

    void initShader() {
        m_shaderProgram.addShaderFromSourceFile(
            QOpenGLShader::Vertex, ":/PassThrough.vert.glsl");
        m_shaderProgram.addShaderFromSourceFile(
            QOpenGLShader::Fragment, ":/PassThrough.frag.glsl");
        m_shaderProgram.link();
        m_shaderProgram.bind();

        glActiveTexture(GL_TEXTURE0);
        m_shaderProgram.setUniformValue("uTex", 0);
    }

    void prepareShader() {
        m_shaderProgram.enableAttributeArray("aPos");
        m_shaderProgram.setAttributeArray("aPos", m_vertices.constData());
        m_shaderProgram.bind();
    }

    void render() {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        prepareShader();
        m_tex->bind();
        glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

        glDrawArrays(GL_TRIANGLES, 0, m_vertices.size());

        m_window->resetOpenGLState();
        //update();
    }

    void synchronize(QQuickFramebufferObject* qqfbo){
        auto parentItem = (ItemSnapshotter*)qqfbo;

        m_window = parentItem->window();
        copyTexture(*parentItem);
    }

    void copyTexture(const ItemSnapshotter &srcItem) {
        QQuickItem* sourceItem = srcItem.sourceItem();
        QSGTextureProvider* sourceTexProvider = sourceItem->textureProvider();
        m_tex = sourceTexProvider->texture();
        GLenum err;
        while ((err = glGetError()) != GL_NO_ERROR) {
            qDebug("\tgl error: 0x%x", err, 0, 16);
        }
    }

    QOpenGLFramebufferObject *createFramebufferObject(const QSize &size) {
        QOpenGLFramebufferObjectFormat format;
        format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil); // TODO simpler format
        return new QOpenGLFramebufferObject(size, format);
    }

private:
    QOpenGLShaderProgram m_shaderProgram;
    QQuickWindow* m_window;
    QSGTexture* m_tex;
    QVector<QVector2D> m_vertices;
};

QQuickFramebufferObject::Renderer *ItemSnapshotter::createRenderer() const {
    return new ItemSnapshotterRenderer();
}

int main(int argc, char *argv[]) {
    qmlRegisterType<ItemSnapshotter>("ItemSnapshotter", 1, 0, "ItemSnapshotter");
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    return app.exec();
}

#include "main.moc"

main.qml:
import QtQuick 2.6
import QtQuick.Window 2.2
import ItemSnapshotter 1.0

Window {
    visible: true
    width: 640
    height: 480

    Row {
        Rectangle {
            layer.enabled: true
            id: rect
            width: 100
            height: 100
            color: "red"
            border.color: "black"
        }

        ItemSnapshotter {
            id: itemSnapshotter
            sourceItem: rect
            width: sourceItem.width
            height: sourceItem.height
        }
    }

    Component.onCompleted: {
        itemSnapshotter.update();
    }
}

PassThrough.frag.glsl:
varying highp vec2 vTexCoord;
uniform sampler2D uTex;

void main() {
    gl_FragColor = texture2D(uTex, vTexCoord);
}

PassThrough.vert.glsl:
attribute highp vec2 aPos;
varying highp vec2 vTexCoord;

void main() {
    gl_Position = vec4(aPos, 0.0, 1.0);
    vTexCoord = aPos;
}


text:
Q: Open query - incorrect syntax next to passed in variable I'm running this query
      SET @Qry = ' SELECT [MLSTQT] INTO ##DISPENSED_LOCATION'
              +' FROM OPENQUERY(MA,''SELECT MLSTQT FROM ES3.MD.MOC   WHERE MLWHSL='''+    @ProcessOrder+''' '')'
        EXEC (@Qry)

And I'm getting an error saying that there is incorrect syntax next to the value @ProcessOrder.
What's wrong with my query?
Seems it would be  WHERE MLWHSL='10000' which is correct.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Motor driver / power supply selection issues I'm planning on running two identical stepper motors controlled by arduino.
The specs are:
Bipolar RMS current - 3A
Bipolar RMS voltage - 3V
I plan on running them at very low (<60) RPM (the speed for max torque, according to the phone rep I spoke to from the manufacturer) and cannot sacrifice power, but can compromise speed.
The problem I'm having is that I can't find both a stepper motor driver and a power supply that operate at that Amp rating and also have a low enough voltage rating. After foraging around on here I stumbled across this helpful(ish) post:
Stepper driver 3.3V 3A
Unless I'm interpreting some of these comments incorrectly, it sounds like operating just below the voltage range of the driver isn't horrible. But other places I've read have said that using a motor below the driver specs can cause damage. Once I select the drivers I'm not too worried about finding a fitting power supply, but that's a bridge I'll have to cross after I decide the drivers I'll be using.
I'm obviously VERY new to the world of electronics and would really appreciate a push in the right direction
link to the motors: http://www.anaheimautomation.com/products/stepper/stepper-linear-actuator-item.php?sID=797&pt=i&tID=80&cID=52

A: It's rare these days to see stepper motors (apart from really small ones) driven by a simple H-Bridge.
You need to look at your detailed spec sheet and find the winding inductance, which in your case it appears is 1.5 mH.
From there it takes a bit of math to figure out what you exactly get out of the motor, but you can use a quick online calculator to get approximations.
For your stepper this was the result:

This shows you can get to about 96 rpm.
Note that there is no microstepping achievable for this type of configuration, so you can only get 200 steps per rev.
There will be losses (voltage) in your H-bridge so you don't want a 3 V supply, depending on whether the H-bridge has transistors or FETs you could need up to 5+ V.
I'd suggest that one solution would be use higher voltage and drive with a constant current driver above the H-bridge.
Or you could put a series resistor in series with each winding to limit the current.
There will be greater power dissipation but I assume that may be ok for you.
One H-bridge able to drive your motor would appear to be the TLE 5206 from Infineon. This can handle 5 A, but needs a supply of 6 V or above to work.
you could add a 1 Ohms resistor in series with each winding (Your motors are 4 wire so this will work).
The state of your H-bridge drive is as follows:

In these diagrams the 0 and 1 in the table indicate +3 A and -3 A current through winding 1a-1b. 0 and 1 under 2a-2b represent the current for the second winding. Providing the RL time constant of your motor is short compared to state time, then this method (values of drive) holds true.
Note: The 1a-1b signals can be produced by 2 ports on your Arduino, or you could use one port and an inverter. In the latter case this means you cannot brake the motor by having 0 current/short across the motor. You can try this out for yourself by leaving the motor winding unconnected and then manually spinning the shaft. Little effort is required and you only feel the magnetic detent positions. If you then short the 1a-1b, 2a-2b windings, the effort to turn the motor is large. This is a brake condition.
If you drive the motor at a speed where the RL time constant is a large part of the state time (>50%) then the drive needs to become a bit more complicated (and you then need to consider RMS and Peak currents). The complication is that the current waveform becomes what's known as sinusoidal and in it's most primitive form (Full step) would look like this:

Note: now that there is actually a new state in the drive steps from the Arduino .... 0 Amps. This means you can't use the invertor drive method and must drive the 1a-1b, 2a-2b using individual ports for the H-bridge halves.
For your application I doubt you will need to consider the complications of sinusoidal drive, though it's possible you could include brake to give you a lower power state with good hold characteristics.

A: The question you linked to actually has the answer: use a chopper driver, which most stepper motor drivers are. These can run at a voltage well above the rated voltage of the motor.
A motor winding is basically an inductor. A chopper driver works by applying the supply voltage across the winding, which causes current to slowly build through the winding, at a rate determined by the inductance. Before the current gets above the rated current of the motor, the driver turns off ("chops"), letting the current decay until it falls below another threshold, at which point it turns back on.
This works because the rated voltage of a stepper motor is not a hard limit, but rather the voltage that will cause the rated current to flow (and the rated current is a real, thermal limit).
There are plenty of stepper motor drivers out there capable of 3A at perhaps 12V or 24V, and power supplies are also easy to find at those voltages.


text:
Q: heroku plugin, how to access an env variable like RAILS_ENV? I'm in the process of building a rails plugin to automate my teams deployment process.. Problem is I can't find a way to access teh rails env variable. I have the following:
config = YAML.load(File.open("#{Dir.getwd}/config/s3.yml"))[RAILS_ENV]

That errors with:
in `const_missing_from_s3_library': uninitialized constant Heroku::Command::Jammit::RAILS_ENV (NameError)

Anyone know how? Thanks

A: You should be using Rails.env instead of RAILS_ENV with Rails 3 and up. Try using:
config = YAML.load(File.open("#{Dir.getwd}/config/s3.yml"))[Rails.env]

Or this if you get scope issues with just Rails:
config = YAML.load(File.open("#{Dir.getwd}/config/s3.yml"))[::Rails.env]


text:
Q: Leer un arreglo desde un controlador hacia un archivo.vue espero me puedan ayudar, recién estoy comenzando en Laravel e intento hacer lo siguiente.
Tengo un controlador con datos en un array:
public function widgetIngresosVentas(Request $request){
    //if (!$request->ajax()) return redirect('/');

    $fechaActual= date('m');

    $ingresosValorTotal = DB::table('ingresos')->sum('total');
    $ingresosValorMes = DB::table('ingresos')->whereMonth('fecha_hora', $fechaActual)->sum('total');
    $ingresosQtxTotal = DB::table('ingresos')->count();
    $ingresosQtxMes = DB::table('ingresos')->whereMonth('fecha_hora', $fechaActual)->count();

    $ventasValorTotal = DB::table('ventas')->sum('total');
    $ventasValorMes = DB::table('ventas')->whereMonth('fecha_hora', $fechaActual)->sum('total');
    $ventasQtxTotal = DB::table('ventas')->count();
    $ventasQtxMes = DB::table('ventas')->whereMonth('fecha_hora', $fechaActual)->count();

    $wIngresosVentas = [
        'wingresos' => [
            'i_val_total' => $ingresosValorTotal,
            'i_val_mes' => $ingresosValorMes,
            'i_qtx_total' => $ingresosQtxTotal,
            'i_qtx_mes' => $ingresosQtxMes,
            'i_msj' => 'Ingresos'
        ],
        'wventas' => [
            'v_val_total' => $ventasValorTotal,
            'v_val_mes' => $ventasValorMes,
            'v_qtx_total' => $ventasQtxTotal,
            'v_qtx_mes' => $ventasQtxMes,
            'v_msj' => 'Ventas'
        ]
    ];
    return ['wIngresosVentas' => $wIngresosVentas];
}

y los quiero leer en un archivo .vue, ya declaré el array y sus variables

Cuando ejecuto la pagina, usando el DevTools de Chrome puedo ver que ya me carga el ArrayIngresosVentas:Object y ya tiene los arrays wingresos y wventas con todos sus campos y valores, pero no se como leer los datos, intenté un v-for pero como estoy tratando de pintar la informacion en etiquetas span... no funciona, presenta los datos pero repetidos, estuve tratando de usar un foreach pero no sirve dentro de un template.
Ya pude leer los datos usando un v-for dentro de un div, el problema es que cuando solo pongo dos datos para presentar.. todo bien, pero cuando pongo un tercer dato... me triplica los span los primeros con inforacion y el tercero en blanco

A: Ya pude solucionar mi problema, adjunto el código
Hice dos arrays
$wingresos =
        array([
            'i_val_total' => $ingresosValorTotal,
            'i_val_mes' => $ingresosValorMes,
            'i_qtx_total' => $ingresosQtxTotal,
            'i_qtx_mes' => $ingresosQtxMes,
            'i_msj' => 'Compras'
        ]);

    $wventas =
        array([
            'v_val_total' => $ventasValorTotal,
            'v_val_mes' => $ventasValorMes,
            'v_qtx_total' => $ventasQtxTotal,
            'v_qtx_mes' => $ventasQtxMes,
            'v_msj' => 'Ventas'
        ]);

    return ['wingresos'=>$wingresos, 'wventas'=>$wventas];

luego en el archivo .vue en methods :  tengo dos funciones
la que carga los datos
widgetIngresos(){
    let me=this;
      var url= '/dashboard/widgetIngresosVentas';
      axios.get(url).then(function (response) {
          var respuesta= response.data;
          me.ArrayWIngresos = respuesta.wingresos;
          me.loadWidgetIngresos();
      })
      .catch(function (error) {
          console.log(error);
      });
  },

y luego la que lee los datos del array y los asigna a las variables
loadWidgetIngresos(){
    let me=this;
    me.ArrayWIngresos.map(function(x){
      me.i_val_total = x.i_val_total;
      me.i_val_mes = x.i_val_mes;
      me.i_qtx_total = x.i_qtx_total;
      me.i_qtx_total = x.i_qtx_total;
      me.i_msj = x.i_msj;
    });
  },

ya solo queda llamar a las variables en la plantilla donde quieran ser presentados

   {{i_msj}}
   {{i_val_mes}}
   {{i_val_total}}

y listo, funciona correctamente


text:
Q: How use input type=file to upload json file I want to send a JSON file on a php script called process.php, save the file on a folder and then send this file to a python script.
At the moment the html code is this:
<form method="post" enctype="multipart/form-data">
    <input type="file" name="files[]" multiple>
    <input type="submit" value="Upload File" name="submit">
</form>

And the javascript code is this:
 const url = 'process.php';
 const form = document.querySelector('form');

 form.addEventListener('submit', e => {
      e.preventDefault();
      const files = document.querySelector('[type=file]').files;
      const formData = new FormData();

      for (let i = 0; i < files.length; i++) {
          let file = files[i];
          formData.append('files[]', file);
       }

      fetch(url, {
          method: 'POST',
          body: formData
      }).then(response => {
           console.log(response);
     });
 });

Lastly my PHP is this:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_FILES['files'])) {
    $errors = [];
    $path = 'uploads/';
    $extensions = ['json'];

    $all_files = count($_FILES['files']['tmp_name']);

    for ($i = 0; $i < $all_files; $i++) {
        $file_name = $_FILES['files']['name'][$i];
        $file_tmp = $_FILES['files']['tmp_name'][$i];
        $file_type = $_FILES['files']['type'][$i];
        $file_size = $_FILES['files']['size'][$i];
        $file_ext = strtolower(end(explode('.', $_FILES['files']['name'][$i])));

        $file = $path . $file_name;

        if (!in_array($file_ext, $extensions)) {
            $errors[] = 'Extension not allowed: ' . $file_name . ' ' . $file_type;
        }

        if ($file_size > 2097152) {
            $errors[] = 'File size exceeds limit: ' . $file_name . ' ' . $file_type;
        }

        if (empty($errors)) {
            move_uploaded_file($file_tmp, $file);
        }

    }

    if ($errors) print_r($errors);
}

}
In the PHP if I try to print $file_name, the name of the file is printed correctly, but if I try to print the other information the result is an empty string or, in the case of $file_size is 0.
So, what's wrong ? Must I set something in the apache configuration to upload a file on my web server or I have committed some mistake in my code ?

A: You need to use the temporary name of the file, the function  is_uploaded_file()  does not accept the file name sent on the client machine, try this:
 if (is_uploaded_file ($_FILES['upload_cont_file']['tmp_name'] ))
    echo 'file uploaded ';
 else
 echo 'error';

A: If want to upload  and move to specific directory for example images folder

if (move_uploaded_file ( $_FILE['upload_cont_file']['tmp_name'] ,'images/'.$_FILE['upload_cont_file']['name']))
{
    echo 'file uploaded ';

}
else
{
  echo 'couldnt file uploaded';

}

If you just check file  uploaded to temp folder
 if (is_uploaded_file ($_FILES['upload_cont_file']['tmp_name'] ))
{
    echo 'file uploaded ';

}
else
{

 echo 'file couldn't upload';

}


text:
Q: The query is always of type unknown when created with @graphql-codegen I have a this graphql query:
import { graphql } from '../__generated__/gql';

// typeof IndexPageQuery is unknown
const IndexPageQuery = graphql(`
  query IndexPageQuery {
    user {
      ...UserInputFragment
    }
  }
  ${UserInputFragment}
`);

And when i run this code:
const { data } = await apolloClient.query(IndexPageQuery);

TS throw error:
Argument of type 'unknown' is not assignable to parameter of type 'QueryOptions<OperationVariables, any>'.ts(2345)

Why IndexPageQuery always has type unknown? Does anyone know what I'm doing wrong? Thanks

A: I'm Charly, from The Guild, working on GraphQL Code Generator.
The preset: 'client' does not require to include fragments documents in the GraphQL operation definition (it does it for you automatically).
To fix your issue, please replace your IndexPageQuery with the following:
const IndexPageQuery = graphql(`
  query IndexPageQuery {
    user {
      ...UserInputFragment
    }
  }
`);


text:
Q: Really can't understand why my program isn't working I've really spent a lot of time working at this problem and googling around to find a solution, but I can't seem to find what's wrong.
I've learning how to code occam and have the following program:
PROC light (CHAN OF BYTE screen, CHAN OF INT light.change)
  INT light.on :
  WHILE TRUE
    SEQ
      light.change ? light.on
      IF
        light.on = 1
          screen ! 'y'
        TRUE
          SKIP
:

PROC test(CHAN OF BYTE keyboard, scr)
  CHAN OF INT to.light :
  INITIAL INT on IS 1(INT) :
  BYTE b :
  SEQ
    light(scr, to.light)
    WHILE TRUE
      SEQ
        keyboard ? b
        IF
          b = 'o'
            to.light ! on
          TRUE
            SKIP
:

All I'm trying to do is communicate from one process to another when I press the 'o' key.
The error message I'm getting from the (KRoC) compiler is:
Error at lift.occ:11
Program failed, state = e, eflags = 00000000

which is the light.on = 1 line.
As far as I can see, the light PROC will wait for some input on its light.change channel and will then assign it to its light.on variable. The program will then proceed to a conditional statement IF, where the light.on = 1 line should in this case evaluate to true. But instead I get this error.
I have tried using the -verbose flag, but the compiler says that you can't use it for .occ files.
Does anyone know how or if I can get more detailed info from the compiler?
Any help on this would be greatly appreciated.
Thanks

A: The above code compiles for me and when run reaches deadlock
james:conc$ occbuild --program light.occ
james:conc$ light
KRoC: deadlock: no valid processes found in workspace(s)

KRoC: program deadlocked (no processes to run)

I can also get it to run in verbose mode as below
occbuild -v --program light.occ

On a different note you might want to change your structure. Try having three PROC's
PROC is.light.on(CHAN BYTE screen! , CHAN INT light.control)
  WHILE TRUE
...output to terminal if light is on or off

PROC light.switch(CHAN BYTE keyboard? , CHAN INT light.control)
  WHILE TRUE
...use the keyboard to turn light on and off

PROC light(CHAN BYTE keyboard? , screen!)
  CHAN INT light.control:--0 for light on;1 for light off
  PAR
    light.switch(keyboard? , light.control!)
    is.light.on(screen! , light.control?)


text:
Q: What is '1' testing against in 'if !1 | finish' in a vimscript? I've seen the following line commonly used in other people's vimrc files:
if !1 | finish | endif

I get that it's saying if not '1', then fishing sourcing the file, but I can't find any documentation of what '1' is. I've tried every way I can think of to search the vim user manual for references to '1', but haven't turned up anything.
My closest guess is that it's testing if evaluations can occur, which may not be possible in minimal versions. If that's the case, then this capability probably bound to a specific feature listed in :h +feature-list, but I'm not sure which it is.
Any ideas?

A: The 1 is just the number, and (like any other non-zero number) stands for a true boolean value. So this checks whether expressions can be evaluated (as this depends on the +eval feature that can be excluded from builds, though it predominantly isn't).
:help no-eval-feature has more information on this topic, and it suggests that the negated test doesn't work, as

the argument of the ":if" and everything between the ":if" and the matching ":endif" is ignored.

I don't know where you saw that, but it may be a form of Cargo cult.


text:
Q: Cakephp how can I give condition on Paginator setTemplate? I am trying to give condition on paginator setTemplate method
I am actually trying to set a active css class in a sort url
$this->Paginator->setTemplates([
    'sort' => '{{text}}',
    'sortAsc' => '{{text}}',
    'sortDesc' => '{{text}}'
]);

Here I want to give a condition or set a default active link , when user will visit products page. Example my all products sort by created desc.
So I am trying give a condition like
if (!$this->request->getQuery('sort')) and {{text}} == 'time' )
{
    return "nav-link active";
}

How can I give this condition ?


text:
Q: Determining audioformat of audio files in Android Is there a way to determine the audio format of an audio file in Android? On normal java I do it like this:
File file= new File(...);
AudioInputStream stream = AudioSystem.getAudioInputStream(file);
AudioFormat format= stream.getFormat();

A: android.media.AudioTrack[1] has the following methods to access information about audio data:

*

*getChannelCount to determine the number of channels

*getChannelConfiguration to determine if you deal with mono or stereo content

*getSampleRate to find out the sampling frequency

and

*

*getAudioFormat to determine if you deal with 8bit or 16bit sample width.

A: The AudioTrack.getXXX methods you list merely return the values supplied to the constructor. This doesn't solve the original poster's issue.


text:
Q: Как передать данные из одной формы в другую? Допустим у нас на странице два товара с кнопкой купить, под каждым товаром есть форма со скрытыми полями описанием (артикул, цена) и кнопкой купить.
И в конце на этой же странице есть ещё одна "главная" форма.
Подскажите пожалуйста - Как при нажатии submit в одной из таких форм, передать value этих полей в главную форму?
Чтоб было понятнее, вот грубый пример этих форм:
Товар1(первая форма)
<form>
<input type="hidden" id="articul" name="articul" value="001">
<input type="hidden" id="price" name="price" value="100руб">

Отправить

Товар2 (Вторая форма)
<form>
<input type="hidden" id="articul" name="articul" value="002">
<input type="hidden" id="price" name="price" value="250руб">

Отправить

Оформление заказа (Главная форма отправляющая данные дальше для обработки)
<form action="post.php" method="POST">
<input type="text" id="Name" name="Имя"  value="">
<input type="text" id="Phone" name="Телефон" value="">
<input type="hidden" id="realarticul" name="articul" value="">
<input type="hidden" id="realprice" name="price" value="">

Буду благодарен за помощь!
Сам делал с помощью jQuery:
$('.sendValues').click(function(){
$('#realarticul').val( $('#articul').val() );
$('#realaprice').val( $('#price').val() );

});
Но тут не важно какую кнопку нажмешь, данные подставляются из первой формы!


text:
Q: Animations Path by Path in RaphaelJS I have to make several animations starting from SVG, what I'm doing is saving the SVG with each modified position so it becomes easy for the animation Raphaeljs, I'm using a converter from SVG to RaphaelJS and generates me some groups of elements that can not handle for the next SVG with the modified position.
full code in jsfiddle
Layer_1_1_.animate({
    path: "M 410.251,139.304 410.617,142.129 270.996,202.417 116.224,194.09 115.859,191.263 264.412,163.038 z"
}, 2000);

jsfiddle


text: Q: Color Highlight On Geo Map I have a dataset where couple of machines are mapped to regions e.g. Emea , APJ , Americas. I have used an external excel file where i have included all the countries which are part of those 3 regions. There are 2 columns in my ext. excel file. Country and Region. Region column i have mapped with my dataset region. By doing this i am able to use geo map representing all 3 regions. Now in my dataset i have some machines and their predicted failure time (future timestamp). How can i highlight the specific region to which the machine belongs to based on the timestamp of failure alert?


text:
Q: How can I publish a Google App Script using a domain-wide-delegation service account? I'm trying to use the what Google terms a 'Domain-wide delegation' service account: https://developers.google.com/admin-sdk/directory/v1/guides/delegation
The specific API I'm trying to access with this delegation is: https://developers.google.com/apps-script/api/
Here's the code:
from google.oauth2 import service_account
import googleapiclient.discovery
import json
import os

SCOPES = ['https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/drive']
SERVICE_KEY = json.loads(os.environ['SERVICE_KEY'])

credentials = service_account.Credentials.from_service_account_info(SERVICE_KEY, scopes=SCOPES)
delegated_credentials = credentials.with_subject('fred.bloggs@my-gapps-domain.com')
script = googleapiclient.discovery.build('script', 'v1', credentials=delegated_credentials)

response = script.projects().get(scriptId='<myscriptId>').execute()
print json.dumps(response)

This fails with:
google.auth.exceptions.RefreshError: ('unauthorized_client: Client is unauthorized to retrieve access tokens using this method.', u'{\n  "error" : "unauthorized_client",\n  "error_description" : "Client is unauthorized to retrieve access tokens using this method."\n}')

I'm pretty sure I've followed all the steps at https://developers.google.com/api-client-library/python/auth/service-accounts, including authorizing the 'https://www.googleapis.com/auth/script.projects' scope with the client ID of the service account json key I downloaded.

Note, I was able to successfully get this particular snippet to work by skipping with_subject, and going in to the Script dashboard as the user, and 'sharing' the script project.
Unfortunately though that still doesn't allow upload a new set of files (as 'sharing' doesn't give the ability to delete). It does at least confirm my calling code is correct, albeit not authenticating properly with the json service key.
To clarify:

*

*The script in question is what I believe is termed 'standalone' (not a web app)

*It's owned by a bot user I've setup just like a regular GSuite user (as I didn't want scripts in regular user's Google Drives)

*The script started in a Google Cloud Project that seemed to be automatically created, and with 'No organisation'. I then created a new project manually within the organisation, and moved the script to that project.

There's an official Google Apps Script client now, so I asked there too https://github.com/google/clasp/issues/225#issuecomment-400174500 - although they use the Javascript API (via Typescript), the principles should be the same.


text:
Q: How to scroll a page with phantomJs I wanna render a page that load its images only when the user scrolls the page. Just setting page.scrollPosition has no effect. I need something that change the scroll position over time.

A: Not sure if this is the best way but it works. It evaluate a script in the page, that increase document.body.scrollTop over time and make a screenshot after a fixed time.
page.open "http://www.somePage.com", (status) ->
      setTimeout(( ->
        page.evaluate(->
          pos = 0
          scroll = ->
            pos += 250
            window.document.body.scrollTop = pos
            setTimeout(scroll, 100)

          scroll()
        )

        setTimeout((->
          page.render('bild.png')
          phantom.exit()
        ), 5000)
      ), 1000)


text:
Q: Connection Refused when connecting two containers in docker-compose I'm new to docker and I'm facing a problem when trying to connect to a container from within another. The wierd stuff is that some containers can indeed be contacted, and others, configured in the same way, not. I tried a zillion fixes found while crawling google, nothing works. I guess this is a simple noob mistake though.
Here's my docker-compose file:
version: '3.4'

services:

  mssql.db.posm:
    image: "microsoft/mssql-server-linux"
    environment:
        SA_PASSWORD: "mypassword"
        ACCEPT_EULA: "Y"
        MSSQL_PID: "Express"
    volumes:
      - mssql-data:/var/opt/mssql
    ports:
      - "1433:1433"
    networks:
      posm:

  api.posm:
    image: ${DOCKER_REGISTRY}posm.api
    build:
      context: .
      dockerfile: Posm.Api/Dockerfile
    expose:
      - "6869"
    ports:
      - "6869:80"
    networks:
      posm:

  cloud.subscription:
    image: ${DOCKER_REGISTRY}cloud.subscription
    build:
      context: ./Services
      dockerfile: Cloud.Subscription/Dockerfile
    ports:
      - "80"
    networks:
      posm:

  catalogmanager.services.posm:
    image: ${DOCKER_REGISTRY}posm.services.catalogmanager
    build:
      context: ./Services
      dockerfile: CatalogManager/Dockerfile
    ports:
      - "80"
    networks:
      posm:
        aliases:
          - services.posm
          - catalogmanager

  productmanager.services.posm:
    image: ${DOCKER_REGISTRY}posm.services.productmanager
    build:
      context: ./Services
      dockerfile: ProductManager/Dockerfile
    ports:
      - "80"
    networks:
      posm:
        aliases:
          - services.posm
          - productmanager

  localizer.services.posm:
    image: ${DOCKER_REGISTRY}posm.services.localizer
    build:
      context: ./Services
      dockerfile: Localizer/Dockerfile
    ports:
      - "80"
    networks:
      posm:
        aliases:
          - services.posm
          - localizer

networks:

  posm:

volumes:

  mssql-data:

So, when I connect to the api.posm, the latter is able to successfully connect to mssql.db.posm and to cloud.subscription. It however fails, with a connection refused error, to connect to 'catalogmanager' and 'productmanager', even though I can resolve their hostname from within api.posm... What is happening?

A: You are giving the alias services.posm both to 'catalogmanager' and 'productmanager':
  posm:
    aliases:
      - services.posm
      - catalogmanager

As you now per the documentation (https://docs.docker.com/compose/compose-file/#aliases), this will give the hostname "services.posm" to the containers in the posm network. This means that you are having 2 times the "services.posm" host in the network, and both exposing the port 80. This will not work. Remove the "services.posm" line on both containers aliases, restart and you will be able of accessing them using the catalogmanager and productmanager hosts.

A: So, the problem was a stack overflow exception in one of my images that was unhandled by my debugger, and that I therefore did not see.
Concerning your answer, Moreno...

You are giving the alias services.posm both to 'catalogmanager' and
  'productmanager'

I had duplicated this post on Docker forums for increasing my chances to get a relevant answer, and someone suggested the same. The reason I was using the same aliases for three different services is that I read somewhere (cannot find it now, of course) that you could tag multiple services with the same alias for discovery purposes. I probably got that wrong but Docker doesn't seem to mind at all anyways.
So, thanks for your time nonetheless, sorry that I bothered for such stupid mishandling of my code.
Bottom line is: DOCKER ROCKS


text:
Q: Python unittest.mock google storage - how to achieve exceptions.NotFound as side effect I've read a few tutorials on mocking in Python, but I'm still struggling :-/
For example, I have a function wrapping a call to google storage to write a blob.
I'd like to mock the google.storage.Client().bucket(bucket_name) method to return an exceptions.NotFound for a specific non-existent bucket.
I'm using side_effect to set the excepted exception
Do you know what I'm doing wrong?
Below is what I tried (I'm using 2 files: main2.py and main2_test.py):
# main2.py
import logging
from google.cloud import storage

def _write_content(bucket_name, blob_name, content):
   storage_client = storage.Client()
   bucket = storage_client.bucket(bucket_name)
   blob = bucket.blob(blob_name)

   try:
        blob.upload_from_string(data=content)
        return True
    except Exception:
        logging.error("Failed to upload blob")
        raise

and
# main2_test.py
import pytest
from unittest.mock import patch
from google.api_core import exceptions
import main2

@patch("main2.storage.Client", autospec=True)
def test_write_content(clientMock):
    bucket_name = "not_existent_bucket"
    clientMock().bucket(bucket_name).side_effect = exceptions.NotFound

    with pytest.raises(exceptions.NotFound):
        main2._write_content(bucket_name, "a_blob_name", '{}')

Example call
pytest main2_test.py::test_write_content

Result
platform linux -- Python 3.7.7, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: /home/user/project, inifile: pytest.ini
plugins: requests-mock-1.8.0
collected 1 item

main2_test.py::test_write_content FAILED                                                                                [100%]

============================================================================================== FAILURES ==============================================================================================
_________________________________________________________________________________________ test_write_content _________________________________________________________________________________________

clientMock = <MagicMock name='Client' spec='Client' id='139881522497360'>

    @patch("main2.storage.Client", autospec=True)
    def test_write_content(clientMock):
        bucket_name = "my_bucket"
        clientMock().bucket(bucket_name).side_effect = exceptions.NotFound

        with pytest.raises(exceptions.NotFound):
>           main2._write_content(bucket_name, "a_blob_name", '{}')
E           Failed: DID NOT RAISE <class 'google.api_core.exceptions.NotFound'>

main2_test.py:14: Failed
=====================================
FAILED main2_test.py::test_write_content - Failed: DID NOT RAISE <class 'google.api_core.exceptions.NotFound'>
=====================================

A: Your test has two problems: you are not mocking the method that shall actually raise (upload_from_string), and you are setting an exception class instead of an exception as side effect.
The following would work:
@patch("main2.storage.Client", autospec=True)
def test_write_content(clientMock):
    blob_mock = clientMock().bucket.return_value.blob.return_value  # split this up for readability
    blob_mock.upload_from_string.side_effect = exceptions.NotFound('testing')  # the exception is created here

    with pytest.raises(exceptions.NotFound):
        main2._write_content("not_existent", "a_blob_name", '{}')

Note also that setting a specific parameter for the bucket call has no effect, as it is called on a mock, and the argument is just ignored - I replaced it with return_value, which makes this clearer.


text:
Q: Intersecting geotiff with another one using alpha-channel (or nodata value) in GDAL? I have two geotiffs related to one location but with different areas covered:
1.

2.

How can I intersect their opaque parts into single geotiff like that?

A: Note: This solution is working for single band image only
If you have multiple bands, you may repeat this for each band adding -A_Band and -B_Band options and then gdal_merge.py -separate the bands.

You should be able to do this:
(We assume NoData Value of your rasters is 0)
gdal_calc.py -A file1.tif -B file2.tif --NoDataValue=0 \
--calc="A*(A>0)+B*logical_and(A==0,B>0)" \
--outfile=outfile.tif

Explanation:

*

*A*(A>0): if A is not Nodata, will be A*1, else A*0

*B*logical_and(A==0,B>0): if A is NoData and B is not Nodata, will be B*1, else B*0.

(This will always prefer A over B).


text:
Q: Вычислить корни уравнения ln(x)+x-0.5=0 методом Ньютона с заданной точностью eps Накидал кода, но правильного ответа нету. Где может быть ошибка?)
#include "pch.h"
#include <iostream>
#include <cmath>
using namespace std;
double fx, f, fa, x, e;
int main()
{
    setlocale(LC_ALL, "rus");
    cout << "Веедите x= ";
    cin >> x;
    cout << endl;
    cout << "Введите e= ";
    cin >> e;
    cout << endl;
    //x=1;
    //e=0.00001;
    fx = log(x);
    cout << endl << fx;
    while (abs(f) > e)
    {
        f = fx + x - 0.5;
        fa = 1 / x + 1;
        x = x - f / fa;
        cout << "x= " << x << "\n";
    }
    cout << "Конечное решение х= " << x << "\n";
    system("pause");
    return 0;
}

A: Ну смотрите сами - вот метод Ньютона:

Вот производная вашей функции:

Делим функцию на производную, вычисляем... Принимаем, что когда разность между двумя точками меньше ε - решение найдено. Всё!
int main()
{
    const double eps = 1e-8;
    double dx, x = 1.0;  // Начальное приближение
    do
    {
        dx = -x*(log(x)+x-0.5)/(1+x);
        x += dx;
    } while(abs(dx) >= eps);

    cout << x << endl;

}

Ваша главная ошибка - вы НЕ вычисляете логарифм, а всегда используете его значение в некоторой начальной точке. Т.е. пытаетесь решить уравнение fx - x = 0.5, где fx - это значение логарифма. Могли бы не мучиться и просто выводить fx-0.5 :)


text:
Q: "screen is terminating" for non-root When I try to run screen as a non-root user I get:
screen

[screen is terminating]

immediately, though it works fine for root
ls -alh /usr/bin/screen
-rwxr-sr-x 1 root screen 465K Jun  9 20:30 /usr/bin/screen

When googling around I noticed a mention of /etc/fstab, here is mine:
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
/dev/md1        /       ext4    errors=remount-ro       0       1
/dev/md2        /home   ext4    defaults        1       2
/dev/sda3       swap    swap    defaults        0       0
/dev/sdb3       swap    swap    defaults        0       0
proc            /proc   proc    defaults                0       0
sysfs           /sys    sysfs   defaults                0       0
tmpfs           /dev/shm        tmpfs   defaults        0       0
devpts          /dev/pts        devpts  defaults        0       0

This on a freshly installed centos 7 on a dedicated server accessed through ssh ( TTY is pts )
Any help would be appreciated.
screen -ls
No Sockets found in /var/run/screen/S-user.

ls -la /var/run/screen/S-user
total 0
drwx------ 2 user user 40 Jul 10 18:23 .
drwxrwxr-t 4 root     screen   80 Jul 10 17:59 ..

A: Ensure no other screen is using that device
This can be achieved with How can I determine what process has a file open in Linux? :
sudo lsof /dev/ttyS0

And then kill that process if that is the case.
For some reason, under this condition, sudo screen can still access the device, but then that connection will miss characters, which are consumed by the other screen.
Ensure the user has read and write permission to the file
E.g. on Ubuntu you want to add the user to the dialout group: https://askubuntu.com/a/133244/52975

A: I had this issue on Dedicated CentOS 7 server, and came across the fix described in this bug report:
bugs.centos.org/view.php?id=7395
That was a fine solution on the Dedicated to add gid=5 to devpts in fstab. screen now works as expected for all users.
However, I ran across this thread as I was trying to solve the issue on an OpenVZ container of CentOS 7. As there isn't a way to edit the fstab for the server (as far as I could find), I found the following work-around fixed it.
I figured I would drop back by this way and see if it might help anyone else out.
(Albeit isn't a very pretty way of doing it.)
In terminal:
chmod u+s /usr/bin/screen
chmod 755 /var/run/screen

A: It might be an errors in your config file
~/.screenrc
Try to check it or create dimmy one.


text:
Q: Error creating control in asp.net while creating a menu in master page when working on a master page i tried to create a menu in my page but it throws me an error called

Error creating control-cpl1
Could not load file or assembly 'System.Web.Extensions,
  version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or
  one of its dependencies.This system cannot find the file specified.

A: Add a reference to the specified assembly and your're done


text:
Q: Python FileNotFoundError no such file or directory I get a file not found error when trying to run this script
class Account:

    def __init__(self, filepath):
        with open(filepath, 'r') as file:
            self.balance=int(file.read())

account=Account("~/Desktop/Courses/Python/account/balance.txt")
print(account)

balance.txt exists and I am running the script from the directory.


text:
Q: Forcing an Entity Framework 6 query to use the correct index I have a C# application that uses SQLite as the database and the SQLite Entity Framework 6 provider to generate queries based on user input.
The database contains the following tables and indexes:
CREATE TABLE Lists (
    ListRowId INTEGER NOT NULL PRIMARY KEY,
    ListId GUID NOT NULL,
    ListName TEXT NOT NULL
);

CREATE UNIQUE INDEX [IX_Lists_ListId] ON [Lists] ( [ListId] );

-- One to many relationship: Lists => ListDetails
CREATE TABLE ListDetails (
    ListDetailRowId INTEGER NOT NULL PRIMARY KEY,
    ListDetailId GUID NOT NULL,
    ListId GUID NOT NULL,
    Plate TEXT
);

CREATE INDEX [IX_ListDetails_Plate] ON [ListDetails] ( [Plate]  ASC );

CREATE TABLE Reads (
    ReadRowId INTEGER NOT NULL PPRIMARY KEY,
    ReadId GUID NOT NULL,
    Plate TEXT
);

-- 1 To many relationship: Reads => Alarms.
-- There may be rows in Reads that have no related rows in Alarms.
CREATE TABLE Alarms (
    AlarmRowId INTEGER NOT NULL PPRIMARY KEY,
    AlarmId GUID NOT NULL,
    ListId GUID NOT NULL,
    ListDetailId GUID NOT NULL,
    ReadRowId INTEGER NOT NULL
);

CREATE INDEX [IX_Alarms_ListId_ListDetailId] ON [Alarms] ([ListId], [ListDetailId]);

CREATE INDEX [IX_Alarms_ReadId] ON [Alarms] ([ReadRowId]);

Please note that the DDL above only includes the relevant columns and indexes.  For reasons of speed and the large number of rows in the ListDetails table, there is no index on the ListDetailId GUID column; nor can I create one.  In fact, I cannot change the database's schema at all.
The database does not have any foreign key relationships defined between any of these tables.  The reason is internal to our system.  I repeat, I cannot change the schema.
Using the SQLite EF6 provider, I've built an entity model from the database.  It is a database first model as the application was originally written using a different database and EF 4.  We upgraded it to EF 6 and replaced the database with SQLite.
While processing user input, I have to put together a query that joins these tables.  Here's the basic EF expression I've built.
from read    in context.Reads
join alrm    in context.Alarms on read.ReadRowId equals alrm.ReadRowId into alarmJoin
from alarm   in alarmJoin.DefaultIfEmpty()
join e       in context.ListDetails on alarm.ListPlate equals e.Plate into entryJoin
from entry   in entryJoin.DefaultIfEmpty()
join l       in context.Lists on alarm.ListId equals l.ListId into listJoin
from list    in listJoin.DefaultIfEmpty()
where alarm.ListDetailId = entry.ListDetailId
select new  {
    alarm,
    list.ListName,
    read
};

I've used the debugger to take that expression and generate the SQL.  I've reduced the output for brevity, as the only part I'm interested in are the join on the ListDetails table:
SELECT *
FROM    [Reads] AS [Extent1]
LEFT OUTER JOIN [Alarms] AS [Extent2] ON [Extent1].[ReadRowId] = [Extent2].[ReadRowId]
LEFT OUTER JOIN [ListDetails] AS [Extent3] ON ([Extent2].[ListPlate] = [Extent3].[Plate]) OR (([Extent2].[ListPlate] IS NULL) AND ([Extent3].[Plate] IS NULL))
LEFT OUTER JOIN [Lists] AS [Extent4] ON [Extent2].[ListId] = [Extent4].[ListId]
WHERE ([Extent2].[ListDetailId] = [Extent3].[ListDetailId]) OR (([Extent2].[ListDetailId] IS NULL) AND ([Extent3].[ListDetailId] IS NULL))

Executing EXPLAIN QUERY PLAN on this shows that the query will perform a table scan of the ListDetails table.  I do not want that to happen; I want the query to use the index on the Plate column.
If I remove the where clause, the SQL that's generated is different:
SELECT *
FROM     [Reads] AS [Extent1]
LEFT OUTER JOIN [Alarms] AS [Extent2] ON [Extent1].[ReadRowId] = [Extent2].[ReadRowId]
LEFT OUTER JOIN [ListDetails] AS [Extent3] ON ([Extent2].[ListPlate] = [Extent3].[Plate]) OR (([Extent2].[ListPlate] IS NULL) AND ([Extent3].[Plate] IS NULL))
LEFT OUTER JOIN [Lists] AS [Extent4] ON [Extent2].[ListId] = [Extent4].[ListId]

EXPLAIN QUERY PLAN on this query shows that the database does indeed use the index on the ListDetails table's Plate column.  This is what I want to happen.  But, there may be multiple rows in the ListDetails table that have the same Plate; it is not a unique field.  I need to return the one and only row that matches the information available to me in the Alarms table.
How do I make my query use the index on the Plate column?

A: Specifying an index requires a query hint. SqlLite uses the INDEXED BY command. Example:
LEFT OUTER JOIN ListDetails as Extent3 INDEXED BY IX_ListDetails_Plate ON Extent2.ListPlate = Extent3.Plate

LINQ does not provide a method to pass a query hint to the database.  LINQ's design philosophy is the developer shouldn't worry about the SQL: that is the DBA's job.
So there probably won't be a .With() LINQ extension coming anytime soon.
However, there are several options / workarounds:
1. The "Proper" Way
The "proper" way per LINQ's design philosophy is for a DBA to create a sproc that uses query hints.
The developer will call the sproc with Entity, and get a strongly typed sproc result.
using(applicationDbContext db = new applicationDbContext())
{
   var myStronglyTypedResult = db.Database.MySprocMethod();
}

Easiest way, with Entity handling the translations and class creations.  However, you will need permission to create the sproc. And it sounds like you do not have that option.
2. Old School
If LINQ doesn't want to use query hints, then don't use LINQ for the query. Simple enough. Back to DataAdapters and hard coded SQL queries.  You already have the query designed, might as well use it.
3. DataContext's Sql Interface
DataContext has a SQL interface built in: The SqlQuery<T>(string sql, object[] params) method. Database.SqlQuery
public class ListDetail
{
   public int ListDetailRowId {get; set;}

   public Guid ListDetialId {get; set;}

   public Guid ListId {get; set;}

   public string Plate {get; set;}
}

using(ApplicationDbContext db = new ApplicationDbContext())
    {
       List<ListDetail> results = db.Database.SqlQuery<ListDetail>("SELECT * FROM ListDetails INDEXED BY IX_my_index WHERE ListDetailRowId = @p0", new object[] {50}).ToList();

       return results;
    }

This gives you the flexibility of straight SQL, you don't have to mess with connection strings nor DataAdapters, and Entity / DataContext handles the translation from DataTable to Entity for you.
However, you will need to manually create the Entity class. It is the same as any other Entity class, it just won't be automatically created like the sproc method does.
This will probably be your best bet.

A: While this was a while ago, and I am no longer in that job, I wanted to take a minute to describe how we got around this problem. The problems are:

*

*SQLite does not support Stored Procedures, so there's no way to work around the problem from the database side,

*You can't embed the INDEXED BY hint into the LINQ query.

The way we ended up fixing this was by implementing a custom user function in the entity model which added the required INDEXED BY hint to the SQL generated by EF. We also implemented a couple of other user functions for a few other SQL Hints supported by SQLite. This allowed up to put the condition for the join that required the hint inside of our user function and EF did the rest.
As I said, I'm no longer in that position, so I can't include any code, but it's just a matter of adding some XML to the entity model file that defines the user functions and defining a class that has placeholder functions. This is all documented in the EF documents.


text:
Q: Summing array in Excel I have four tables. The first one shows amount of ingredient each menu uses.
Menu_Ingredient
  menu  | ingredient | amount
--------+------------+--------
  Foo   |   A        |  0.1
  Foo   |   B        |  0.2
  Bar   |   A        |  0.3
  Baz   |   C        |  0.4

Then I have the transaction table which shows date and the menu sold.
Menu_Sold
  date  | menu sold
--------+------------
   x    |   Foo
   x    |   Foo
   x    |   Bar
   x    |   Baz

I leave the date blank, assuming they are all the same for now.
The final table that I want is showing how much ingredient was used each month. As shown in column A,B,C. To do this I created another table in column F,G,H.
     A         B          C           F       G      H
   month | ingredient | amount      month | menu | amount
  -------+------------+--------   --------+------+--------
3    x   |     A      |   ?           x   |  Foo |   2
4    x   |     B      |   ?           x   |  Bar |   1
5    x   |     C      |   ?           x   |  Baz |   1

Here is the formula I used to count the amount in H column.
=COUNTIF(Menu_Sold!B:B,Monthly_Ingredient_Used!G4)

Here is what I did to find amount of ingredient A.

*

*Get array of menus that contains ingredient in A3  =IF($B$3=Menu_Ingredient!B:B,Menu_Ingredient!A:A,"")

*Get amount sold in that month (here assumming all entries are in the same month, thus left blank)
=IFNA(INDEX(H:H,MATCH(IF($B$3=Menu_Ingredient!B:B,Menu_Ingredient!A:A,""),G:G,0)),0)

*Multiply by amount of ingredient used
=IFNA(INDEX(H:H,MATCH(IF($B$3=Menu_Ingredient!B:B,Menu_Ingredient!A:A,""),G:G,0)),0)*Menu_Ingredient!C:C

*SUM all amount
=SUM(IFNA(INDEX(H:H,MATCH(IF($B$3=Menu_Ingredient!B:B,Menu_Ingredient!A:A,""),G:G,0)),0)*Menu_Ingredient!C:C)
Here is an image of the result I got
Questions:

*

*The first three steps give the right result. When I expand an array down the column, I can see correct numbers. However in the last step, it doesn't sum the whole array and give the first element as a result.

*I also tried using VLOOKUP instead for step 2, but somehow it gives wrong lookup value and I don't understand why.

Here is the file if you want to try it out.
https://1drv.ms/x/s!AgK3RJYPrJR8iGsfvXV0rrhtLiZa

A: Please check if this will work for you.
It looks like the table that you have created will give you outcome for A. If you want for B, you will have to create another table. From what I best understand your question, I suggest a slightly different approach which requires you to create a single Helper Table with number of columns = number of Menu items.
Here's an example. To keep it simple and accommodate in a single screenshot, all tables are in a single sheet.
Table 3, 4 & 5 are as what you have in your sheet (Table numbers may vary though)
See the Helper Table. Here each column is per Menu Item. So Foo, Bar & Baz in this case.
This is side by side with Table 1, the final outcome table.
I have added one more ingredient say D in this example.

Now in D3 put the following formula and drag it across the rows and columns of this table.
=SUMPRODUCT(($P$3:$P$7=$B3)*($O$3:$O$7=D$2),$Q$3:$Q$7)

This gives the Quantity of A used in Foo, Bar & Baz in Row 3. Similarly on the next row 4 it gives Quantity of B used in the same ingredients.
Now to get Amounts used all you need to do is use SUMPRODUCT
Formula in C3 is
=SUMPRODUCT(D3:F3,TRANSPOSE($J$3:$J$5))

Since J3:J6 are transposed to match the Array in SUMPRODUCT the entire formula needs to be an Array Formula. Press CTRL + SHIFT + ENTER from within the formula bar to create an Array Formula. The Formula shall now be enclosed in Curly Braces to indicate that it's an Array Formula. Drag it down along the column and for each Ingredient, you shall get the amounts consumed.
Note that here Month is not coming into picture as how you have treated it for now in your example.. If Month is to be added, formula might get more complex.


text:
Q: How to get the precision and recall from a nltk classifier? import nltk
from nltk.corpus import movie_reviews
from nltk.tokenize import word_tokenize

documents = [(list(movie_reviews.words(fileid)), category)
             for category in movie_reviews.categories()
             for fileid in movie_reviews.fileids(category)]

all_words = []

for w in movie_reviews.words():
    all_words.append(w.lower())

all_words = nltk.FreqDist(all_words)

word_features = list(all_words.keys())[:3000]

def find_features(document):
    words = set(document)
    features = {}
    for w in word_features:
        features[w] = (w in words)

    return features

featuresets = [(find_features(rev), category) for (rev, category) in documents]

training_set = featuresets[500:1500]
testing_set = featuresets[:1500]

classifier = nltk.DecisionTreeClassifier.train(training_set)

print "Classifier accuracy percent:",(nltk.classify.accuracy(classifier, testing_set))*100 , "%"

string = raw_input("Enter the string: ")
print (classifier.classify(find_features(word_tokenize(string))))

This code will display the accuracy of the classifier and then get input from user. And it returns the polarity of the string input by the user.
But here's my question: since I can obtain the accuracy by using nltk.accuracy(), is it possible to get its precision and recall as well?

A: If you're using the nltk package, then it appears you can use the recall and precision functions from nltk.metrics.scores (see the docs).
The functions should be available after invoking
from nltk.metrics.scores import (precision, recall)

Then you need to call them with reference (known labels) and test (the output of your classifier on the test set) sets.
Something like the code below should produce these sets as refsets and testsets
refsets = collections.defaultdict(set)
testsets = collections.defaultdict(set)

for i, (feats, label) in enumerate(testing_set):
    refsets[label].add(i)
    observed = classifier.classify(feats)
    testsets[observed].add(i)

Then, you can see the precision and recall for positive predictions with something like
print( 'Precision:', nltk.metrics.precision(refsets['pos'], testsets['pos']) )
print( 'Recall:', nltk.metrics.recall(refsets['pos'], testsets['pos']) )
# `'pos'` is for the "positive" (as opposed to "negative") label


text:
Q: Native Messaging postMessage with callback So, I create a port
var port = chrome.runtime.connectNative("my.native.app");

And I'll define
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnect);

So when I call
port.postMessage({"text":"messsage"});

It goes to my native application using standard in/out and I get my response.
Here's my problem: I have several functions that expect a response, and others that do not.  I want to be able to post a message and wait for a response from the native application (which is continually running). How is this done?
I am aware of "one time messaging" via sendMessageNative which works great, except I use my native application as a state machine, so it kills my application after it is done, which is no good.

A: My solution is to assign each message an unique id, and use a map to store the callback function for each message id (if there is a callback for the message).
When you receive a message from the host, check the message id and lookup the callback map. If there is a callback bound to that message, pass the response data and call it!

A: You could add another listener to onNativeMessage to call your callback and then de-register.
Something like this, with closures:
function callbackOnId(ev, id, callback) {
  var listener = ( function(port, id) {
    var handler = function(msg) {
      if(msg.id == id) {
        ev.removeListener(handler);
        callback(msg);
      }
    }
    return handler;
  })(ev, id, callback);
  ev.addListener(listener);
}

/* ... */
callbackOnId(port.onMessage, "someRequestId", callback);
port.postMessage({"text":"message", "id": "someRequestId"});

Now, the first time your port receives a message containing "id": "someRequestId", callback will be called with that message, after which the listener will de-register itself.
If you need it, you can add an ability to remove the listener and/or modify the message checks.


text:
Q: Android webview cookies are cleared/garbage collected after some time - Can I set a cookie custom storage path? I am trying to make my webview remember its cookies. My problem is that, they are removed after some time.
After doing some research, I found out that java's internal HttpClient uses CookieManager and CookieStore will get garbage collected. HttpClient is used in some of my networking code (not all written by me).
I am pretty sure this is the reason for my problem.
So my question is: Is there a way to save cookies from webview to another location than the one used by HttpClient?
I have tried setting a custom path like so:
webview.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    if (getCustomActivity() != null) {
                        CookieSyncManager.createInstance(getCustomActivity()).sync();
                    }
                }
            });
            webview.getSettings().setAppCachePath("/data/data/"+getActivity().getPackageName()+"/webview_cookies/");
            webview.loadUrl(url, true);

But with no luck.

A: I finally found a solution, which I am satisfied with. Basically, I am saving cookies in Shared Preferences and fetching them from there.
Here is my suggestion for a solution (A view class extending AdvancedWebView, which also could be the standard webview):
public class PersistentCookiesWebView extends AdvancedWebView {

    private static String       url                         = "PersistentCookiesWebView";
    private static String       cookieKey                   = "";
    private static final String COOKIE_STORAGE_KEY_PREFIX   = "cskp_";
    private static final long   COOKIE_MAX_STORAGE_BYTES    = 500000;

    public PersistentCookiesWebView(Context context) {
        super(context);
    }

    public PersistentCookiesWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PersistentCookiesWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void loadUrl(final String url, String cookieKey) {
        this.url        = url;
        this.cookieKey  = cookieKey;
        initializeWebView(new WebViewListener() {
            @Override
            public void onWebViewReady() {
                PersistentCookiesWebView.super.loadUrl(url);
            }
        });
    }

    @Override
    public void loadUrl(final String url) {
        this.url        = url;
        this.cookieKey  = getHostName();
        initializeWebView(new WebViewListener() {
            @Override
            public void onWebViewReady() {
                PersistentCookiesWebView.super.loadUrl(url);
            }
        });
    }

    @Override
    public void loadUrl(final String url, final Map<String, String> additionalHttpHeaders) {
        this.url        = url;
        this.cookieKey  = getHostName();
        initializeWebView(new WebViewListener() {
            @Override
            public void onWebViewReady() {
                PersistentCookiesWebView.super.loadUrl(url, additionalHttpHeaders);
            }
        });
    }

    @Override
    public void loadUrl(final String url, final boolean preventCaching) {
        this.url        = url;
        this.cookieKey  = getHostName();
        initializeWebView(new WebViewListener() {
            @Override
            public void onWebViewReady() {
                PersistentCookiesWebView.super.loadUrl(url, preventCaching);
            }
        });
    }

    @Override
    public void loadUrl(final String url, final boolean preventCaching, final Map<String, String> additionalHttpHeaders) {
        this.url        = url;
        this.cookieKey  = getHostName();
        initializeWebView(new WebViewListener() {
            @Override
            public void onWebViewReady() {
                PersistentCookiesWebView.super.loadUrl(url, preventCaching, additionalHttpHeaders);
            }
        });
    }

    protected void initializeWebView(final WebViewListener webViewListener) {
        setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                CookieManager.getInstance().flush();
            }
        });
        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                saveCookies(null);
                return false;
            }
        });
        fetchCookies(new CookieFetchListener() {
            @Override
            public void onCookiesFetched() {
                webViewListener.onWebViewReady();
            }
        });
    }

    public void saveCookies(CookieSaveListener cookieSaveListener) {

        String storageKey                   = COOKIE_STORAGE_KEY_PREFIX + cookieKey;
        String currentCookieString          = CookieManager.getInstance().getCookie(url) + "";
        ArrayList<String> currentCookieList = new ArrayList<String>(Arrays.asList(currentCookieString.split(";")));
        long cookieBytes                    = 0;
        String newCookies                   = "";

        for(int i = currentCookieList.size() - 1; i >= 0; i--) {
            String cookie = currentCookieList.get(i);
            try {
                cookieBytes = cookieBytes + cookie.getBytes().length;
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (cookieBytes < COOKIE_MAX_STORAGE_BYTES) {
                newCookies = cookie + ";" + newCookies;
            } else {
                break;
            }
        }
        PreferencesManager.putString(getContext(), storageKey, newCookies);

        if (cookieSaveListener != null) {
            cookieSaveListener.onCookiesSaved();
        }
    }

    private void fetchCookies(final CookieFetchListener cookieFetchListener) {
        String storageKey                   = COOKIE_STORAGE_KEY_PREFIX + cookieKey;
        String currentCookieString          = CookieManager.getInstance().getCookie(url) + "";
        String storedCookiesString          = PreferencesManager.getString(getContext(), storageKey) + "";
        ArrayList<String> storedCookiesList = new ArrayList<String>(Arrays.asList(storedCookiesString.split(";")));

        for (String storedCookie : storedCookiesList) {
            if(!currentCookieString.contains(storedCookie)) {
                CookieManager.getInstance().setCookie(url, storedCookie);
                CookieManager.getInstance().setCookie(cookieKey, storedCookie);
            }
        }
        cookieFetchListener.onCookiesFetched();
        saveCookies(null);
    }

    private String getHostName() {
        try {
            URL aURL = new URL(url);
            return aURL.getHost() + "";
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        Log.d(getClass().getSimpleName(), "Cookies attempting to save...");
        saveCookies(new CookieSaveListener() {
            @Override
            public void onCookiesSaved() {
                Log.d(getClass().getSimpleName(), "Cookies saved!");
            }
        });
    }

    interface CookieFetchListener {
        void onCookiesFetched();
    }
    interface CookieSaveListener {
        void onCookiesSaved();
    }
    interface WebViewListener {
        void onWebViewReady();
    }
}

I hope this can be useful to others as well.


text:
Q: set user group using ZKLibrary i need help to create a function in zkteco php library to change user group
this is my code but its not working,anybody can help me
reference url : https://github.com/adrobinoga/zk-protocol/blob/master/sections/access.md
zklibrary : https://github.com/kamshory/ZKLibrary
`public function userGroup($uid,$gid)
{
    $command = CMD_USERGRP_WRQ;
    $byte1 = chr((int) ($uid % 256));
    $byte2 = chr((int) ($uid >> 8));
    $byte3 = chr((int) ($gid));
    $command_string = $byte1 . $byte2 . $byte3;
    return $this->execCommand($command, $command_string);
}`

this function is not ok i think the $command_string is wrong but i cant rectify the error


text:
Q: save full dataframe into txt file I want to save the dataframe into txt file
#create the dataframe of timetable
import pandas as pd
timeline_table = pd.DataFrame.from_dict(timeline, orient = 'index', columns = ['events'])
a = timeline_table.reset_index()
r=a.rename(columns={"index": "years"})
final_table = r.shift()[1:]
print(final_table)

#save the timeline/timetable into new file
path= "data.txt"
with open(path, mode = 'w') as output:
    output.write(f'{final_table}')

The output is like this:
1   1000  About thirty countries maintain about seventy ...
2   1270  from which derived the Old French pole antarti...
3   1391  from which derived the Old French pole antarti...
4   1773  European maps continued to show this hypotheti...
5   1775  European maps continued to show this hypotheti...
..   ...                                                ...
57  2014  In 1985, three British scientists working on d...
58  2015  With the ban of CFCs in the Montreal Protocol ...
59  2018  which operated its own scientific station—Worl...

I want all the rows containing sentences corresponding to the extracted years to be fully displayed in the output file.
Is there any way to do that?

A: pd.set_option('display.max_colwidth', -1)


text:
Q: NSAutoReleasePool and async functions I have a function in my program that creates new widgets to represent data, however whenever a widget is created i get alot of "AutoRelease with no NSAutoReleasePool in place" error messages. Since an NSAutoReleasePool should be automatically created on the main thread, I have an inkling that these error messages appear because an async function might create my threads...
This is the function called to create widgets to represent the latest information. This function is called pretty often:
    private void CreateAndDisplayTvShowWidget (TvShow show)
    {
        var Widget = new TvShowWidgetController (show);
        Widget.OnRemoveWidget += ConfirmRemoveTvShow;

        Widget.View.SetFrameOrigin (new PointF (0, -150));
        Widget.View.SetFrameSize (new SizeF (ContentView.Frame.Width, 150));

        ContentView.AddSubview (Widget.View);
        show.ShowWidget = Widget;
    }

This function is usually called when this async function returns:
    private static void WebRequestCallback (IAsyncResult result)
    {
        HttpWebRequest request = (HttpWebRequest)result.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse (result);

        StreamReader responseStream = new StreamReader (response.GetResponseStream ());
        string responseString = responseStream.ReadToEnd ();
        responseStream.Close ();

        ProcessResponse (responseString, request);
    }

ProcessResponse (responseString, request) looks like this:
    private static void ProcessResponse (string responseString, HttpWebRequest request)
    {
        string requestUrl = request.Address.ToString ();

        if (requestUrl.Contains (ShowSearchTag)) {
            List<TvShow> searchResults = TvDbParser.ParseTvShowSearchResults (responseString);
            TvShowSearchTimeoutClock.Enabled = false;
            OnTvShowSearchComplete (searchResults);
        } else if (requestUrl.Contains (MirrorListTag)) {
            MirrorList = TvDbParser.ParseMirrorList (responseString);
            SendRequestsOnHold ();
        } else if (requestUrl.Contains (TvShowBaseTag)) {
            TvShowBase showBase = TvDbParser.ParseTvShowBase (responseString);
            OnTvShowBaseRecieved (showBase);
        } else if (requestUrl.Contains (ImagePathReqTag)) {
            string showID = GetShowIDFromImagePathRequest (requestUrl);
            TvShowImagePath imagePath = TvDbParser.ParseTvShowImagePath (showID, responseString);
            OnTvShowImagePathRecieved (imagePath);
        }
    }

CreateAndDisplayTvShowWidget (TvShow show) is called when the event OnTvShowBaseRecieved (TvShow) is called, which is when I get tons error messages regarding NSAutoReleasePool...
The last two functions are part of what is supposed to be a cross-platform assembly, so I can't have any MonoMac-specific code in there...
I never call any auto-release or release code for my widgets, so I assume that the MonoMac bindings does this automatically as part of its garbage collection?

A: You can create autorelease pools at point within the call stack, you can even have multiple nested autorelease pools with the same call stack. So you should be able to create your autorelease pools in the async entry functions.

A: You only need an NSAutoreleasePool if you use the auto-release features of objects. A solution is to create a NSAutoreleasePool around the code that manipulates auto-released objects (in the async callback).
Edit:
Have you tried to encapsulate the creation code with a NSAutoreleasePool ? As this is the only place where you call MonoMac code, this should solve the issue.
private void CreateAndDisplayTvShowWidget (TvShow show)
{
    using(NSAutoreleasePool pool = new NSAutoreleasePool())
    {
        var Widget = new TvShowWidgetController (show);
        Widget.OnRemoveWidget += ConfirmRemoveTvShow;

        Widget.View.SetFrameOrigin (new PointF (0, -150));
        Widget.View.SetFrameSize (new SizeF (ContentView.Frame.Width, 150));

        ContentView.AddSubview (Widget.View);
        show.ShowWidget = Widget;
    }
}

Note that even if you don't use auto-released objects directly, there are some case where the Cococa API use them udner the hood.

A: I had a similar problem and it was the response.GetResponseStream that was the problem. I surrounded this code with...
using (NSAutoreleasePool pool = new NSAutoreleasePool()) {
}

... and that solved my problem.


text:
Q: accessing VM arguments during compile time I have problem in accessing VM arguments in My program. I am writing an annotation processor in which i want to access some VM arguments. I am Using NETBeans IDE. I create the jar file of the annotation processor and then use it in another project which has java files with the annotations.
Now in my annotation processor project, In IDE i set the VM arguments as follows
-Dname="hello from VM"

and in the process() function of the annotation processor when i try to access it
String property = System.getProperty("name");

System.out.println(property);

It prints null.
Can we access these VM arguments during compile time As both the annotation processor and the annotated class run in the same VM ?
Thanks

A: I do not know of a way to access system properties from the annotation processor, but I think that the annotation processor options would support your use case.  Essentially you would want to implement getSupportedOptions in your processor, access the options via processingEnv.getOptions, and pass the options on the command line with -Aname=value.  Supported options may also be specified via the @SupportedOptions annotation.

A: You can pass options to the JVM that runs javac using -J, so
-J-Dname="hello from VM"

may possibly do what you require.

A: This works for me in Netbeans 8.0 under Windows 8.1 x64 with Java 1.8.0_05.  I can only presume its been fixed lately.
    Messager cm = processingEnv.getMessager();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        System.getProperties().storeToXML(baos, "System Properties");
    }
    catch (IOException ex) {
        cm.printMessage(Kind.ERROR, "Exception while getting System properties as XML: " + ex.getMessage());
    }
    cm.printMessage(Kind.NOTE, "\System.properties XML:\n" + baos.toString());

This will give me
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>System Properties</comment>
<entry key="java.runtime.name">Java(TM) SE Runtime Environment</entry>
<entry key="java.vm.vendor">Sun Microsystems Inc.</entry>
...
</properties>

The anwser of jbunting (i.e using processingEnv.getOptions()) is definitely more correct for cleanly passing key-value pairs to your annotation processor.


text:
Q: sh command in python fails I am a beginner in python. I got these scripts from IP vendor.
cmd = "sh compile_regression_vcs.sh"

try:
    self.agent.run_commands(cmd, pwd=self.agent.test_dir, extra_env=env)
except TestException as e:
    s = traceback.format_exc()
    serr = "there were errors:\n%s\n" % (s)
    self.logger.info(serr)
    raise TestException("Could not compile RTL")
except IOError as e:
    raise TestException("Could not compile RTL: %s" % str(e))

output looks like this:
TestException: command 'sh' generated 2 errors, aborting.

When i run sh command seperately without python, i donot get any errors. I donot understand why python gives an exception

A: Try this instead:
/bin/sh compile_regression_vcs.sh

Is compile_regression_vcs.sh in the current directory?

A: The issue could mainly be the path for you shell and your shell script.
It could also be that the environment that you are running in your shell maybe different from the one that you are using in your python script. Check this: extra_env=env
If you are still unable to zero in on issue you can debug further with following options:
You might want to use some debugging in your script to see the exact error.
Using sys.exc_info() would be a good option to see stack details.
you could use this piece of code in your exception block:
import sys
tb = sys.exc_info()[2]
    lst = format_list(extract_stack())
    for l in lst: print l,

or you could just use:
import traceback
traceback.print_exc()

much cleaner :)
Refer to: traceback,
sys
You can also run a python debugger to debug run_commands is executing as expected.
Simply put these lines of code in your try block and you will get into the interactive python debugger mode.
try:
    import pdb
    pdb.set_trace()
    self.agent.run_commands(cmd, pwd=self.agent.test_dir, extra_env=env)

you can later type help in python debugger mode to see all options available.
Refer:
pdb
You could also use inspect module:
inspect module


text:
Q: Router module in Angular 5 does not work, how to use it? I'm trying to use Router for redirection within my Angular 5 component.
In the app.module I have:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { HttpModule } from '@angular/http'
import { Router, RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { ProductFormComponent } from './productform/productform.component';
import { ProductComponent } from './productform/product/product.component';
import { ProductService } from './productform/shared/product.service';

@NgModule({
    declarations: [
        AppComponent,
        ProductFormComponent,
        ProductComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        ReactiveFormsModule,
        RouterModule
    ],
    exports: [
        RouterModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

In the component:
import { Injectable } from '@angular/core';
import { Component, OnInit, AfterViewChecked, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms'
import { Router, RouterModule } from '@angular/router'@Component({
    selector: 'app-product',
    templateUrl: 'product.component.html'
})
export class ProductComponent implements OnInit, AfterViewChecked {
    constructor(private router: Router) {
    }
}

Whenever I try to use this.router within component function I'm getting the error in the console:
Unhandled Promise rejection: StaticInjectorError[Router]:
  StaticInjectorError[Router]:
    NullInjectorError: No provider for Router! ; Zone: <root> ; Task: Promise.then ; Value: Error: "StaticInjectorError[Router]:
  StaticInjectorError[Router]:
    NullInjectorError: No provider for Router!"

I'm not sure I should add a provider and what provider?
I am new to angular, not fully understand how it works.
Thanks

A: You have to add routing information as follows.
const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent }, // These are dummy information
  { path: 'hero/',      component: HeroDetailComponent },
 ...
];

@NgModule({
  imports: [
    RouterModule.forRoot(
      appRoutes,
    )
    // other imports here
  ],
  ...
})
export class AppModule { }

Note : If you want to redirect to another component just call window.location.replace('url')

A: You have to use RouterModule.forRoot([]). If you don't have any route yet keep it empty. Use it in import like below:
imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        ReactiveFormsModule,
        RouterModule.forRoot([])
    ]

Find more details from the DOC

Note:
Here is the sample code from their DOC. If you have routes you could get idea from it.
import { NgModule }             from '@angular/core';
import { BrowserModule }        from '@angular/platform-browser';
import { FormsModule }          from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent }          from './app.component';
import { CrisisListComponent }   from './crisis-list.component';
import { HeroListComponent }     from './hero-list.component';

const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { path: 'heroes', component: HeroListComponent },
];

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- debugging purposes only
    )
  ],
  declarations: [
    AppComponent,
    HeroListComponent,
    CrisisListComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

A: You need to provide the router, tipically in the root of Your app. In Your import array use:
RouterModule.forRoot(routes)

You do not need to export RouterModule.
Of course you need a routes array too


text:
Q: Flutter MacOS app constantly requests firebase_auth keychain dialog depending on which release created the keychain As the title suggests, when I first submitted my app to testflight I noticed the dialog below. I found this issue on the firebase ios sdk repo. It should have been fixed. What I've done:

*

*Updated to the latest firebase flutter libs. Specifically 4.1.5 firebase auth.

*Enabled keychain sharing as described by the fix. I confirmed in the archive that the "keychain-access-groups" entitlement is present.

My observations.

*

*When the firebase_auth keychain is not present, I can build the app in debug locally and it works fine.

*With the keychain item now present, if I open a testflight build the dialog will always pop up until "Always Allow" is selected.

*If I log out and log back in with the testflight build the keychain dialog no longer pops up for the testflight build. But now pops up for my debug builds.

*If I update the app through testflight the keychain dialog comes back.
Any ideas how to avoid making the keychain dialog popup on testflight updates? I have not attempted to release the app because I don't want this happening in production.


text:
Q: How to reduce the execution time in Parallel.ForEach function? Code:
Parallel.ForEach(
    infoMap,
    map =>
    {
        var workItem = map.WorkItem;
        var parentInViews = viewMaps;
        var workbenchItem = map.WorkbenchItem;
        string LinkType = string.Empty;

        WorkItemLinkCollection linkedWorkItems = workItem.WorkItemLinkHistory;
        if (linkedWorkItems != null && linkedWorkItems.Count > 0)
            LinkType = linkedWorkItems[0].LinkTypeEnd.LinkType.ReferenceName;
        else if (workItem != null)
            LinkType = workItem.Store.WorkItemLinkTypes.LinkTypeEnds["Parent"].LinkType.ReferenceName;

        if (!string.IsNullOrEmpty(LinkType))
        {
            var viewMap = parentInViews.FirstOrDefault();
            if (viewMap != null)
            {
                var linkName =  LinkType;
                var childType = viewMap.ChildType;

                ILinkItem itm = Factory.BuildLinkItem(linkName, workbenchItem, workbenchItem);
                lock (Addparents)
                {
                    Addparents.Add(itm);
                }
            }
        }
    });

Factory.BuildLinkItem definition:
public static ILinkItem BuildLinkItem(string linkName, IWorkbenchItem parent, IWorkbenchItem child)
{
       return new LinkItem { LinkName = linkName ?? string.Empty, Child = child, Parent = parent };
}

Totally 658 items are present and it takes nearly 10 seconds to execute the above Parallel.ForEach function.
Is it possible to reduce the execution time and if so, please suggest me a solution. Thanks.
Note: Apart from Parallel.ForEach, if any alternate method is there to increase the performance and reduce the execution time also, Please suggest. Thanks.

A: Your problem is in the lock statement. The mutex mechanism behind it is extremely performance expensive compared to other synchronization mechanisms. I'm gonna bet 99.99% of those 10 seconds, the code spends locking and waiting in that critical section. Even non-parallel select would be much faster.
Your have two options. First is to use .AsParallel() .Select() and .Where() instead of Parallel.ForEach and adding into a collection inside a lock. I would highly recommend this. This way, the synchronization between operation on different items is handled automatically.
Second option is to use some kind of concurrent collection that exist in .NET 4 instead of locking and normal collection. Those collections are specially optimized to extra quick adding of items, that is threadsafe.
This is little hack, how could you simply convert it to AsParallel:
infoMap.AsParallel().Select(
map =>
{
    var workItem = map.WorkItem;
    var parentInViews = viewMaps;
    var workbenchItem = map.WorkbenchItem;
    string LinkType = string.Empty;

    WorkItemLinkCollection linkedWorkItems = workItem.WorkItemLinkHistory;
    if (linkedWorkItems != null && linkedWorkItems.Count > 0)
        LinkType = linkedWorkItems[0].LinkTypeEnd.LinkType.ReferenceName;
    else if (workItem != null)
        LinkType = workItem.Store.WorkItemLinkTypes.LinkTypeEnds["Parent"].LinkType.ReferenceName;

    if (!string.IsNullOrEmpty(LinkType))
    {
        var viewMap = parentInViews.FirstOrDefault();
        if (viewMap != null)
        {
            var linkName =  LinkType;
            var childType = viewMap.ChildType;

            ILinkItem itm = Factory.BuildLinkItem(linkName, workbenchItem, workbenchItem);

            return new {item = itm, filter=true};
        }
    }
    return new {item = (ILinkItem)null, filter=false};
})
.Where(x=>x.filter)
.Select(x=>x.item)
.ToList();


text:
Q: How to generate 10 random numbers in java and assign them to fields? I have one project in school where i need to make a simulation of keeping records for vehicles.
And Vehicle is abstract class which extends two classes (Automobile class and Motor class). There is also one Interface (NewRegistration) which contains one method register() and these two classes implements that interface. It should register a new registration for automobile and motor, but i should previously check if registration which i have insert is correct in one method checkNumber().
All in all, i have solved every task i have gotten, but only one i can't solve and it is to generate 10 random numbers..
Registration should have 15 characters, for first and second character UpperCase letter, for third character symbol "-", and for the the last two characters lowerCase letters.. other characters should be numbers and those numbers should be randomly generated.
Here is what i have done so far:
Automobile.java:
public class Automobil extends Vozilo implements NovaRegistracija{

private int brojVrata, brojSedista;

public Automobil(String marka, String model, String registracija, int kubikaza, int brojVrata, int brojSedista) {
    super(marka, model, registracija, kubikaza);
    this.brojVrata = brojVrata;
    this.brojSedista = brojSedista;
}

public Automobil() {

}

// checkNumber() method
@Override
public void proveriBroj() {
    boolean provera = true;
    boolean proveraKubikaze = true;
    String parsedInteger = String.valueOf(getKubikaza());

    for (int j = 0; j < parsedInteger.length(); j++) {
        if (Character.isLetter(parsedInteger.charAt(j))) {
            proveraKubikaze = false;
        }
    }

    // Checking registration
    if (this.getRegistracija().length() == 15) {
        if (Character.isUpperCase(getRegistracija().charAt(0)) && Character.isUpperCase(getRegistracija().charAt(1))) {
            if (getRegistracija().charAt(2) == '-') {
                if (Character.isLowerCase(getRegistracija().charAt(getRegistracija().length()-1)) && Character.isLowerCase(getRegistracija().charAt(getRegistracija().length()-2))) {
                    for (int i = 3; i < getRegistracija().length()-2; i++ ) {
                        if (!Character.isDigit(getRegistracija().charAt(i))) {
                            provera = false;
                            System.out.println("11111111111111111");
                            break;
                        }
                    }
                } else {
                    System.out.println("222222222222");
                    provera = false;
                }
            } else {
                System.out.println("333333333333");
                provera = false;
            }
        } else {
            System.out.println("44444444444444444");
            provera = false;
        }
    } else {
        System.out.println("555555555555555");
        provera = false;
    }

    if (proveraKubikaze) {
        System.out.println("Kubikaza je dobra!");
    } else {
        System.out.println("Kubikaza nije dobra!");
    }

    if (provera) {
        System.out.println("Broj registracije je ispravan!");
    } else {
        System.out.println("Broj registracije je neispravan!");
    }

}

// register() method from interface NewRegistration
@Override
public void registruj() {
    this.setRegistracija("AA-" + "aa");
    proveriBroj();
    System.out.println("- - - - - - - - - - - - - - - - - - - -");
}

public int getBrojVrata() {
    return brojVrata;
}

public void setBrojVrata(int brojVrata) {
    this.brojVrata = brojVrata;
}

public int getBrojSedista() {
    return brojSedista;
}

public void setBrojSedista(int brojSedista) {
    this.brojSedista = brojSedista;
}

}

So how would i now assign randomly 10 generate numbers for the whole registration of vehicle?
Thank you in advance.

A: Use org.apache.commons.lang.RandomStringUtils.
System.out.println(RandomStringUtils.randomNumeric(10));

A: Math.random() so this is the method i would go for, you can simply generate simple numbers by for ex. multiplying 10 and (or without) rounding.

public static double random()
Returns a double value with a positive sign, greater than or equal to
0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.

A: Here is a function I wrote:
import java.util.Random

private String generateRegistration() {
    String selectFrom1 = "ABCDEFGHIJKLMNOPRSTUVWXYZ";
    String selectFrom2 = "0123456789";
    String selectFrom3 = selectFrom1.toLowerCase();

    return randomFromSelection(selectFrom1,2)+"-"+randomFromSelection(selectFrom2,10)+randomFromSelection(selectFrom3,2)
}
private String randomFromSelection(String selection, int times) {
    Random random = new Random();
    String toReturn = "";
    for (int useless = 0; useless < times; useless++) {
        toReturn += selection.charAt(random.nextInt(selection.length()));
    }
    return toReturn;
}

This function is very flexible and can be used with any input for selection or times.


text:
Q: My user registration data isn't passing to the login route

usersRouter.post('/register', checkNotAuthenticated, async (req, res) => {
    console.log(req.body)
    const salt = await bcrypt.genSalt();
    const hashedPassword = await bcrypt.hash(req.body.password, salt);
    const user = new User ({
        name: req.body.name,
        email: req.body.email,
        password: hashedPassword
    })
    try {
        await user.save();
        res.redirect(201, '../users/login') /* 200 means accepted status, 201 created resource */
    } catch {
        res.redirect(500, 'users/register') /* Internal server error */
    }
    });

  usersRouter.post('/login', async (req, res) => {
  const user = await User.find({email: req.body.email})
    console.log(user)
    if (!user)  {
        return res.send('User does not exist')
    }
    try {
        if (!await bcrypt.compare(req.body.password, user.password)) {
            return res.status(401).send('password failed') /* user Unauthorized */
        } else {
            return res.status(200).send('password validated');
            }
    } catch (err) {
        res.send(err.message)
    }
})

In /register path
When I try to make a request, console.log(req.body) = [Object: null prototype] { name: 'p', email: 'p@p', password: '1' }
In /login path
console.log(user) = [], instead of the registered user
console.log(user.email) = undefined; instead of the registered user email


text:
Q: chat server setup in dotnet backend and flutter as front end I am very much not clear about how to set up chat application for flutter app. I have found lots of examples as running both the client and server from front end itself for flutter chat apps. But my doubt is, since I have a back end in dot net and I can set up or save the chats in dot net, why I need a separate chat server?
Or inorder to setup my dotnet server for a chat to receive and save what should I do?


text:
Q: python типы данных Есть набор данных типа object, если построить график по ним, то все получается нормально. Если поменять тип данных на float, то график совершенно не соответствует тому что при object. С чем это может быть связано? И как сделать так чтобы было и при float все корректно, так как для дальнейшей обработки нужны именно float. Заранее спасибо!
Данные загружаются из файла и создается DataFrame. Тип данных object.
Summary at time        GP

1005  3.0589000000000000e+04     65.22
1006  3.0619000000000000e+04  19391.91
1007  3.0650000000000000e+04     69.61
1008  3.0681000000000000e+04     59.79
1009  3.0710000000000000e+04     51.50
1010  3.0741000000000000e+04     47.63
1011  3.0771000000000000e+04   5821.52
1012  3.0802000000000000e+04   4659.31
1013  3.0832000000000000e+04   4056.77
1014  3.0863000000000000e+04   3649.93
1015  3.0894000000000000e+04   3357.23
1016  3.0924000000000000e+04   3121.40
1017  3.0955000000000000e+04   2923.38
1018  3.0985000000000000e+04   2764.70
1019  3.1016000000000000e+04   2620.68
1020  3.1047000000000000e+04   2498.85
1021  3.1075000000000000e+04   2390.34
1022  3.1106000000000000e+04   2288.30
1023  3.1136000000000000e+04   2191.79
1024  3.1167000000000000e+04   2105.11
1025  3.1197000000000000e+04   2024.18
1026  3.1228000000000000e+04   1946.56
1027  3.1259000000000000e+04   1880.71
1028  3.1289000000000000e+04   1812.01
1029  3.1320000000000000e+04   1748.42
1030  3.1350000000000000e+04   1691.69
1031  3.1381000000000000e+04   1644.56
1032  3.1412000000000000e+04   1598.90
1033  3.1440000000000000e+04   1564.24
1034  3.1471000000000000e+04   1519.17

При типе данных object ( x -time, y - GP)

При типе данных float ( x -time, y - GP)

Полный набор данных cvs файл

A: Как раз с типом данных float - график получается нормальным:
In[22]: df
Out[22]:
    Summary     time        GP
0      1005  30589.0     65.22
1      1006  30619.0  19391.91
2      1007  30650.0     69.61
3      1008  30681.0     59.79
4      1009  30710.0     51.50
..      ...      ...       ...
25     1030  31350.0   1691.69
26     1031  31381.0   1644.56
27     1032  31412.0   1598.90
28     1033  31440.0   1564.24
29     1034  31471.0   1519.17
[30 rows x 3 columns]

In[23]: df.plot.scatter(x='time', y='GP')