text:
Q: 'NoneType' object is not subscriptable - error at Keras custom callback class I am getting this error when I am defining a custom callback function.
'NoneType' object is not subscriptable

Code sample
class Metrics(tf.keras.callbacks.Callback):
  def on_train_begin(self, logs={}):
        self._data = []
  def on_epoch_end(self, batch, logs={}):
        X_val, y_val = self.validation_data[0], self.validation_data[1]
        y_predict = np.asarray(model.predict(X_val))
        y_val = np.argmax(y_val, axis=1)
        y_predict = np.argmax(y_predict, axis=1)
        self._data.append({
          'val_jaccard': jaccard(y_val, y_predict),
          'val_f1': f1_score(y_val, y_predict),
          'val_precision': recall_score(y_val, y_predict),
          'val_jaccard': precision_score(y_val, y_predict),
     })
    return

metrics = Metrics()
model.fit((item for item in image_data),steps_per_epoch=steps_per_epoch,
     epochs=20, validation_data = (item for item in image_data_val), validation_steps = valid_step , callbacks = [metrics], verbose=2)

Previously I was getting another error: "AttributeError: 'Sequential' object has no attribute 'validation_data'. In order to solve that error, I removed self.model.validation_data with self.validation_data as suggested here. After which I landed up to this error. I am not able to understand the source of this error
Keras version is 2.2.4
Complete traceback as requested
Epoch 1/20

Exception ignored in: <bound method BaseSession._Callable.__del__ of <tensorflow.python.client.session.BaseSession._Callable object at 0x7f8fbe48fa20>>
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py", line 1473, in __del__
    self._session._session, self._handle)
tensorflow.python.framework.errors_impl.CancelledError: (None, None, 'Session has been closed.')
Exception ignored in: <bound method BaseSession._Callable.__del__ of <tensorflow.python.client.session.BaseSession._Callable object at 0x7f8fbe42f2e8>>
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py", line 1473, in __del__
    self._session._session, self._handle)
tensorflow.python.framework.errors_impl.CancelledError: (None, None, 'Session has been closed.')

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-102-43fa8dafc96c> in <module>()
      5     model.fit((item for item in image_data),steps_per_epoch=steps_per_epoch, epochs=20,
      6                     validation_data = (item for item in image_data_val),
----> 7                     validation_steps = valid_step , callbacks = [metrics], verbose=2)
      8     eval_model=model.evaluate(image_batch, label_batch)
      9     eval_model

4 frames

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    671           use_multiprocessing=use_multiprocessing,
    672           shuffle=shuffle,
--> 673           initial_epoch=initial_epoch)
    674     if training_utils.is_eager_dataset_or_iterator(x):
    675       # Make sure that y, sample_weights, validation_split are not passed.

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, validation_freq, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
   1431         shuffle=shuffle,
   1432         initial_epoch=initial_epoch,
-> 1433         steps_name='steps_per_epoch')
   1434
   1435   def evaluate_generator(self,

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training_generator.py in model_iteration(model, data, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, validation_freq, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch, mode, batch_size, steps_name, **kwargs)
    329     if mode == ModeKeys.TRAIN:
    330       # Epochs only apply to `fit`.
--> 331       callbacks.on_epoch_end(epoch, epoch_logs)
    332     progbar.on_epoch_end(epoch, epoch_logs)
    333

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/callbacks.py in on_epoch_end(self, epoch, logs)
    309     logs = logs or {}
    310     for callback in self.callbacks:
--> 311       callback.on_epoch_end(epoch, logs)
    312
    313   def on_train_batch_begin(self, batch, logs=None):

<ipython-input-101-71d6af0b20ff> in on_epoch_end(self, batch, logs)
     14
     15   def on_epoch_end(self, batch, logs={}):
---> 16         X_val, y_val = self.validation_data[0], self.validation_data[1]
     17         y_predict = np.asarray(model.predict(X_val))
     18         y_val = np.argmax(y_val, axis=1)

TypeError: 'NoneType' object is not subscriptable

UPDATE
Based on the suggestion, I am using keras for callback i.e class Metrics(keras.callback.Callback). After this solution, my original error is gone but I am getting another error which is AttributeError: 'Metrics' object has no attribute 'on_train_batch_begin'
I don't really know this error.
The traceback for the new error is
    Epoch 1/20

---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-60-43fa8dafc96c> in <module>()
      5     model.fit((item for item in image_data),steps_per_epoch=steps_per_epoch, epochs=20,
      6                     validation_data = (item for item in image_data_val),
----> 7                     validation_steps = valid_step , callbacks = [metrics], verbose=2)
      8     eval_model=model.evaluate(image_batch, label_batch)
      9     eval_model

3 frames

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    671           use_multiprocessing=use_multiprocessing,
    672           shuffle=shuffle,
--> 673           initial_epoch=initial_epoch)
    674     if training_utils.is_eager_dataset_or_iterator(x):
    675       # Make sure that y, sample_weights, validation_split are not passed.

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, validation_freq, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
   1431         shuffle=shuffle,
   1432         initial_epoch=initial_epoch,
-> 1433         steps_name='steps_per_epoch')
   1434
   1435   def evaluate_generator(self,

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training_generator.py in model_iteration(model, data, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, validation_freq, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch, mode, batch_size, steps_name, **kwargs)
    258       # Callbacks batch begin.
    259       batch_logs = {'batch': step, 'size': batch_size}
--> 260       callbacks._call_batch_hook(mode, 'begin', step, batch_logs)
    261       progbar.on_batch_begin(step, batch_logs)
    262

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/callbacks.py in _call_batch_hook(self, mode, hook, batch, logs)
    245     t_before_callbacks = time.time()
    246     for callback in self.callbacks:
--> 247       batch_hook = getattr(callback, hook_name)
    248       batch_hook(batch, logs)
    249     self._delta_ts[hook_name].append(time.time() - t_before_callbacks)

AttributeError: 'Metrics' object has no attribute 'on_train_batch_begin'

A: Its a bug in tf.keras, they deprecated the validation_data parameter and no longer set the validation_data of the callback, its always set to None.
Your option is not to use tf.keras and just use the official keras package, I tested your code and it works in Keras 2.2.4. Alternatively you could also just pass your validation data to the __init__ of your callback and set it there.

A: I think you can solve this by passing the validation_dataset to your Metrics class instead of relying on.. How was self.validation_data supposed to get set?


text:
Q: Model on itemview is not shown I am having a trouble displaying the model in an itemview.
Currently using require.js with backbone.marionette.
this is my header template:
// header.js
define( [
   "jquery",
   "underscore",
   "marionette",
   "user",
   "userSession",
   "text!../../tpl/header_template.html"
   ], function ( $, _, Marionette, User, UserSession, HeaderTemplate ) {

  return Marionette.ItemView.extend( {
     template: HeaderTemplate,

     initialize: function(){
        alert(UserSession.firstName + " " + UserSession.lastName)
     },

     onRender: function(){
        alert(UserSession.firstName + " " + UserSession.lastName)
     },

     model: new User({
        lastName: UserSession.lastName,
        firstName: UserSession.firstName
        })
    });
  });

this is the template snippet code
   Logged in as <%= firstName %> <%= lastName %>

and this the code when I try to display the itemview
// attached the view
layout.header.show(new HeaderView());

When I run this code, the view is rendered fine, but the model (firstname and lastname) data is not correct. firstname and lastname are both null. The weird thing is both on initialize and onRender, they both display the first name and last name correctly.
Does anyone know how to overcome this?

A: I think you should do like:
initialize: function(){

    this.model = new User({
        lastName: UserSession.lastName,
        firstName: UserSession.firstName
    });
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: mocking a class used by a Gradle plugin when testing I'm writing a Gradle plugin that interacts with an external HTTP API. This interaction is handled by a single class (let's call it ApiClient). I'm writing some high-level tests that use Gradle TestKit to simulate an entire build that uses the plugin, but I obviously don't want them to actually hit the API. Instead, I'd like to mock ApiClient and check that its methods have been called with the appropriate arguments, but I'm not sure how to actually inject the mocked version into the plugin. The plugin is instantiated somewhere deep within Gradle, and gets applied to the project being executed using its void apply(Project project) method, so there doesn't appear to be a way to inject a MockApiClient object.
Perhaps one way is to manually instantiate a Project, apply() the plugin to it (at which point, I can inject the mocked object because I have control over plugin instantiation), and then programmatically execute a task on the project, but how can I do that? I've read the Gradle API documentation and haven't seen an obvious way.
A worst-case solution will be to pass in a debug flag through the plugin extension configuration, which the plugin will then use to determine whether it should use the real ApiClient or a mock (which would print some easily grep-able messages to the STDOUT). This isn't ideal, though, since it's more fuzzy than checking the arguments actually passed to the ApiClient methods.

A: Perhaps you could split your plugin into a few different plugins

*

*my-plugin-common - All the common stuff

*my-plugin-real-services - Adds the "real" services to the model (eg RealApiClient)

*my-plugin-mock-services - Adds "mock" services to the model (eg MockApiClient)

*my-plugin - Applies my-plugin-real-services and my-plugin-common

*my-plugin-mock - Applies my-plugin-mock-services and my-plugin-common
In the real world, people will only ever apply: 'my-plugin'
For testing you could apply: 'my-plugin-mock'


text:
Q: Content Alignment For Custom Control I'm writing my own library of controls. I'm working on the check box control and one of the final things that I need help on is drawing the check box in relation to the text. I have a ContentAlignment property that can change where the text appears in the control, but I'm not sure how to adjust the check box in relation to that because I don't know how to get the location of the text in the control.
    protected override void OnPaint(PaintEventArgs e)
    {
        Graphics canvas = e.Graphics;
        canvas.SmoothingMode = SmoothingMode.HighQuality;
        int x = 0;
        int y = (int)(canvas.MeasureString(this.Text, this.Font).Height - 12) / 2;
        switch (this.Style)
        {
            case E.CheckBoxStyle.Check:
                canvas.DrawRectangle(new Pen(this.BorderColor), new Rectangle(x, y, 12, 12));
                if (this.Checked)
                    canvas.DrawString("√", new Font("serif", 7f, FontStyle.Bold), Brushes.Black, 1f, 3f);
                break;
            case E.CheckBoxStyle.Round:
                canvas.DrawEllipse(new Pen(this.BorderColor), new Rectangle(x, y, 12, 12));
                if (this.Checked)
                {
                    Rectangle region = new Rectangle(x + 1, y + 1, 10, 10);
                    canvas.FillEllipse(Functions.CreateGradient(region, this.FillColor, 90), region);
                }
                break;
            case E.CheckBoxStyle.Square:
                canvas.DrawRectangle(new Pen(this.BorderColor), new Rectangle(x, y, 12, 12));
                if (this.Checked)
                {
                    Rectangle region = new Rectangle(x + 1, y + 1, 10, 10);
                    canvas.FillRectangle(Functions.CreateGradient(region, this.FillColor, 90), region);
                }
                break;
        }
        if (!this.AutomaticSize)
        {
            StringFormat format = new StringFormat();
            switch (this.Alignment)
            {
                case ContentAlignment.TopRight:
                    format.Alignment = StringAlignment.Far;
                    format.LineAlignment = StringAlignment.Near;
                    break;
                case ContentAlignment.TopLeft:
                    format.Alignment = StringAlignment.Near;
                    format.LineAlignment = StringAlignment.Near;
                    break;
                case ContentAlignment.TopCenter:
                    format.Alignment = StringAlignment.Center;
                    format.LineAlignment = StringAlignment.Near;
                    break;
                case ContentAlignment.MiddleRight:
                    format.Alignment = StringAlignment.Far;
                    format.LineAlignment = StringAlignment.Center;
                    break;
                case ContentAlignment.MiddleLeft:
                    format.Alignment = StringAlignment.Near;
                    format.LineAlignment = StringAlignment.Center;
                    break;
                case ContentAlignment.MiddleCenter:
                    format.Alignment = StringAlignment.Center;
                    format.LineAlignment = StringAlignment.Center;
                    break;
                case ContentAlignment.BottomRight:
                    format.Alignment = StringAlignment.Far;
                    format.LineAlignment = StringAlignment.Far;
                    break;
                case ContentAlignment.BottomLeft:
                    format.Alignment = StringAlignment.Near;
                    format.LineAlignment = StringAlignment.Far;
                    break;
                case ContentAlignment.BottomCenter:
                    format.Alignment = StringAlignment.Center;
                    format.LineAlignment = StringAlignment.Far;
                    break;
            }
            canvas.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), ClientRectangle, format);
        }
        else
        {
            canvas.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), 14f, 0f);
            Size newSize = Size.Round(canvas.MeasureString(this.Text, this.Font));
            this.Size = new Size(newSize.Width + 14, newSize.Height);
        }
    }

One solution is to take away the property completely, I suppose. But that's not ideal. Another, I thought make a rectangle that contains the check box as well as the text and to move that rectangle accordingly but I don't know how to implement that. Thanks for any help! Here's a picture that might help show the problem:

A: Instead of any of the excessive code used for the switch statement you can use this extension I wrote:
public static Point AlignDrawingPoint(this Graphics g, Size objectSize, Rectangle clientRectangle, ContentAlignment alignment)
{
    int margin = 4;
    Point center = new Point((clientRectangle.Width >> 1) - (objectSize.Width >> 1), (clientRectangle.Height >> 1) - (objectSize.Height >> 1));
    int rightMargin = clientRectangle.Width - (objectSize.Width + margin);
    int bottomMargin = clientRectangle.Height - (objectSize.Height + margin);
    Point p = Point.Empty;
    switch (alignment)
    {
        case ContentAlignment.TopLeft:
            p = new Point(margin, margin);
            break;
        case ContentAlignment.TopCenter:
            p = new Point(center.X, margin);
            break;
        case ContentAlignment.TopRight:
            p = new Point(rightMargin, margin);
            break;
        case ContentAlignment.MiddleLeft:
            p = new Point(margin, center.Y);
            break;
        case ContentAlignment.MiddleCenter:
            p = new Point(center.X, center.Y);
            break;
        case ContentAlignment.MiddleRight:
            p = new Point(rightMargin, center.Y);
            break;
        case ContentAlignment.BottomLeft:
            p = new Point(margin, bottomMargin);
            break;
        case ContentAlignment.BottomCenter:
            p = new Point(center.X, bottomMargin);
            break;
        case ContentAlignment.BottomRight:
            p = new Point(rightMargin, bottomMargin);
            break;
    }
    p.Offset(clientRectangle.X, clientRectangle.Y);
    return p;
}

You can use this extension not just for drawing strings, you can use this extension when needing to align anything you need to draw within a rectangle.
But in your case you would do something like this:
g.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), AlignDrawingPoint(g.MeasureString(this.Text, this.Font).ToSize(), this.ClientRectangle, this.TextAlign));


text:
Q: Understanding Proposition 10.28 in Rotman's homological algebra (Spectral sequence) I am reading the Rotman's Introduction to homological algebra, p.641, Proposition 10.28 and stuck at understanding some statement :

I am trying to understand the underlined statements. For example,
Q. 1) Why $E^{\infty}_{1, n-1} = Z^{\infty}_{1,n-1}/B^{\infty}_{1,n-1} =0$ (c.f. his book p.624 definition) is true?
Q. 2) Why $\Phi^{t+1}H_n / \Phi^{t}H_n \cong E^{\infty}_{t+1,n-t-1}=0$ (If so, then $\Phi^{t}H_n = \Phi^{t+1}H_n $) is true?
What property of $E^{\infty}$ can we use? Using the (ii) in the proposition 10.28? I think that I am unfamiler to deep(?) structure of the limit term $E^{\infty}$ of spectral sequence. (If we understand this issue, then it seems that it will be great help for increasing undersanding theory of spectral sequence.) Can anyone helps?

A: Observe that $E^\infty_{p,q}$ is a subquotient of $E^2_{p,q}$.  By hypothesis, $E^2_{p,q} = 0$ if $p \notin \{0, t\}$.  So $E^\infty_{p,q} = 0$ for $p \notin \{0, t\}$.


text:
Q: Can't create procedure with mysqli, but can with phpmyadmin? trying to create a stored procedure through mysqli in php. Keep throwing back at 1064 error when I do it through php, but is fine, when I copy the same sql command in php. Anyone able to shed some light on what could be the problem, or anyone found a solution to something similar?
Create Procedure code:
DELIMITER //
CREATE PROCEDURE 6de443aacf727f6009e857480f33153cmakeLive (IN taskID INT, IN avaliableTime INT)
    BEGIN
        DECLARE done INT DEFAULT FALSE;
        DECLARE a INT;
        DECLARE cur1 CURSOR FOR SELECT t.`task_id`
            FROM `task_dependency` d
            LEFT OUTER JOIN (
                SELECT `task_id`, `dependent_on_task_id`, ti.`id`, min(ti.`completed`) as make_live
                FROM `task_dependency`
                LEFT OUTER JOIN (
                    SELECT `task_id`, `completed` FROM `6de443aacf727f6009e857480f33153c_tasks`
                ) ti ON ti.`task_id` = `dependent_on_task_id`
                GROUP BY `task_id`
            ) t ON d.`task_id` = t.`task_id`
            WHERE d.`dependent_on_task_id` = taskID
                AND t.make_live > 0;
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

        OPEN cur1;

        read_loop: LOOP
            FETCH cur1 INTO a;
            IF done THEN
                LEAVE read_loop;
            END IF;
            UPDATE `6de443aacf727f6009e857480f33153c_tasks` SET `live` = 1 WHERE `task_id` = a;
        END LOOP;

        CLOSE cur1;

        UPDATE `6de443aacf727f6009e857480f33153c_tasks` SET `earliest_start` = avaliableTime WHERE `task_id` IN (
            SELECT `task_id`
            FROM `task_dependency`
            WHERE `dependent_on_task_id` = taskID
        ) AND `earliest_start` < avaliableTime;
    END //
DELIMITER ;

PHP Code:
if (!$this->dbc->query("DROP PROCEDURE IF EXISTS " . $this->table_prefix . "makeLive") ||
    !$this->dbc->query($query)) {
    echo "Stored procedure creation failed: (" . $this->dbc->errno . ") " . $this->dbc->error . "

" . $query;
    exit;
}
echo "success";
exit;

Script execution is throwing out the following error...
Stored procedure creation failed: (1064) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER //
        CREATE PROCEDURE 6de443aacf727f6009e857480f33153cmakeLive (IN tas' at line 1

Although it says it's a syntax error, the fact a straight copy and paste of the command to phpmyadmin seems to work, looks like it's gotta be some sort of mysqli bug perhaps?

A: The query function only allows you to execute a single query.  Try the multi_query function (documentation: http://www.php.net/manual/en/mysqli.multi-query.php ) instead.  It allows for multiple commands, and may fix your issue.

A: Turns out mysqli->query already parses semi-colons and runs the whole command. The delimiter commands at the start and end of the query where unnecessary in successfully creating the procedure.

A: Just remove DELIMITER and it will work. So in your case it will be like this:
CREATE PROCEDURE 6de443aacf727f6009e857480f33153cmakeLive (IN taskID INT, IN avaliableTime INT)
BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE a INT;
    DECLARE cur1 CURSOR FOR SELECT t.`task_id`
        FROM `task_dependency` d
        LEFT OUTER JOIN (
            SELECT `task_id`, `dependent_on_task_id`, ti.`id`, min(ti.`completed`) as make_live
            FROM `task_dependency`
            LEFT OUTER JOIN (
                SELECT `task_id`, `completed` FROM `6de443aacf727f6009e857480f33153c_tasks`
            ) ti ON ti.`task_id` = `dependent_on_task_id`
            GROUP BY `task_id`
        ) t ON d.`task_id` = t.`task_id`
        WHERE d.`dependent_on_task_id` = taskID
            AND t.make_live > 0;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    OPEN cur1;

    read_loop: LOOP
        FETCH cur1 INTO a;
        IF done THEN
            LEAVE read_loop;
        END IF;
        UPDATE `6de443aacf727f6009e857480f33153c_tasks` SET `live` = 1 WHERE `task_id` = a;
    END LOOP;

    CLOSE cur1;

    UPDATE `6de443aacf727f6009e857480f33153c_tasks` SET `earliest_start` = avaliableTime WHERE `task_id` IN (
        SELECT `task_id`
        FROM `task_dependency`
        WHERE `dependent_on_task_id` = taskID
    ) AND `earliest_start` < avaliableTime;
END;


text:
Q: MVC Ajax.error render Partial View While working with the Kendo UI Grid for ASP.NET MVC I am finding some frustrating behavior that I can't seem to understand or find any information on.  I have a grid which makes a kendoGrid.saveChanges() request to the server which has some server side validation.  If the server-side validation fails, it returns the following result:
Response.StatusCode = HTTP_BAD_CLIENT_REQUEST; // const int 400
return PartialView("Error/BadRequest");

The partial view just has some basic HTML for displaying the error information to the user, and the grid's datasource error callback does the following:
function errorCallback(e) {
    // Handles explicit Ajax and Kendo DataSource error callbacks
    var content = e.responseText || e.xhr.responseText;
    // Wrapper around a kendo.ui.Window to display content
    Core.Alert.raiseAlert(content);
}

When I run my project in debug mode, or publish the Release version of the project to my local machine the e.xhr.responseText value is populated correctly i.e. it contains the partial view's HTML message. However, as soon as I move this to the production server the e.xhr.responseText simply contains the value "Bad Request" which is also the HTTP status code I am currently using. I've tried using other status codes but the result is the same (error name is used as the responseText).
The reason I find this to be so odd is that I am doing something similar in another project for an internal application at our company and this works perfectly fine. They are running on the same versions and tools of both Kendo and ASP.NET.
Can anyone point me in the direct of tools or documentation, Kendo or AJAX, which explain why the response text is not using my partial view result or how I can map the partial view result I am sending to the xhr.responseText property?
Edit: With trying different error codes, I found that certain status codes such 405 (Not Allowed) resulted in the IIS server error html being returned. So now I'm really stumped, why is it that some status codes simply return a name of the request, while others return templated HTML for that error code when I am specifying the return value and view to return?

A: Credit for findings and solutions goes to this post.
After doing some digging, I figured out that the issue came down to IIS overriding the content (and therefore partial view) being sent when I used the error HTTP status codes.
The solution is to add an <httpErrors> tag to the system.webServer in the web.config.  I found that the following was sufficient to get my partial views to reach the client.
<system.webServer>
    <httpErrors existingResponse="PassThrough" />
</system.webServer>


text:
Q: Plotting equation to cartesian plane I am trying to plot a two variable equation to a Cartesian plane. Here is my problem, on the code below if I comment out one for loop and let another run, the plot of the graph (the negative or positive sides of x) is correct, but if I run both for loops they seem to alter each other and the graph comes out wrong. I've tried every combination of for loops, looping frontward, backward, nothing seems to solve it.
I commented out the where these loops are at the end of the class "public class DrawingComponent extends JComponent" where it says "// This two loops work fine if each one is run independently"
public class GraphingCalc extends JFrame {

    private static final int FRAME_WIDTH = 450;
    private static final int FRAME_HEIGHT = 400;

    private static final double INITIAL_BALANCE = 1000;

    private JLabel rateLabel;
    private JTextField rateField;
    public JButton button ;
    private JLabel resultLabel;

    private JPanel basePanel;
    private JPanel topPanel; // will contain rateLabel, rateField, and buton
    private JPanel bottomPanel; // will contain drawingComponent

    JComponent drawingComponent;

    Rectangle box;
    //////////////////////////////
    Graph graphObj;
    double xCoord;
    int yCoord_size;
    double xRate;
    double[] yCoord;
    //////////////////////////////

    public GraphingCalc() {

        createTextField();

        drawingComponent = new DrawingComponent();
        box = new Rectangle(100, 100, 20, 30);
        graphObj = new Graph();
        xCoord = 0;

        yCoord_size = 400;
        xRate = 0.101;

        yCoord = new double[yCoord_size];

        createButton();

        createPanel();

        setSize(FRAME_WIDTH, FRAME_HEIGHT);
    }

    private void createTextField() {

        rateLabel = new JLabel("Equation: ");

        final int FIELD_WIDTH = 10;
        rateField = new JTextField(FIELD_WIDTH);

    }

public void createButton() {

        button = new JButton("Plot");

         class AddInterestListener implements ActionListener {

            public void actionPerformed(ActionEvent event) {

                if(event.getSource() == button) {

                    //System.out.println("Boo");
                    graphObj.setEq(rateField.getText());

                }
                else {

                }

                //yCoord = Arrays.copyOf(graphObj.setY(), 10);
                yCoord = graphObj.getY(drawingComponent.getSize().width);

                //for(int i=0; i<10; i++)
                    //System.out.println("yCoord: " + yCoord[i] +"\n");

                revalidate();
                repaint();

            }
        }
        ActionListener listener = new AddInterestListener();
        button.addActionListener(listener);
    }

public class DrawingComponent extends JComponent {

    public void paintComponent(Graphics g) {

            //////////////////////////
            // int scale
            // multiply coord values by this
            // scale
            /////////////////////////
            Graphics2D g2 = (Graphics2D) g;

            g2.setStroke(new BasicStroke(1f));
            //g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            int drawArea_width = getSize().width;
            int drawArea_height = getSize().height;

            /////////////////////
            // x axis
            g2.draw(new Line2D.Double( 0, drawArea_height/2, drawArea_width ,drawArea_height/2 ));
            Font font = new Font("Times New Roman", Font.PLAIN, 10);
            g2.setFont(font);

            //positive x axis values

            for(int i = 1; i < 20; i++) {

                String num = Integer.toString(i);
                if(i >= 10) {
                    g2.draw(new Line2D.Double((drawArea_width/2 -19 ) + i*12 , (drawArea_height/2) -2 , (drawArea_width/2 -19 ) + i*12 , (drawArea_height/2) + 2 ));
                    g2.drawString(num, (drawArea_width/2 -22 ) + i*12  , (drawArea_height/2) + 15 );
                }

                else {
                    g2.draw(new Line2D.Double((drawArea_width/2) + i*10 , (drawArea_height/2) -2 , (drawArea_width/2) + i*10 , (drawArea_height/2) + 2 ));
                    g2.drawString(num, (drawArea_width/2 -1) + i*10 , (drawArea_height/2) + 15 );
                }
            }
            //

            //negative x axis values
            for(int i = 20; i > 0; i--) {

                String num = Integer.toString(i);
                if(i <= 9) {

                    g2.draw(new Line2D.Double((drawArea_width/2 ) - i*13 , (drawArea_height/2) -2 , (drawArea_width/2 ) - i*13 , (drawArea_height/2) + 2 ));
                    g2.drawString("-" + num, (drawArea_width/2 - 4) - i*15 , (drawArea_height/2) + 15 );
                }

                else {

                    g2.draw(new Line2D.Double((drawArea_width/2 + 16 ) - i*15 , (drawArea_height/2) -2 , (drawArea_width/2 + 16 ) - i*15 , (drawArea_height/2) + 2 ));
                    g2.drawString("-" + num, (drawArea_width/2 + 16 ) - i*17  , (drawArea_height/2) + 15 );
                }
            }
            //

            //////////////////////

            //y axis
            g2.draw(new Line2D.Double( drawArea_width/2, 0, drawArea_width/2, drawArea_height ));

            g2.setStroke(new BasicStroke(1.20f));

            // This two loops work fine if each one is run independently

            xCoord = 0;
            for(int i = 0; i < yCoord_size/2 ; i++) {

                //g2.draw(new Line2D.Double((drawArea_width/2 ) + xCoord , yCoord[i] + (drawArea_height/2), (drawArea_width/2 ) + xCoord , yCoord[i] + (drawArea_height/2) ) );
                g2.draw(new Ellipse2D.Double((drawArea_width/2 ) + xCoord , yCoord[i] + (drawArea_height/2), 1, 1));
                xCoord-= xRate;
            }

            /*
            for(int i = yCoord_size/2; i < yCoord_size ; i++) {

                //g2.draw(new Line2D.Double((drawArea_width/2 ) + xCoord , yCoord[i] + (drawArea_height/2), (drawArea_width/2 ) + xCoord , yCoord[i] + (drawArea_height/2) ) );
                g2.draw(new Ellipse2D.Double((drawArea_width/2 ) + xCoord , yCoord[i] + (drawArea_height/2), 1, 1));
                xCoord+= xRate;
            }
            */

        }
}

    private void createPanel() {

        basePanel = new JPanel();
        topPanel = new JPanel();

        basePanel.setLayout(new BorderLayout());

        topPanel.add(rateLabel);
        topPanel.add(rateField);
        topPanel.add(button);

        basePanel.add(topPanel, BorderLayout.NORTH);
        basePanel.add(drawingComponent, BorderLayout.CENTER);

        add(basePanel);
    }
}

public class Graph {

    int yCoord_size;
    double xRate;
    String equation;
    double[] yCoord;
    static double num;

    public Graph() {

        yCoord_size = 400;
        xRate = 0.101;

        equation = "";
        num = 0;
        yCoord = new double[yCoord_size];

        for(int i=0; i <10; i++)
            yCoord[i] = 0;
    }

    public void setEq(String eq) {

        equation = eq;

        //System.out.println("eq is: " + eq);

    }

    public double equationStrToVal(String eq, double inX){

        double total = 0.0;
        double x = inX;
        String[] tokens;
        tokens = eq.split(" ");

        for(int i=0; i<tokens.length; i++){

            if(tokens[i].equalsIgnoreCase("x")){

                total+= x;
            }

            //addition
            else if(tokens[i].equals("+")){
                if(tokens[i+1].equalsIgnoreCase("x"))
                    total+= x;
                else
                    total+= stringToDouble( tokens[i+1]);
                i++;
            }

            //multiplication
            else if(tokens[i].equals("*")){
                if(tokens[i+1].equalsIgnoreCase("x"))
                    total*= x;
                else
                    total*=stringToDouble( tokens[i+1]);
                i++;
            }

            //raised to a power

        }

        return total;
        //System.out.println("The result is: " + total);
    }

    public double[] getY(int screen_width) {

        double j = 0.0;

        //for(int i=0 ; i < screen_width/2; i++, j-=0.05)
        for(int i=0 ; i < yCoord_size/2; i++, j-=xRate)
            yCoord[i] =  -1 * equationStrToVal(equation, j);

        j = 0;

        //for(int i=screen_width/2 ; i<screen_width ; i++, j+=0.05)
        for(int i= yCoord_size/2 ; i< yCoord_size ; i++, j+=xRate)
            yCoord[i] = -1 * equationStrToVal(equation, j);

        return yCoord;
    }

    static double stringToDouble(String num){

        return ( Double.valueOf(num.trim()).doubleValue());

    }

}

public class GraphingCalcViewer {

    public static void main(String[] args) {

        JFrame frame = new GraphingCalc();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

}

A: if you comment out one loop the other loop always start with xCoord = 0;
if you run both loops the second starts with the current xCoord.value
it looks like you have to set "xCoord = 0;" before the second loop;


text:
Q: Why undefine location in Flutter coonection with GraphQL?
*

*enter image description here
Query(
options: QueryOptions(documentNode: gql(
r"""
query getAllLookups{
getAllLookups{
nodes{
_id
name
}
totalCount    } }
""" ),pollInterval: 1),
builder: (QueryResult result, { VoidCallback refetch, FetchMore fetchMore }){
return Center(child: result.hasException ? Text(result.exception.toString())
:Text("comoplete"));
        return Center(child: Text("getting"));
      }

  ),**strong text**


text:
Q: How to use an Object in a trait by using its type in Scala I was trying to implement some Model - Row implementation similar that Rails (Activerecord)  in Scala. I simply trying to do this;
trait Model[A]:
  def query = "model has this good stuff I want to use in RowData"

trait RowData[B <: Model[B]]:
  def query = B.query

case class Person(name: String, age: Int) extends RowData[Person]

object Person extends Model[Person]

Person("onur", 38).query // I wan't to use like this

I'm getting Not found: B on RowData trait. Because Model[A] is an object I supposed that I can use it as is.
You can try in here: https://scastie.scala-lang.org/U3MOJhFXSS2O8fanY5aIpg

A: trait RowData[B <: Model[B]]:
  def query = B.query

This is not supported because (among other reasons) the query method might not exist.
The problem is that the type of the companion object is not related to the type of the class. So the fact that B is a subclass of Model[B] says nothing about the type of the companion object of B. And specifically, it does not require the companion object of B to be a subclass of Model[B] and therefore it is not required to have the appropriate query method.
The other problem is that this does not compile:
trait RowData[B <: Model[B]]:
  def query = B.query

case class Person(name: String, age: Int) extends RowData[Person]

The RowData trait requires that Person is a subclass of Model[Person] but Person does not inherit from Model[Person]
You either need to have Person inherit from Model and provide the appropriate query method, or look at using a type class for this problem.

A: It seems the requirement is to use the companion object's method, but the issue with this solution is that, given this code:
trait RowData[B <: Model[B]]:
  def query = B.query

Because B is supposed to be the companion object, it cannot be passed as a type in []. You need to pass it as an object in parentheses (), like this:
trait Model[A]:
  def query = "model has this good stuff I want to use in RowData"

trait RowData(B: Model[_]):
  def query = B.query

case class Person(name: String, age: Int) extends RowData(Person)

object Person extends Model[Person]

Person("onur", 38).query

However, this is not an ideal solution either, because B is not enforced to be the companion object you pass for the RowData trait. In Scala, we commonly use Context Bound to enforce this, like this:
trait Model[A]:
  def query = "model has this good stuff I want to use in RowData"

trait RowData[B : Model]:
  def query = summon[Model[B]].query

case class Person(name: String, age: Int) extends RowData[Person]

given Person: Model[Person] with {} // Implement custom query method here

Person("onur", 38).query


text:
Q: Use fill_value outside boundaries with scipy.interpolate.griddata and method=nearest Function scipy.interpolate.griddata allows to specify the keyword fill_value, for which the doc states:

Value used to fill in for requested points outside of the convex hull of
  the input points. If not provided, then the default is nan.
  This option has no effect for the 'nearest' method.

However, I need to specify a fill_value to use outside of the boundaries when
using method='nearest' with 2D data. How can this be achieved?

A: This can be relatively easily achieved with the following work-around:

*

*run with method='nearest'

*run again with method='linear'; here the outside region is filled with np.nan.

*wherever there is a NaN in the result of 2. assign your desired fill_value to the result of 1.

Code:
import numpy as np
from scipy.interpolate import griddata

def func(x, y):
    return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2

grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]

points = np.random.rand(100, 2)
values = func(points[:,0], points[:,1])

grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest')
grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear')

fill_value = 123  # Whatever you like
grid_z0[np.isnan(grid_z1)] = fill_value

A less ad-hoc approach would be to compute the convex hull explicitly and use it to assign the fill value. This would require more effort but might run faster.


text: Q: Из файла .py сделан .exe Антивирус ругается После создания файла .exe ругается антивирус на троян. Использовал pyinstaller. Скомпилировал код, в котором нет tkinter и антивирус не ругается уже. Подскажите, почему так.


text: Q: Is there any way to copy the value of all the parameters of a method in debug mode in Visual Studio? Yesterday, my boss did it again... He opened the code, changed the type of one of the parameters, saved the file, compiled (no errors) and committed the changes. After that, asked me to try his changes and tell him if I find any errors. Of course I found them and now I have to tell him exactly what to change and with what values to call the method so he can change it comfortably. The problem is that the function has many parameters. Is there any way to copy all those values automatically?


text:
Q: How do I submit the iWatch app to the App Store? I want to submit iWatch app on appstore.
But I can't find the option for iwatch.
Can you please help me for this?
Thank you.

A:

*

*When you create a new Watch App project (not an iOS App with Watch App), note that it creates a Watch App target, a Watch Extension target, AND an almost empty iOS App target (no code, storyboards, xcassets, but under build phases it is dependent on the Watch App and embeds the Watch app).

*On App Store Connect, you create a new iOS app project for your independent Watch app, but only fill in the data related to the Watch part of the project.

*Archive and upload your project as you normally would a standard iOS project.

Voila! (And yes, that is not intuitive).
find more here and here

A: alright, it's possible to submit as a watch version on existing iOS app.

A: Yes, it's possible to submit on the existing iOS app.
But you need to create the watch app bundle ID from iOS app ID.


text:
Q: dialog-ready event does not fire when dialog opens in AEM 6.1? My most basic problem is to load a select field in touch UI dialog with dynamic options.
These options are coming from a external URL via webservices so please don't mention datasources here.
In classic UI is easy with optionsProvider.
In touch UI I am trying to write a script that fetches the data from the external webservice via AJAX ON DIALOG load and set these options in the select field.
My dialog.ready event is just not getting called.
There is another annoying issue I see with touch UI is that I can't see the edit option when I hover over a component. It shows just "delete" and "group" option. And this happens for some components only. I have to double tap to to open the dialog.
Please see image

Also see my code below to for dialog ready.
(function ($, $document, $window) {
"use strict";
console.log('Namaste'); // works

$document.on("dialog-ready", function() {

    console.log('Hello'); // Does not work/fire when dialog opens

     $window.adaptTo("foundation-ui").alert("Open", "Dialog now open, event [dialog-ready]");
    if(comm) {
          var serviceUrl = xyz.config.baseUrl + '/public/movies';
          $.ajax({
                url: serviceUrl,
                cache:false,
                success: function(result){
                    console.log('Result'+JSON.stringify(result));
            }
          });
    }

});

$document.on("dialog-closed", function() {
    $(window).adaptTo("foundation-ui").alert("Close", "Dialog closed, event [dialog-closed]");
});

})($, $(document), $(window));

A: To invoke your method on dialog open , you should set categories of your client lib as "cq.authoring.dialog"
It's a global category that's applies on all touch UI dialog.


text:
Q: Xcode 11 apple distribution accepted but impossible to build with flutter I renewed my 1 year apple development and renewed my certificate
> Xcode 11 supports the new Apple Development and Apple Distribution certificate types. These certificates support building, running, and
> distributing apps on any Apple platform. Preexisting iOS and macOS
> development and distribution certificates continue to work, however,
> new certificates you create in Xcode 11 use the new types. Previous
> versions of Xcode don't support these certificates. (45527608)

Due to this note for Xcode11, I test to create an Apple distribution instead of iOS distribution like before
So, I create this and select the good provisioning profileee in Xcode.
At this step, all is good.
but now when I try to run app
I have
No Provisioning Profile was found for your project's Bundle Identifier or your
device. You can create a new Provisioning Profile for your project in Xcode for
your team by:
  1- Open the Flutter project's Xcode target with
       open ios/Runner.xcworkspace
  2- Select the 'Runner' project in the navigator then the 'Runner' target
     in the project settings
  3- Make sure a 'Development Team' is selected.
     - For Xcode 10, look under General > Signing > Team.
     - For Xcode 11 and newer, look under Signing & Capabilities > Team.
     You may need to:
         - Log in with your Apple ID in Xcode first
         - Ensure you have a valid unique Bundle ID
         - Register your device with your Apple Developer Account
         - Let Xcode automatically provision a profile for your app
  4- Build or run your project again

It's also possible that a previously installed app with the same Bundle
Identifier was signed with a different certificate.

But my provisioning profile is well accepted in Xcode in signing & capabilities, team is well selected, I'm well connected with my Apple ID
when it's write :
"It's also possible that a previously installed app with the same Bundle
Identifier was signed with a different certificate."

I think it's the case, because I renew my 1 year account, and renew my certificate. I don't understand what is the problem
I well selected my physical device
I try flutter clean, xcode build clean
If I use automatically manage signing, Xcode select a iOS developpement profile type, so I can build and run my app, but If I select manually my Apple distribution it doesn't work

A: Close Xcode, then clean derived data:
rm -rf ~/Library/Developer/Xcode/DerivedData/*

Open Xcode Clean and Rebuild

A: Based on:

It's also possible that a previously installed app with the same Bundle
Identifier was signed with a different certificate.

If it's a different certificate then you need to trust that new developer certificate on your physical device.
See steps from here:
If you want to turn on SSL trust for that certificate, go to Settings > General > About > Certificate Trust Settings. Under "Enable full trust for root certificates," turn on trust for the certificate.


text:
Q: java - to set multiple value in a map I got a scenario like the following:
Map1 - Map<String, Map<String,List<Vo>>>
Map2 - Map<String, Set<String>

Is it possible to set the same have a same key reference for the above 2 Maps like the following?
Map<String, Collection<?>  mapCommon=new HashMap<String, Collection<?>();

Can anyone please give some idea about how to set this?
edit: yes same reference

A: What you want to do is impossible because Set and Map do not share any common implementation or super class except Object. You can see it in the official documentation :

*

*Javadoc Map

*Javadoc Set
You could do a Map<String, Object> but I strongly not advise you to doing that. How could you know if your object is a map or a set ? It is not possible to do that properly.
In my opinion, the best solution you have is to create a new class to wrap your two collections :
public class YourWrapper {
    Map<String, Map<String,List<Vo>>> a;
    Map<String, Set<String> b;
    // getter setter etc...
}

After that you can create your collection :
Map<String, YourWrapper> myMap = new HashMap<String, YourWrapper>();

A: If I understand you would want to have the same key to be used for various different types of values.
Why not have a new Class itself that would consists of maps, sets, whose instances could be used as values
class MyClass {

     private Map<String, List<Vo>> theMap;
     private Set<String> theSet;
     ...
     ...   // have its own getters and setters

}

And then you can have your top level map defined like this
Map<String, MyClass> myMainMap = new HashMap<String, MyClass>();

Or as an alternative have a tuple
You can check this link further to see how that is done.

A: You are touching here two interesting elements.
Firstly - Map does not belong to Collection. List and Set do belong, but Map is a different one even though it shares some commonalities with Lists and Sets.
Secondly - Mixing the types into one commonMap the way you are trying is doable but it should be avoided as it is generally not considered as best practice. The problem we are dealing with is caused by type erasure. Once compiler compiles the code - it does not pass any information about generic types hold by Map or Set. Effectively your Map<String, List<Vo>> becomes raw-type Map<?> in the compiled code. The problem with that is casting back original values. The compiler will not allow you to check the instance if it is Map<String, List<Vo>> or Set<String>.
The fllowing piece of code will fail:
public static void processElement(Object commonMapObjectEitherMapOrSet) {
    if (commonMapObjectEitherMapOrSet instanceof Map<String, List<Vo>>) {
        //...
    }
}

Error: Cannot perform instanceof check against parameterized type
  Map>. Use the form Map instead since further
  generic type information will be erased at runtime

The possible workaround would be to forget about generics and check if the instance is a raw-type Set or Map. The code below shows how check if Object is either Map or Set.
public static void processElement(Object commonMapObjectEitherMapOrSet) {
    if (commonMapObjectEitherMapOrSet instanceof Map) {
        System.out.println("Got map; but types held in the map are not known due to type-erasure");

        // This is where things will get messy as you will get warnings:
        Map<String, List<Vo>> map = (Map<String, List<Vo>>) commonMapObjectEitherMapOrSet;
        // ...
    }

    if (commonMapObjectEitherMapOrSet instanceof Set) {
        System.out.println("Got set; but types held in the set are not known due to type-erasure");

        // This is where things will get messy as you will get warnings:
        Set<String> set = (Set<String>) commonMapObjectEitherMapOrSet;
        // ...

    }
}

The problem with the above is casting the value from your commonMap back to your desired types ie. Map<String, List<Vo>> and Set<String>. The compiler won't be able to check if the casting is correct and will issue a warning. You can technically Suppress the warning with (@SuppressWarnings("unchecked") annotation ) but this may not be the best thing to do.
At this stage - it makes sense to consider whether or not to create your own specialized class to manage different types.
Back to your original question - to answer it I am posting the code that maps things to the common map:
package stackoverflow;

import java.util.*;

class Vo {}

public class MultipleRefs {
    public static void main(String[] args) {

        Map<String, List<Vo>> mapVo = new HashMap<>();
        Set<String> set = new HashSet<>();

        Map<String, Object> commonMap = new HashMap<>();

        //commonMap.put("a", Map)
        commonMap.put("mapVoOne", mapVo);
        commonMap.put("setOne", set);

        commonMap.forEach((key, value) -> processElement(value));
    }

    public static void processElement(Object commonMapObject) {
        if (commonMapObject instanceof Map) {
            System.out.println("Got map; but types held in the map are not known due to type-erasure");

            // This is where things will get messy:
            Map<String, List<Vo>> map = (Map<String, List<Vo>>) commonMapObject;

            System.out.println("  processElement prints map: " + map);
        }

        if (commonMapObject instanceof Set) {
            System.out.println("Got set; but types held in the set are not known due to type-erasure");

            // This is where things will get messy:
            Set<String> set = (Set<String>) commonMapObject;

            System.out.println("  processElement prints set: " + set);
        }
    }
}


text:
Q: Binary characters in front of sent data in Godot Engine I want to connect to Twitch server. But Godot adds binary characters in front of my data as you can see in the pictures. This happens everytime no matter the data type. Why is this happenning and how can I prevent this happening?

code

A: Perhaps an issue with a BOM from UTF8-encoding. A BOM (Byte Order Mark) may be prepended to UTF8 strings in some cases but is not necessary and usually not recommended. Check:
What's the difference between UTF-8 and UTF-8 without BOM?
Try removing the first two bytes in your stream data and see if that helps.

A: Some functions like var2bytes() prefix its output with some type data so it can build it back to an engine type like with bytes2var().
You will have to be aware of these when transmitting data.


text:
Q: A generalization of Witt's theorem for quaternion algebra isomorphism Let $Q$ be a quaternion $k$-algebra (namely, a dimension 4 $k$-central simple algebra).
Then it is possible to (canonically) attach a smooth projective conic $C_Q\subseteq \mathbf{P}_k^2$ to $Q$: if $\mathrm{char}\,k \neq 2$, then $Q\simeq \langle x,y : x^2 = a, y^2 = b, xy+yx=0\rangle$ for certain $a\in k,b\in k^\times$ so it suffices to set $C_Q\simeq\{ aX_0^2+bX_1^2 - X_2^2 =0\}\subseteq \mathbb{P}^2_k$. If instead $\mathrm{char}\,k =2$ one has $Q=\langle x,y : x^2+x=a,y^2=b, xy+yx=yy\rangle$ for some $a\in k,b\in k^\times$ and assign $C_Q=\{aX_0^2 +bX_1^2 +X_2^2 + X_0X_2 =0\}$.
There exists an interesting relationship between splitting of quaternion algberas (i.e. $Q\simeq M(2,k)$) and existence of $k$-rational points in the associated conic $C_Q$. This works for every characteristic too.
But there is an even more elegant result, attributed to Witt, which relates isomorphism of two quaternion algebras with the birational equivalence of their associated conics. More precisely:
Theorem. Let $Q,R$ be two quaternion $k$-algebras. Then $Q\simeq R$ if and only if $C_Q$ and $C_R$ are birational (namely $k(C_Q)\simeq k(C_R)$).
Such result can be found, for instance, in the great book by Gille and Szamuely, Central simple algebras and Galois cohomology where, much to my dismay, almost all the results are shown for a field of characteristic $\neq 2$.
In particular, the above Theorem is proved using the definitions for quaternion algebras and conics in characteristic not 2.
I have searched in some more specific book (like Vigneras' lectures and Voight's draft) but this result does not seem to be covered. In the Vigneras' book there is a chapter called "Geometry" in which something similar is done, but the whole chapter works in the non-dyadic case.
I was wondering if such result held for a field of characteristic 2 and, if yes, is there a reference for this?

A: Norms of quaternion algebras are particular cases of n-fold Pfister forms for n=2 (in any characteristic), and the result holds true for any Pfister forms. See, for example, Elman, Karpenko, Merkurjev "The algebraic and geometric theory of quadratic forms": https://sites.ualberta.ca/~karpenko/publ/Kniga.pdf, Corollary 23.5.


text:
Q: Error creating verifyTokenAdmin middleware I'm trying to create two middlewares, an authentication middleware and a middleware that checks if the user in question has "isAdmin" true inside its database.
The authentication middleware works perfectly, but to make the admin middleware work, I tried to put req.users = data; inside, but it returns me the error:
Property 'users' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.ts(2339)

auth middleware:
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

interface TokenPayload {
  id: string;
  iat: number;
  exp: number;
}

export default async function authMiddleware(
  req: Request, res: Response, next: NextFunction
  ) {
    const { authorization }  = req.headers;

    if (!authorization) {
      return res.status(401).json('Invalid Authorization');
    };

    const token = authorization.replace('Bearer', ' ').trim();

    try {
      const secret = process.env.JWT_SECRET as string;
      const data = jwt.verify(token, secret);

      req.users = data;

      const { id } = data as TokenPayload;

      req.userId = id;

      return next();
    } catch (err) {
      return res.status(401).json(err);
    }
}

In auth middleware admin, in users it returns the same error
Property 'users' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.ts(2339)

auth middleware admin
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import authMiddleware from './AuthMiddlewares';

export default async function authAdminMiddleware(
    req: Request, res: Response, next: NextFunction,
) {
    authMiddleware(req, res, () => {
        if (req.users.isAdmin) {
            next();
        } else {
            res.status(403).json("You are not alowed to do that!");
        }
    })
}

A: You can use declaration merging to declare the additional property users in your req object:
declare global {
  namespace Express {
    interface Request {
      users: any
    }
  }
}

(See also here.)


text:
Q: local variable referenced before assignment discord bot i was creating my own discord bot and for some reason i allways sent me output when i ran my command
local variable referenced 'thing' before assignment
and in these lines of code it told me that 'thing' is not defined
options = starter_thing
    if thing in db.keys():
      options = options + db["thing"]

and
def update_thing(thing_message):
    if thing in db.keys():
        thing = db["thing"]
        thing.append(thing_message)
        db["thing"] = thing
    else:
        db["thing"] = [thing_message

A: the key is a string:
if "thing" in db.keys():
    ...

or assign a value to the variable thing first:
thing = "thing"
if thing in db.keys():
    ...

A: From what I can tell in thhose code snippets, the 'thing' variable does not exist anywhere, so Python doesn't know what you mean when you use 'thing'
Try assigning something to 'thing' like
thing = "thingToCheck"


text:
Q: How to export a Lab Manager machine to ESX? I'm wondering if I can export my Lab Manager templates directly into a cheaper ESX host. Easy enough to import from other ESX hosts. I imagine validating machines in LM and then moving the nicely configured templates off to a plain ESX host. That would save Lab Manager resources for things that really need to be there.
Possible? Seems like it ought to be - Lab Manager just runs on ESX. Anyone tried it? How?
Using LM 3, ESX 3.5. (I'm also digging around LM forums, will let you know what we find out)

A: Lab Manager templates and VM instances from within Lab Manager (as long they're not currently running) can be exported as a series of 2GB (or less) vmdk files.  Those files can then be used by any VMware product (ESX, VMware Workstation, Fusion, etc).  Depending on the size of the template/VM, it can take an hour or more to export to a network share so don't freak out if you see it spinning for a bit.

A: If you go to the templates page of LM, you can mouse over the template you want to export to bring up a menu.  Choose export, point it to an SMB share and let it go.


text:
Q: Error while opening excel pivot table report from sharepoint 2010 I made a pivot table report using excel 2010 that retrieving data from shareportint 2010 list, the report is working fine in excel but when I uploaded it to document library and put it in web part to view from share point it showing me this error :
Unable to refresh data for a data connection in the workbook.
Try again or contact your system administrator. The following connections failed to refresh:

owssvr[1]

what should I do to resolve this error?
Thanks.

A: You should refer to this artice in MSDN when working with external data connections within an Excel workbook. Before publishing the workbook into SharePoint you must make sure the connection belongs among the set of (administrator-defined) trusted connections.

A: I got a similar error when trying to refresh data in an Excel Web Part using SharePoint 2010.
Here is the screenshot of my error:
SharePoint Error
My problem was that I was setting the source of the Excel Pivot tables directly to the SharePoint list. In order to get it to work I had to:

*

*Go to the SharePoint list to be used as a data source

*Select the "Export to Excel" button to obtain the .iqy file

*Save this file then open it in Excel which will open the list in Excel

*Any pivot tables created must then use this table as the source, not the connection that is found under the "existing connections" button in Excel


text:
Q: Show tooltip on variables with type in Intellij with Scala Is there any way so that IntelliJ shows a tooltip with the type of a variable when you are programming with Scala?
I know that Eclipse has this feature. I have been looking for in the settings and I didn't find it.

A: File / Settings / Languages & Frameworks / Scala / Editor / Show type info on mouse hover after, ms ....

A: When you have your cursor on variable, use Alt + =.
By cursor I mean the caret, not mouse pointer.

A: In MacOS IntelliJ 16.x, I observed that the compiler warning/error tooltip takes precedences to the type info tooltip. To force the type tooltip to show, use View > Type Info menu option or ctrl + shift + p (the default keymap) when the cursor is on the element you want to inspect.


text:
Q: Highcharts (Highstock) how to catch errors? Is there any way to catch the errors thrown by Highcharts? Especially the Invalid negative value error which is quite common in my case whenever my app switches to a different dataset on the server.
I'm looking forward to something like:
try {
  // some code that may or may not work
} catch (err) {
  // print out error or come up with a workaround
}

Thanks guys!


text:
Q: Using serial ports, I get an error: Attempted to read or write protected memory I know this question has been asked before but none of the existing answers solved my problem. I have a WinForms Application which communicates with a number of devices, takes data and writes them to a file.
It opens GPIB and Serial port communications and at the end closes all of them. I use this.Dispose() and this.Close() to make sure that memory is released (at least I think the memory is released). However, next time I run it, after several hours I get the error:

Attempted to read or write protected memory. This is often an
  indication that other memory is corrupt.

If I run it again the crash time becomes shorter and shorter as if something is accumulating in memory. I copy parts of my code that seem to be related to this issue. Am I making any mistake in memory consumption?
What I tried:
Added this.Dispose() and the Close() functions to close the ports (initially I forgot to add them). But still did not help. I also tried to restart my computer before each run, yet it did not help either.
public partial class Form1 : Form
{
    //GPIB and serial ports
    SerialPort Arduino;
    SerialPort serialPort1 = new SerialPort();
    private Device DMM1, DMM2, DMM3;
    private Address DMM1_Address, DMM2_Address, DMM3_Address;
    private Address[] Address_List = new Address[3];
    private AddressCollection GPIB_Adds;
    Board GPIB = new Board(0);
    //Timers
    System.Windows.Forms.Timer fire_time = new System.Windows.Forms.Timer();
    System.Windows.Forms.Timer measurement_time = new System.Windows.Forms.Timer();
    System.Windows.Forms.Timer preparation_delay = new System.Windows.Forms.Timer();
    System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();

    public Form1()
    {
        // ...some code
    }

    private void InitializePorts()
    {
        // ...ports are initialized here
    }

    private void button1_Click(object sender, EventArgs e)
    {
       preparation_delay.Interval = 1000;
       preparation_delay.Tick += new EventHandler(start);
       preparation_delay.Start();

       measurement_time.Interval = 60000;
       measurement_time.Tick += new EventHandler(stop);

       fire_time.Interval = Convert.ToInt32(textBox6.Text) * 1000;
       fire_time.Tick += new EventHandler(FIRE);
        }
    }

    private void start(object obj, EventArgs e)
    {
        stopwatch.Start();
        measurement_time.Start();
        fire_time.Start();
        preparation_delay.Stop();
        preparation_delay.Tick -= new EventHandler(start);
        //Here I try to annihilate the event handler in fear of staying in memory
    }

    private void FIRE(object obj, EventArgs e)
    {
        string p = //Reads data from device
        string[] k = //Reads data from device
        string t = //Reads data from device
        Write_to_Text(t, p, k);
    }

    private void stop(object obj, EventArgs e)
    {
        fire_time.Stop();
        measurement_time.Stop();
        progress.Stop();
    }

    private void Write_to_Text(string time_date, string PRC_Reading, string[] DMM_Reading)
    {
        string string_to_save =  ...some string

        try
        {
            System.IO.File.AppendAllText(@filename, string_to_save);
        }
        catch (Exception ex)
        {
            serialPort1.Close();
            Arduino.Close();
            GPIB.Dispose();

            measurement_time.Stop();
            fire_time.Stop();
            this.Dispose();
            this.Close();
        }
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        serialPort1.Close();
        Arduino.Close();
        GPIB.Dispose();

        this.Dispose();
        this.Close();
    }
}

A: For native NET objects in principle you don't need to call Dispose explicitly (the finalizer will do that), but if you have some external objects accessing external resources (GPIB?) you have to be careful. What I see is that if there is an exception in Write_To_Text you will call GPIB.Dispose twice, and also that it can be called before the timers effectively stop. Make sure that there will be no call to any Gpib function after you dispose it (for example set a flag that will be checked before calling Gpib functions).

A: Whenever you find yourself manually calling the Dispose() function, that's a bit of a code smell... an indication something is not right.
Instead, learn to use the using keyword to create blocks that wrap disposable objects. This will help you create meaningful scope boundaries for the those objects. It also helps avoid mistakes, where Close() and Dispose() calls were not properly wrapped with a finally block.
In this case, the problem likely involves these code snippets:
this.Dispose();
this.Close();

Never call Dispose() from inside the object itself you want to dispose (except as part of implementing the core IDisposable pattern). Instead, it's up to the outside code to tell your object when it's finished. Here, you attempt to Dispose() a form before the Form_Closing method is raised (see Write_To_Text()), meaning the form is invalid when Form_Closing() itself tries to execute.


text:
Q: $\frac{1}{n}=O(\frac{1}{\ln n})$ or $\frac{1}{n}=o(\frac{1}{\ln n})$? $\frac{1}{n}=O(\frac{1}{\ln n})$ or $\frac{1}{n}=o(\frac{1}{\ln n})$?
I know that $n\geq\ln n, (n> 0)$, with which $\frac{1}{n}\leq \frac{1}{\ln n}$ and so $\frac{1}{n}=O(\frac{1}{\ln n})$.
To know if $\frac{1}{n}=o(\frac{1}{\ln n})$, I need to know if $\lim_{n\to \infty}\frac{\ln n}{n}=0$, but how can I prove that this limit does not exist or does exist? Thank you very much.

A: You have a typical $\frac{\infty}{\infty}$ indeterminacy. Consider the continuous version of your ratio where you replace $n$ by $x\in\mathrm{R}$ and use the L'Hospital rule to conclude that $\lim_{x\rightarrow\infty}\frac{\ln x}{x}=0$.

A: Without L'Hopital or anything fancy, only elementary manipulations of what you know already.
If you know $x\geq \ln x$ for all $x\geq 1$, then you know
$$
\sqrt{x} \geq \ln \sqrt{x}
$$
for all $x\geq 1$ as well. Therefore, you know
$$
\sqrt{x} \geq \frac{1}{2}\ln x
$$
for all $x\geq 1$, and rearranging you get
$$
\frac{\ln x}{\sqrt{x}} \leq 2\,.
$$
It follows that, for $x\geq 1$,
$$
0\leq \frac{\ln x}{x} \leq \frac{2}{\sqrt{x}}
$$
and this is in particular true for integers:
$$
0\leq \frac{\ln n}{n} \leq  \frac{2}{\sqrt{n}} \xrightarrow[n\to\infty]{} 0
$$


text:
Q: Issue in consuming a asmx web method I am creating a simple asmx web service and trying to consume them. Below is the asmx web service
public class AddTwoNumbers : System.Web.Services.WebService
{

    [WebMethod]
    public int GetSum(int a, int b)
    {
        return  a + b;
    }
}

This is the Windows Console application where I am consuming the service that was created
 namespace TestASMXService
 {
 class Program
 {
    static void Main(string[] args)
    {
        AddingNumber.AddTwoNumbers add = new AddingNumber.AddTwoNumbers();
        Console.Write("First Number:");
        int firstNum = Convert.ToInt32(Console.ReadLine());
        Console.Write("Second Number:");
        int secNum = Convert.ToInt32(Console.ReadLine());
        Console.Write ("The Sum is:",add.GetSum(firstNum, secNum));
        Console.ReadLine();
    }
}

It receives the user inputs and does not return any result or throws any error

Can anyone please tell me what I am missing here.

A: You are trying to pass an argument in the Console.Write, but do not have a placeholder for it in the format string. The method GetSum will therefore not be called.
Change it to:
Console.Write("The Sum is: {0}", add.GetSum(firstNum, secNum));


text:
Q: Angular custom service call fails I have been following a tutorial online on PluralSight for working with Angular, however it appears that some of the information is outdated.
I have reached a section on creating custom services and have followed the tutorial to the letter however my custom service will not work correctly.
It seems to fail when I try to call my github service, it looks like the promise fails to return correctly to the script.js .then() handler for github.getUser()
The plunk for it is here http://plnkr.co/edit/8vy6ZMpUJBfEOQ3qFoKk
Can someone please tell me what I am missing here?

A: If you want just to get it to work, here's how to fix it:
Your second option is to add a return to your $http on the service, like this:
var getUser = function(username) {
  return $http.get("https://api.github.com/users/" + username)
    .then(function(response) {
      return response.data;
    });
};

Note that you only forgot the first "return" before the $http. The rest was working well
A better way to solve that would be to not resolve your promise inside the service. That way you get a thin service and can manage your data as you like within your controller.
So I changed your getUser to this:
var getUser = function(username) {
  return $http.get("https://api.github.com/users/" + username);
};

This way it returns the entire promise from $http. Since I removed your "wrapper" I need to modify your onUserComplete () too:
var onUserComplete = function(result) {
  $scope.user = result.data;
  github.getRepos($scope.user).then(onRepos, onError);
};

Here is the working plunker: http://plnkr.co/edit/8abkaU08fCzFreA5APz1?p=info


text:
Q: not able to modify this pointer why I am not able to modify this pointer? getting compilation error "error: lvalue required as left operand of assignment".
Following is the program
#include<iostream>
using namespace std;

class Test
{
private:
  int x;
public:
  Test(int x = 0) { this->x = x; }
  void change(Test *t) { this = t; }
  void print() { cout << "x = " << x << endl; }
};

int main()
{
  Test obj(5);
  Test *ptr = new Test (10);
  obj.change(ptr);
  obj.print();
  return 0;
}

A: You can't assign to this, you should think of it as conceptually constant pointer Test *const this.
What you actually need to do in change() is just copy the contents of t:
void change(Test *t) {this->x = t->x;}

If you want to be a good C++ citizen you could also make t constant:
void change(const Test *t) {this->x = t->x;}


text:
Q: Filter multidimensional array by lowest price I'm working with an array that I'd like to filter so it only contains the lowest prices per key. So 50 would only have one unit, same with 100, and that unit would be the lowest price.
Here's an example of what I'm working with:
$units = [
    50 => [
        41788 => ['StdRate' => 231.0000, 'UnitName' => "NN23"],
        46238 => ['StdRate' => 303.0000, 'UnitName' => "1038"],
        46207 => ['StdRate' => 303.0000, 'UnitName' => "1007"]
    ],
    100 => [
        41570 => ['StdRate' => 299.0000, 'UnitName' => "HH18"],
        46214 => ['StdRate' => 388.0000, 'UnitName' => "1014"]
    ]
];

I wanted to avoid doing this with a complicated foreach loop, so I thought an array_filter would be nice, but having a hard time wrapping my head around it. Or would a foreach be best?
$filtered = array_filter($units, function($a) {

});

Expected Output:
[
    50 => [
        41788 => ['StdRate' => 231.0000, 'UnitName' => "NN23"]
    ],
    100 => [
        41570 => ['StdRate' => 299.0000, 'UnitName' => "HH18"]
    ]
];

A: Here is a function that will go through your multi-dimensional array and grab the lowest units.  It will retain the key of the big array (50, 100) and the key of the unit it grabbed (41788, 41570).  It will not retain multiple values of the same low rate.  In those cases it will return the first of the lowest value it found.  Might not be exactly what you want, but it should be a good start and you can always modify it later.  It uses a nested foreach to get its work done.
Hope this help you out!
function findLows($big) {
    $lowUnits = array();
    foreach($big as $id => $array) {
        $low = false;
        $prev = false;
        foreach($array as $k => $a) {
            if(!$low) {
                $low = $k;
                $prev = $a['StdRate'];
            } else {
                if($a['StdRate'] < $prev) {
                    $prev = $a['StdRate'];
                    $low = $k;
                }
            }
        }
        $lowUnits[$id] = array( $low => $array[$low]);
    }
    return $lowUnits;
}

$bigArray = array();
$bigArray[50][41788] = array('StdRate' => 231.0000, 'UnitName' => "NN23");
$bigArray[50][46238] = array('StdRate' => 303.0000, 'UnitName' => "1038");
$bigArray[50][46207] = array('StdRate' => 303.0000, 'UnitName' => "1007");
$bigArray[100][41570] = array('StdRate' => 299.0000, 'UnitName' => "HH18");
$bigArray[100][46214] = array('StdRate' => 388.0000, 'UnitName' => "1014");

$filtered = findLows($bigArray);

var_dump($filtered);

Will produce:
array(2) {
  [50]=>
  array(1) {
    [41788]=>
    array(2) {
      ["StdRate"]=>
      float(231)
      ["UnitName"]=>
      string(4) "NN23"
    }
  }
  [100]=>
  array(1) {
    [41570]=>
    array(2) {
      ["StdRate"]=>
      float(299)
      ["UnitName"]=>
      string(4) "HH18"
    }
  }
}

A: For an array with 1 fewer levels of depth, you could have directly iterated the data with array_filter().  Because you want to filter each set of data relating to first level entries, you just need to nest the array_filter() inside of array_map() (for a functional-style script).
I am going to isolate the StdRate values in each set and determine the lowest value by calling min() on the temporary array generated by array_column().
To pass the $min value into the filter's scope, use use().
This snippet will potentially return multiple deep subarrays for a respective set of data IF there is a tie among the lowest values in the set.
Code: (Demo)
$units = [
    50 => [
        41788 => ['StdRate' => 231.0000, 'UnitName' => "NN23"],
        46238 => ['StdRate' => 303.0000, 'UnitName' => "1038"],
        46207 => ['StdRate' => 303.0000, 'UnitName' => "1007"]
    ],
    100 => [
        41570 => ['StdRate' => 299.0000, 'UnitName' => "HH18"],
        46214 => ['StdRate' => 388.0000, 'UnitName' => "1014"]
    ]
];

var_export(
    array_map(
        function($unit) {
            $min = min(array_column($unit, 'StdRate'));
            return array_filter(
                $unit,
                function($row) use ($min) {
                    return $row['StdRate'] == $min;
                }
            );
        },
        $units
    )
);

Output:
array (
  50 =>
  array (
    41788 =>
    array (
      'StdRate' => 231.0,
      'UnitName' => 'NN23',
    ),
  ),
  100 =>
  array (
    41570 =>
    array (
      'StdRate' => 299.0,
      'UnitName' => 'HH18',
    ),
  ),
)


text:
Q: How do I get a Jenkins Agent to pull its Docker image from Artifactory? I have a docker agent setup under the "Configure Clouds" page on Jenkins. It is successfully pulling bibinwilson/jenkins-slave:latest and I've done some successful test runs, but I am hitting rate limiting issues so I would like to pull from Artifactory or anywhere other than docker-hub. I have already pushed the image to Artifactory from my server, however I do not know how to configure the Jenkins Agent to pull from Artifactory.
Is this possibly something that would be configured under configureClouds>docker_agent_templates>container_settings>Docker_Command on Jenkins? Or maybe I am supposed to change some settings on the docker server? Please help.


text:
Q: mssql 2008 - using variables as column names I have searched a lot to use variable names as column names, however I could not find anything. I have a table which has nameMaster column and xVariable,yVariable,zVariable underneath. I know I can use:
case nameMaster when 'xVariable' then total else 0 end AS xVariable
case nameMaster when 'yVariable' then total else 0 end AS yVariable
case nameMaster when 'zVariable' then total else 0 end AS zVariable

However I like to do this in a loop, not manually.
My table is like this:
nameMaster | total
---------------------
xVariable  | 10.000
yVariable  | 20.000
zVariable  | 30.000

What I want to display is like this:
xVariable | yVariable | zVariable
---------------------------------
10.000      20.000       30.000

Thanks in advance..

A: Well the thing that you want to achieve is called PIVOT table and it will transform your columns in to rows based on your columns selections.
You can refer this article to see how the pivot happens.


text:
Q: Email not popping up in Sharekit Inside the Sharekit 's SHK file, there's a function called ShowViewController which bring the Mailcontroller up.
In SHKMail
[[SHK currentHelper] showViewController:mailController];
In the SHK file
// Show the nav email controller
[topViewController presentModalViewController:vc animated:YES];

vc is the viewcontroller of the Mail.
I checked both the topviewController and vc are valid, however, nothing show up when the email button of the sharekit is clicked.

A: I tried like this and it was working for me and hope it should work for you as well
-(UIViewController*)getRootViewController{

    return _APPDELEGATE.navigationController;
}

[[SHK currentHelper] setRootViewController:[self getRootViewController]];

[actionSheet showFromToolbar:_APPDELEGATE.navigationController.toolbar];

I do not know why my above code is not working for you.
Okay try this code, should work
SHKItem *item = [SHKItem URL:someNSURL title:@"a title"];

//hack: force SHK to know the root view controller
[[SHK currentHelper] setRootViewController:self];

// Share the item
[SHKMail shareItem:item];

[item release];


text:
Q: Error term of the prime number theorem in arithmetic progressions It is known that if $(a, q)$ and $q\le (\ln x)^N$, then the following is true
$$\sum_{k\le x, k\equiv a\pmod{q}}\Lambda(k) = \frac{x}{\phi(q)} + O(x\exp(-C\sqrt{\ln x}))$$
where $C$ depends only on $N$. This error term appears because of the possibility of a counterexample to the Generalised Riemann Hypothesis. What would the error term be if the GRH was true?

A: Corollary 13.8 of Montgomery and Vaughn's Multiplicative Number Theory states that under the Generalized Riemann Hypothesis for the Dirichlet $L$ functions of characters $\chi$ modulo $q$, we have that $$\psi(x;q,a)=\sum_{\begin{array}{c}
n\leq x\\
n\equiv a\ (q)
\end{array}}\Lambda(n)=\frac{x}{\phi(q)}+O\left(x^{1/2}\log^{2}x\right).$$ In particular, if GRH is true, then we have the asymptotic $\psi(x;q,a)\sim\frac{x}{\phi(q)}$ for all $q\leq x^{1/2}/\log^3(x)$.


text:
Q: I'm getting a SyntaxError: (unicode error) 'unicodeescape' codec Hi I'm making a simple code that is due soon. I'm using Wing IDE 4.1.3-1 and I keep getting this message when I run my program code
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (, line 4)
Here is my program:
#=====================================================================
# Program:      Calculating Sales
# Programmer:   Viet-Anh Tran
# Date:         2-14-2012
#               July 1, 2011 - Revised for Python 3
# Abstract:     This program processes highest sales, lowest sales,
#               and averages the total numnber of sales. Each
#               salesperson will be asked enter the amount they sold
#               and the price of each sale.
#=====================================================================

def main():
    #create variable to control loop
    keep_going = 'y'
    #process each salperson's sales
    while keep_going == 'y' or keep_going == 'Y':
        #use a function to process sales
        show_sales()
        keep_going = input("would you like to calculate another salesperson's" +
        "sales? (enter y or Y as yes to continue) ")
#define show_sales
def show_sales():
    #ask for name of salesperson
    name = input("What is the salesperson's name? ")
    #ask for first sales amount
    print('Enter', name, "'s first sale amount: ")
    first_sale = float(input())
    #when assigning a value for first sale make sure its bewtween 1-25000
    while first_sale < 1 or first_sale > 25000:
        #prompt error message if it does not meet within range
        print('ERROR: First sale amount must fall in the range of $1-$25,000.')
        #ask user again for CORRECT amount
        print('Please enter', name, "'s correct first sale amount:")
        first_sale = float(input())
    #assign all total highest and lowest sales to first sale
    total_sale = first_sale
    highest_sale = first_sale
    lowest_sale = first_sale
    #ask for the total number of sales
    print('Are there any more sales? If so, type in the total number of sales:')
    number_sales = int(input())
    #create a loop
    for sale in range(2, number_sales + 1):
        print('What is', name, "'s next sales amount?")
        sales_amount = float(input())
        #again make sure that it is within range and ask the correct amount again
        while sales_amount < 1 or first_sale > 25000:
            print('ERROR: Sale amount must fall in the range of $1-$25,000.')
        print('Please enter', name, "'s correct sale amount:")
        sales_amount = float(input())
        #accumulate the total sales
        total_sales += sales_amount
        #this assigns the lowest and highest value to the correct variable
        if sales_amount > highest_sale:
            highest_sale = sales_amount
        if sales_amount < lowest_sale:
            lowest_sale = sales_amount
    #calculate average and print highest, lowest, and average
    average_sales = total_sales / number_sales
    print(name, "'s highest sale: $", format(highest_sale, ',.2f'), sep='')
    print(name, "'s lowest sale: $", format(lowest_sale, ',.2f'), sep='')
    print(name, "'s sale on average: $", format(average_sale, ',.2f'), sep='')

A: File "<string>" shows that your program is being run through exec, most likely passed there with a byte string. So that's probably an oversight in the IDE.
The cause of error may be special characters somewhere in your name. Python 3 should handle that anyway, but Wing IDE seems to try and make code the compatible with Python 2... and fails.
Of course, this is mostly speculation, but you should consider running your script in command line, without any IDE. I did, and it worked.

A: This is a bug in Wing 4.1.3 that can be fixed by using Check for Updates in the Help menu.


text:
Q: How to delete vssver2.scc and global.asax from my Windows Server? I have a Windows server that I SFTP into, and I have some very old vssver2.scc files on there. They are used by Visual Source Safe- which is no longer used (SVN instead now). I want to delete them.
Most troubling though is a very old global.asax file used by ASP.NET applications - since the app is compiled, it reads from it's global.dll in the Bin folder, and not the global.asax. I want to get rid of it. But I can't - and I can't overwrite it in favor of a newer one either.
These files have 444 (Owner:r Group:r Public:r) permission and when I try to give them 777 (O:rwx G:rwx P:rwx) permission hoping it will let me delete them, it goes back to 444.

A: In the root directory write the following:
attrib -s -h -r *.?cc /s
del *.?cc /s

A: It's some sort of wierd permissions issue. Since the sysadmins won't fix it and don't know what the issue is, whenever I have this problem, I just bug them to delete the files I need.

A: If you have physical access to the server, you can boot a live cd like Knoppix and from there navigate over to your drive to delete those files.


text:
Q: Dynamically alter an underscore template for Backbone I'm using Backbone with underscore templates defined in my html like so:
<script type="text/template" id="editTemplate">
    <select id="scred" class="scredSelect">
        <!-- some options -->
    </select>
</script>

and assigned to my Backbone view template (via coffeescript) like this:
template: _.template $("#editTemplate").html()

everything is working as intended. However... I would like to dynamically add some options to the select scred.
I've tried to access the scred select via $("#editTemplate").find('.scredSelect'), but of course, since everything inside of the script tags is not treated as html, the selector doesn't work.
I can access the element like so...
html = $("#editTemplate").html()
$(html).find('.scredSelect').doStuff()

Is there an even easier way to accomplish this?  Or would this be a task better suited to a full blown templating engine like handlebars or mustache?


text:
Q: How to make youtube video added in the iframe accessible? Please advise on how to make Youtube video embedded inside iframe accessible

A: Find your video on YouTube and go to Share>Embed copy the code.
You code should look like this:
<iframe src="https://www.youtube.com/embed/your-video-code"></iframe>


text:
Q: Super simple page navigation with Backbone I have searched all over the place to no avail. Everyone seems to have their own way of building some form of a todo list with backbone. I need to do something a little different albeit more crude. I need to build a four page site on top of backbone–I know I could easily do this with jQuery or equivalent, but this might be something that is increased in scope down the road. So really Im not using Models or Collections, just routes, views and templates. My number of templates is so small I don't need to get them from an external folder I can just swap out divs and have the templates live inline.
In its most simple form I have a single page web app that I need to swap out 4 static views with with one button, one direction, with a start and finish. Thats it. No tutorial or documentation I have found performs something this basic with backbone. Any savvy folks out there care to point me in the right direction?

A: Here's a simple little one-page app that swaps out 4 different templates and steps from page 1 to 4 as you press the button. Let me know if you have questions.

    <title>Steps</title>


text:
Q: remover dados repetidos no mysql Tenho a seguinte tabela chamada cadastro:
cod | nome | idade
Com os dados:
   COD   NOME     IDADE
    2  | rafael  | 15
    3  | bruno   | 17
    4  | rafael  | 33
    5  | sabrina | 18
    6  | bruno   | 15
    7  | paulo   | 15
    8  | rafael  | 15

Notem que algum nomes se repetem, eu preciso rodar um comando no meu mysql para apagar todos os nome repetidos e manter apenas 1, que contenha o maior cod.
Exemplo:
tenho 3 registros com o nome  rafael.
Nesse caso teria que manter apenas o 8 | rafael | 15.
Isso é possível de ser feito?

A: Você pode fazer um DELETE com INNER JOIN na mesma tabela, porém no INNER JOIN você vai trazer somente os registros onde o cod for menos que o da primeira tabela.
DELETE b FROM cadastro a
INNER JOIN cadastro b ON a.nome = b.nome AND b.cod < a.cod

Faça um backup da tabela antes de executar, não tenho sua tabela aqui
  para fazer o teste.


text:
Q: trying to split homepage into four parts I'm trying to divide my homepage into four even images with no scroll. as you click on the website I would like the four images to fill the entire screen and have no scroll. Here's how far I am now but it's not quite working. Any suggestions?

img {
  max-width: 100%;
  height: auto;
}
#container {
  max-width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
.containermenu img {
  width: 50%;
  height: auto;
  float: left;
}

My Code Here

A: Right, here is how I would do it. I'd make 4 boxes and position them in each quarter of the screen. Then I'd give each one a background image that is set to stay centred and to cover the entire box.

/* Sizing */
.containermenu {
  position: absolute;
  width: 50vw;
  height: 50vh;
  background-size: cover;
  background-position: center;
}

/* Images */
.tl {
  background-image: url(https://image.freepik.com/free-vector/bathroom-mosaic-pattern_23-2147497370.jpg);
}
.tr {
  background-image: url(https://image.freepik.com/free-vector/abstract-geometric-pattern_23-2147508597.jpg);
}
.br {
  background-image: url(https://images.blogthings.com/whatpatternisyourbrainquiz/pattern-2.jpg);
}
.bl {
  background-image: url(https://static1.squarespace.com/static/5459ec52e4b04d305f68f1ed/t/548a96e1e4b0a10ad41ef12f/1418368738802/Pattern14.jpg?format=1000w);
}

/* Positioning */
.tl,
.tr {
  top: 0
}
.br,
.tr {
  right: 0
}
.bl,
.br {
  bottom: 0
}
.tl,
.bl {
  left: 0
}

Hope this is helpful.

A:     Is your looking ?

.containermenu{width:25%;float:left}
.containermenu img
{
width: 100%;
height: auto;
float: left;
}

Click here!

A: If you want to remain the proportion, you could use the images as backgrounds in CSS and use
background-size: cover;

A: In your CSS you are trying to use viewport sizing, so you have to set the meta to be available to use it, and body height and width to 100%,  besides setting padding and margin to 0 to remove white bordering as @Andrew Bone suggested.

body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}

img {
  max-width: 100%;
  height: auto;
}

#container {
  max-width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.containermenu img{
  width: 50%;
  height: auto;
  float: left;
}

<meta charset="UTF-8">
<meta name="viewport" content="height=device-height, width=device-width, initial-scale=1">
<title>The Steve Barrett Collection</title>
<link href="style.css" rel="stylesheet" type="text/css">

A: There are two different ways you could to do to achieve this result
With images
If you want to work with images you could make use of the
object-fit: cover property. The great thing about this is that it acts like the background-image: cover but you can set it directly to an image and it doesn't get stretched. There is also a object-position property. Sadly this great feature is not fully supported by the one and only Internet Explorer and even Edge.
HTML

CSS
html,
body {
  height: 100%;
}

body {
  margin: 0;
}

#container {
  width: 100%;
  height: 100%;
  background: #000;
  font-size: 0;
  overflow: hidden;
}

#container img {
  width: 50%;
  height: 50%;
  display: inline-block;
  object-fit: cover;
  object-position: center;
}

html,
body {
  height: 100%;
}
body {
  margin: 0;
}
#container {
  width: 100%;
  height: 100%;
  font-size: 0;
  overflow: hidden;
}
#container img {
  width: 50%;
  height: 50%;
  display: inline-block;
  object-fit: cover;
  object-position: center;
}

With background images
One small disadvantage is that you have to set the path of the images in the CSS but the big advantage is that you can make use of the background-size: cover which is supported in every browser. Here you can also make use of the nth-child selector so you don't have to give each div, in this case .img a class left, right or something.
HTML

CSS
html,
body {
   height: 100%;
}

body {
  margin: 0;
}

#container {
  width: 100%;
  height: 100%;
  font-size: 0;
  overflow: hidden;
}

#container .img{
  width: 50%;
  height: 50%;
  display: inline-block;
  background-size: cover;
}

.img:nth-child(1){
  background-image: url(https://static.pexels.com/photos/32237/pexels-photo.jpg);
}

.img:nth-child(2){
  background-image: url(https://static.pexels.com/photos/30168/pexels-photo-30168.jpg);
}

.img:nth-child(3){
  background-image: url(https://static.pexels.com/photos/164241/pexels-photo-164241.jpeg);
}

.img:nth-child(4){
  background-image: url(https://static.pexels.com/photos/230800/pexels-photo-230800.jpeg);
}

html,
body {
  height: 100%;
}
body {
  margin: 0;
}
#container {
  width: 100%;
  height: 100%;
  font-size: 0;
  overflow: hidden;
}
#container .img {
  width: 50%;
  height: 50%;
  display: inline-block;
  background-size: cover;
  background-position: center;
}
.img:nth-child(1) {
  background-image: url(https://static.pexels.com/photos/32237/pexels-photo.jpg);
}
.img:nth-child(2) {
  background-image: url(https://static.pexels.com/photos/30168/pexels-photo-30168.jpg);
}
.img:nth-child(3) {
  background-image: url(https://static.pexels.com/photos/164241/pexels-photo-164241.jpeg);
}
.img:nth-child(4) {
  background-image: url(https://static.pexels.com/photos/230800/pexels-photo-230800.jpeg);
}


text:
Q: When Nameservers are mapped, my domain say 404 Not Found Hello I have a domain in godaddy, and the server in digital ocean.
In godaddy I configured the nameservers like this: ns1.digitalocean.com, ns2.digitalocean.com, ns3.digitalocean.com
when I enter the domain in the control panel (plesk), I see that there is an error in the DNS configuration, and it says "The domain name of the website does not resolve or resolves to a different IP address". and when I enter the domain it shows me 404 not found.
What am I doing wrong?

A: Plesk control panel? It is not correct. You may login to your domain portal registration to change your name server. If you are not sure, you can contact Godaddy and ask them to point your domain to DigitalOcean name server.


text:
Q: Constructing a Lyapunov function for this system? This question seems interesting but I cant figure out how to apply Micahel E2's solution to my system:
How to write that Lyapunov function?
My system is very simple, I already have a working Lyapunov function for the following system however I would like to see what Mathematica has to offer:
\begin{align}
\frac{dS}{dt} &= \nu N -\frac{\beta S I}{N} + \xi R - \nu S\\[2ex]
\frac{dI}{dt} &= \frac{\beta S I}{N} -\gamma I -\nu I \\[2ex]
\frac{dR}{dt} &= \gamma I -\xi R - \nu R
\end{align}
Let $N=1$; other parameters are arbitrary.
Working Lyapunov function:
\begin{equation}
V(S,I) = S_2^*\left(\frac{S}{S_2^*}-\ln \frac{S}{S_2^*} \right)+ \frac{\gamma + \xi + \nu }{\gamma + \nu}I_2^*\left(\frac{I}{I_2^*}-\ln \frac{I}{I_2^*} \right) .
\end{equation}
where
\begin{align*}
S_2^* &= \frac{\gamma + \nu}{\beta}\\
I_2^*&= \frac{\left(\gamma+\nu \right) \left( \xi + \nu \right) \left( \frac{\beta}{\gamma+\nu} -1 \right) }{\beta\left(\gamma + \xi+\nu \right)}
\end{align*}
A more complex system which I need a Lyapunov function would be:
\begin{align}
\frac{dS}{dt} &= \Lambda-\beta S I + \xi R - \mu S\\[2ex]
\frac{dL}{dt} &= \beta S I+(1-\eta) \delta T -(\mu+\epsilon) L \\[2ex]
\frac{dI}{dt} &= \epsilon L +\eta \delta T - (\mu+\gamma+\sigma_1) I\\[2ex]
\frac{dT}{dt} &= \gamma I -(\mu+\delta+\sigma_2+\alpha) T \\[2ex]
\frac{dR}{dt} &= \alpha T -(\mu+\xi)R
\end{align}
Another interesting system is:
\begin{align}
\frac{dS}{dt} &= \Lambda-\beta S I - (\mu+\sigma) S + \theta V\\[2ex]
\frac{dV}{dt} &= \sigma S -(\mu +\theta)V \\[2ex]
\frac{dE}{dt} &= \beta S I -(\mu +\omega)E\\[2ex]
\frac{dI}{dt} &= \omega E -(\mu+\kappa) I \\[2ex]
\frac{dR}{dt} &= \kappa I -\mu R
\end{align}


text:
Q: Pass gpg key password when signing a release I use a gpg key that is secured with a password.
Is there a way to pass the password to the underlying gpg command?
helm package --sign \
--key "my_key_name" \
--version "$VERSION" \
--app-version "$APP_VERSION" \
--keyring ~/.gnupg/secring.gpg my-chart

I tried echoing the password and piping it, also tried the yes command, but that does not seem to work.
When I do echo "password" | helm package ... I get Error: inappropriate ioctl for device

A: According to helm documentation:

NOTE: If your PGP private key has a passphrase, you will be prompted
  to enter that passphrase for any commands that support the --sign
  option. You can set the HELM_KEY_PASSPHRASE environment variable to
  that passphrase in case you don't want to be prompted to enter the
  passphrase.

The final command is:
export HELM_KEY_PASSPHRASE=<password>
helm package --sign \
--key "my_key_name" \
--version "$VERSION" \
--app-version "$APP_VERSION" \
--keyring ~/.gnupg/secring.gpg my-chart


text:
Q: R remove duplicated columns I have data like this
     X3    X4    X5    X6     X7   X24   X25   X26    X39    X40    X41    X54    X55    X56    X69    X70    X71
1 step1 step2 step3 step4 step10 step2 step3 step4 step10 step10 step10 step10 step10 step10 step10 step10 step10

And I want remove duplicated columns. So desired output is
  X3    X4    X5    X6     X7
1 step1 step2 step3 step4 step10

A:  df[!duplicated(as.list(df))]
     X3    X4    X5    X6     X7
1 step1 step2 step3 step4 step10

A: Try this:
df <- read.table(text = "X3    X4    X5    X6     X7   X24   X25   X26    X39    X40    X41    X54    X55    X56    X69    X70    X71
1 step1 step2 step3 step4 step10 step2 step3 step4 step10 step10 step10 step10 step10 step10 step10 step10 step10",
                 header = TRUE)

df[!duplicated(lapply(df, summary))]
#Output
#     X3    X4    X5    X6     X7
#1 step1 step2 step3 step4 step10