text:
Q: How to show that $\theta(A):=A\cup\mathscr{der}(A)$ is a kuratowski operator? Let be $\eta:\mathcal{P}(X)\rightarrow\mathcal{P}(X)$ a function such that:

*

*$\eta(\varnothing)=\varnothing$;

*$\eta(\eta(A))\subseteq A\cup\eta(A)$, for any $A\subseteq X$;

*$\eta(A\cup B)=\eta(A)\cup\eta(B)$, for any $A,B\subseteq X$;

*$x\notin \eta(\{x\})$, for any $x\in X$.

So putting
$$
\tau*=\{A\subseteq X: \phi(A)\subseteq A\}
$$
I am trying to prove that the collection
$$
\tau=\{V\subseteq X:X\setminus V\in\tau*\}
$$
is a topology on $X$ equal to $\tau^*$ and such that
$$
\eta(A)=\operatorname{der}A
$$
for any $A\in\mathcal P(X)$.
Well to prove the statement we define
$$
\theta:\mathcal{P}(X)\owns A\rightarrow\big(A\cup\eta(A)\big)\in\mathcal{P}(X)
$$
so that we let to prove that $\theta$ is a Kuratowski operator. So to do this we have to demonstrate that

*

*$\theta(\varnothing)=\varnothing$;

*$A\subseteq\theta(A)$ for any ${A}\subseteq{X}$;

*$\theta(\theta(A))=\theta(A)$ for any ${A}\subseteq{X}$;

*$\theta(A\cup{B})=\theta(A)\cup\theta(B)$ for any $A,B\subseteq{X}$.

Well let's start to prove this:

*

*first of all we observe that
$$
\theta(\varnothing)=\varnothing\cup\eta(\varnothing)=\varnothing
$$
so that $1$ holds;

*then we observe that
$$
A\subseteq A\cup\eta(A)=\theta(A)
$$
so that $2$ holds;

*moreover we observe that
$$
\theta(\theta(A))=
\theta(A\cup\eta(A))=
(A\cup\eta(A))\cup\eta(A\cup\eta(A))=\\(A\cup\eta(A))\cup(\eta(A)\cup\eta(\eta(A)))=
A\cup\eta(A)\cup\eta(\eta(A))=
A\cup\eta(A)=
\theta(A)
$$
so that $3$ holds;

*finally we observe that
$$
\theta(A\cup B)=(A\cup B)\cup\eta(A\cup B)=A\cup\eta(A)\cup B\cup\eta(B)=\theta(A)\cup\theta(B)
$$
so that $4$ holds.

Well we proved that $\theta$ is a kuratowski operator so we have
$$
\theta(A)=\operatorname{cl}A
$$
that is
$$
A\cup\eta(A)=A\cup\mathscr{der}(A)
$$
for any $A\subseteq X$: could I argue from this that the identity
$$
\eta(A)=\mathscr{der}(A)
$$
holds? if not how to prove it?
Could someone help me, please?

A: No, you can't argue so, because condition 4. was not used, and without that your reasoning would also work for the closure operator $\eta:=\theta$  itself, concluding that closure is always the same as the derived set.
Nevertheless, $A\cup B=A\cup C$ implies $B\setminus A\subseteq C$ and $C\setminus A\subseteq B$, which will be used below.
If $x\in A\setminus \mathrm{der}(A)$, then there is an open $U\ni x$ such that $U\cap A=\{x\}$, then $\eta(A\setminus U) \subseteq \theta(A\setminus U) \subseteq \theta(X\setminus U) =X\setminus U$, which in particular doesn't contain $x$, so by conditions 3. and 4. for $\eta$, we get
$$x\notin \eta(A\cap U)\cup\eta(A\setminus U) =\eta(A)\,.$$
If $x\notin{\rm der}(A)$ then the case $x\in A$ was just concluded, and in the case $x\notin A$, we have $x\notin \bar A=A\cup \eta(A)$, thus again $x\notin \eta(A)$.
These imply $\eta(A)\subseteq {\rm der}(A)$.
For the other direction, we have ${\rm der}(A)\setminus A=\bar A\setminus A\subseteq \eta(A)$ for any set $A$.
So, let $a\in{\rm der}(A)\cap A$, but then, for $B:=A\setminus\{a\}$, we still have $a\in{\rm der}(B)$, so we can apply the above observation to obtain $a\in\eta(B)$, and conclude by $\eta(A) =\eta(B) \cup\eta(\{a\})$.


text:
Q: What is the purpose of the `KILL QUERY` command? I am beginner to MySQL and SQL and I am learning these technologies from MySQL and MyISAM websites.
I am learning the KILL command now and have learned how to use KILL CONNECTION. But when I come to learn KILL QUERY from MySQL and MyISAM websites where they simply provided information about KILL QUERY that they terminate query that the specified connection id is executing.
Other user (not me) executes INSERT and DELETE queries but when i have used KILL QUERY by getting the connection id of other user via SHOW PROCESSLIST command, it says

Query OK, 0 rows affected (0.01 sec)

But nothing happen to other user.
I just want to know that what is the exact use of this command. What is the purpose of this KILL QUERY command. Can anyone tell me?

A: Some useful pointers:
How can I stop a running MySQL query?
MySQL Kill query
How to kill all processes for a Specific user
MySQL Manaul - Kill
You need to have some clarity here KILL will kill the connection, but KILL QUERY will only kill that query and will leave that connection intact.
Really, if you are using KILL QUERY on another users command, this can only really be noticable if their query is running for longer than your Kill Query command, so if it's a slow query, because [most] queries will execute and close within a fraction of a second, so by the time you've KILLed the other users query, their query may well have completed and closed anyway.
I suspect this is what you are seeing, that you're trying to kill a query that closes and is finished before the kill command can execute.
Killing queries seems (from literature) only useful for slow and long running queries, and why this is so should be obvious from the above.

Edit:
(I had this ready to post on my original answer and then took it out as being irrelevant, but seems to be more relevant now due to comments!)
From the MySQL Manual:

Note
You cannot use KILL with the Embedded MySQL Server library because the embedded server merely runs inside the threads of the host application. It does not create any connection threads of its own.

So to answer your question in the comment, I think that you may be running MySQL embedded so your kill calls will not function.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Equivalent of MERGE in HIVE query I have the following SQL query :
MERGE INTO member_staging x
USING (SELECT member_id, first_name, last_name, rank FROM members) y
ON (x.member_id  = y.member_id)
WHEN MATCHED THEN
    UPDATE SET x.first_name = y.first_name,
                        x.last_name = y.last_name,
                        x.rank = y.rank
    WHERE x.first_name <> y.first_name OR
           x.last_name <> y.last_name OR
           x.rank <> y.rank
WHEN NOT MATCHED THEN
    INSERT(x.member_id, x.first_name, x.last_name, x.rank)
    VALUES(y.member_id, y.first_name, y.last_name, y.rank);

I want to implement it in a Hive query , is there any equivalent for MERGE JOIN in HIVE ?

A: Manual Entry:

*

*https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DML#LanguageManualDML-Merge

Example Syntax:
MERGE INTO <target table> AS T USING <source expression/table> AS S
ON <boolean expression1>
WHEN MATCHED [AND <boolean expression2>] THEN UPDATE SET <set clause list>
WHEN MATCHED [AND <boolean expression3>] THEN DELETE
WHEN NOT MATCHED [AND <boolean expression4>] THEN INSERT VALUES<value list>

Your specific case:
MERGE INTO member_staging AS x
USING (SELECT member_id, first_name, last_name, rank FROM members) y
ON (x.member_id  = y.member_id)
WHEN MATCHED AND (
    x.first_name <> y.first_name OR
    x.last_name <> y.last_name OR
    x.rank <> y.rank
)
THEN
    UPDATE SET x.first_name = y.first_name,
               x.last_name  = y.last_name,
               x.rank       = y.rank
WHEN NOT MATCHED THEN
    INSERT VALUES (y.member_id, y.first_name, y.last_name, y.rank);

A: The MERGE statement is based on ANSI-standard SQL, so the query is pretty the same.
Just switch the WHERE condition in an AND clause like below :
MERGE INTO member_staging AS x
using (SELECT member_id,
              first_name,
              last_name,
              rank
       FROM   members) y
ON ( x.member_id = y.member_id )
WHEN matched AND ( x.first_name <> y.first_name OR x.last_name <> y.last_name OR
x.rank <> y.rank ) THEN
  UPDATE SET x.first_name = y.first_name,
             x.last_name = y.last_name,
             x.rank = y.rank
WHEN NOT matched THEN
  INSERT
  VALUES(y.member_id,
         y.first_name,
         y.last_name,
         y.rank);


text:
Q: Python open doesn't create a file per the docs I find it hard to believe that python still has a problem creating files in 2020...So, I'm assuming it's windows or me...
Here is the code with output.
I have tried modes w, w+, wt with the error message below. The whole point of using w, w+, wt is that the file is created if it doesn't exist
I have changed to using Path.touch, and then using a, a+ modes which just gives and error enter

import sys
print("Python version:")
print (sys.version)

import platform
print("Platform: {} - {} - {}".format(platform.system(), platform.release(), platform.version()))

from pathlib import Path
output = 'hello world!'
save_dir = Path.cwd().joinpath("./sw_out")
if(save_dir.exists() == False):
    save_dir.mkdir()
    print("dir exists now: {}".format(save_dir.exists()))

debug_file = save_dir.joinpath("my_debug.txt")
#debug_file.touch(exist_ok=True)
print(str(debug_file))
with(open(debug_file), 'w+') as f:
    f.write(output)
f.close()

Python version:
3.7.6 | packaged by conda-forge | (default, Dec 26 2019, 23:30:11) [MSC v.1916 64 bit (AMD64)]
Platform: Windows - 10 - 10.0.17763
dir exists now: True
C:\users\me\project\sw_out\my_debug.txt

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-19-447d2a994262> in <module>
     16 #debug_file.touch(exist_ok=True)
     17 print(str(debug_file))
---> 18 with(open(str(debug_file)), 'w+') as f:
     19     f.write(output)
     20 f.close()

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\users\\me\\project\\sw_out\\my_debug.txt'

A: You're doing it wrong.
Change this:
with(open(debug_file), 'w+') as f:

to:
with(open(debug_file, 'w+')) as f:

Which is the same as:
with open(debug_file, 'w+') as f:

A: Simple change should get this working:
with open(debug_file, 'w+') as f:
    f.write(output)
f.close()

A: Try like this:
#debug_file.touch(exist_ok=True)
print(str(debug_file))
with open(debug_file, 'w+') as f:
    f.write(output)
f.close()

This worked for me.


text:
Q: I have a question about the Google Cloud Platform DataFusion product I wonder if data distribution function exists after ETL work in Google Cloud Platform datafusion.
If datafusion cannot provide data distribution method after ETL work, is there a way to provide distribution using another 3-party tool?
I wonder if data distribution is provided after ETL work in datafusion.


text:
Q: Wicket 1.5.RC3 Bug - "Header was already written" I was working on wicket 1.5.1. I tried to export file with iReport.
Export is working but with this error :

ERROR [org.apache.wicket.DefaultExceptionMapper] Unexpected error
  occurred java.lang.IllegalStateException: Header was already written
  to response!

I guess this is a bug of maven 1.5-RC3 and was fixed 1.5.RC4. I have changed maven version to 1.5.RC4.2 .  But still i have same problem.
do you have any idea?


text:
Q: How to get each element in array and split them into two variables from a delimiter How can I get each element in an array, separate them from its delimiter, and store them into two different variables. I can only get the last iteration of my foreach loop. Any answers are fully appreciated.
This is want I wanted to accomplish:
$string1 = array('AL8941786046','AL8941786046');
$string2 = array('464646', '555');

And here is the array that I wanted to work:
Array ( [0] => AL8941786046|464646 [1] => AL8941786046|555 )

First iteration will be this first element AL8941786046|464646, then I separate this first element into two string using explode function. using this line of code
list($string1, $string2) = explode('|', $myArray, 2);
Now I can only get the last iteration only the second element AL8941786046|555
Here is my code:
             $string1 = array();
             $string2 = array();
             $myArray = array('AL8941786046|464646','AL8941786046|555');
             foreach ($myArray as $val) {
                $ars = $val;
                list($string1 , $string2 = explode('|', $val, 2);
             }

A: If you want two arrays as result:
         $string1 = [];
         $string2 = [];
         $myArray = array('AL8941786046|464646','AL8941786046|555');
         foreach ($myArray as $val) {
            $arr=explode('|', $val, 2);
            $string1[]=$arr[0];
            $string2[]=$arr[1];
         }

This will be the output:
$string1: Array ( [0] => AL8941786046 [1] => AL8941786046)
$string2: Array ( [0] => 464646 [1] => 555 )

A: $string1 =[];
         $string2 =[];
         $myArray =  array('AL8941786046|464646','AL8941786046|555');
         foreach ($myArray as $val) {
            $string1[]=explode('|',$val)[0];
            $string2[]=explode('|',$val)[1];
         }
$array=array_combine($string1,$string2);

A: If you want the elements in the array to build two arrays that contain the first and the second part of the elements, you can do this:
$string1 = [];
$string2 = [];
$myArray = ['AL8941786046|464646', 'AL8941786046|555'];

foreach ($myArray as $val) {
    $exploded = explode('|', $val, 2);

    $string1[] = $exploded[0];
    $string2[] = $exploded[1];
}

This will give you:


text:
Q: I want to show employee names of each department on the side. How can I do that in Django?
This is my model; employee and department class. Employee is a child of department.
#models.py
from django.db import models
from django.urls import reverse

# Create your models here.
class emplye(models.Model):
    name = models.CharField(max_length=30)
    email= models.CharField( max_length=20)
    phone =models.CharField( max_length=20)
    address =models.CharField( max_length=20)
    # dept_id =models.IntegerField(max_length=20)
    depertment =models.ForeignKey("depertment", on_delete=models.CASCADE)

    def __str__(self):
        return self.name

class depertment(models.Model):
    name = models.CharField( max_length=20)
    about =models.CharField( max_length=20)

Here is my views.py file. I am annotating employee objects and from department. I am trying to show the employee names in each department .
#views.py
from django.shortcuts import render
from .models import *
from django.db.models import Count

def index(request):

    b = department.objects.all().annotate(emp=(Count('emplye')))

    print("Return:",b)
    print()
    print("SQL Query:",b.query)

    context = {
        'b':b,
    }

    return render(request, 'employee/index.html',context)

Here is my html file
#index.html
{% for z in b %}
    <h1>{{ z.name }} {{ z.emp }}  {{z.employee.name}} </h1>
{% endfor %}

A: You can do this with a custom template filter.
@register.filter
def get_department_employees(department):
    employees = emplye.objects.filter(depertment=department)
    return employees

Then in your template you can access these employees using the with tag.
{% for z in b %}
    {% with employees=z|get_department_employees %}
         <h1>{{ z.name }} {{ z.emp }}  {% for employee in employees %}{{employee.name}}{% endfor %} </h1>
    {% endwith %}
{% endfor %}

To learn how to set up custom template filters read the [Django-Docs] - Custom Template Tags

Note: Assuming you're using the English language, it may be worth checking the spelling for your models. depertment --> department , emplye --> employee.


text:
Q: Widgets and setOnClickPendingIntent Complete android development newbie here, be warned.
I'm trying to develop a homescreen widget that allows you to tap the widget to call a predefined number. I can create the widget and add it to the homescreen just fine, however, when I try to make the widget clickable using setOnClickPendingIntent, it does not launch the activity. The code I am using is provided below:
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
          int[] appWidgetIds) {
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
              R.layout.callwidget_layout);
    Log.d("stuff", "remoteview defined");
    Intent callIntent = new Intent(Intent.ACTION_CALL);
    Log.d("stuff", "intent created");
    callIntent.setData(Uri.parse("tel:"+8888888));
    Log.d("stuff", "intent data added");
    PendingIntent clickPI=PendingIntent
            .getBroadcast(context, 0,
                          callIntent,
                          PendingIntent.FLAG_UPDATE_CURRENT);
    Log.d("stuff", "pending intent created");

    remoteViews.setOnClickPendingIntent(R.layout.callwidget_layout, clickPI);
    Log.d("stuff", "setonclickpendingintent created");

}

The Log.d methods work fine, as they show up on the logcat output, but tapping the widget does nothing. There are no other error messages that show up on logcat. Is there anything I am doing wrong?
UPDATE: Changed the setOnClickPendingIntent to reference a button with the ID "callbutton" (remoteViews.setOnClickPendingIntent(R.id.callbutton, clickPI);), and also tried adding these three lines of code to the onUpdate method:
ComponentName myWidget = new ComponentName(context, WidgetProvider.class);
appWidgetManager.getInstance(context).updateAppWidget(myWidget, remoteViews);
Log.d("stuff", "widget updated");

Again, the Log.d method works, suggesting that the widgets update fine, but tapping the button still does not do anything.
UPDATE 2: Changing PendingIntent clickPI=PendingIntent.getBroadcast to PendingIntent clickPI=PendingIntent.getActivity does not do anything either.

A: Alright, so I have a bit of a workaround to this problem that will have to do until I find an actual solution. This involves launching an activity that in turn launches the intent I want. I initially wanted to avoid this, but oh well.
My new code, for anyone that might need it:
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
          int[] appWidgetIds) {
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
              R.layout.callwidget_layout);
    Log.d("stuff", "remoteview defined");
    Intent callIntent = new Intent(context, CallActivity.class);
    PendingIntent clickPI=PendingIntent
            .getActivity(context, 0,
                          callIntent,
                          PendingIntent.FLAG_UPDATE_CURRENT);
    Log.d("stuff", "pending intent created");

    remoteViews.setOnClickPendingIntent(R.id.callbutton, clickPI);
    Log.d("stuff", "setonclickpendingintent created");
    ComponentName myWidget = new ComponentName(context, WidgetProvider.class);
    appWidgetManager.getInstance(context).updateAppWidget(myWidget, remoteViews);
    Log.d("stuff", "widget updated");

}

CallActivity.java:
package com.example.callzepolice;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

public class CallActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_call);
        Intent callIntent = new Intent(Intent.ACTION_CALL);
        Log.d("stuff", "intent created");
        callIntent.setData(Uri.parse("tel:"+8888888));
        Log.d("stuff", "intent data added");
        startActivity(callIntent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.call, menu);
        return true;
    }

}

A: remoteViews.setOnClickPendingIntent(R.layout.callwidget_layout, clickPI);
You should be referencing a view within a layout. Not a layout.
EDIT: If this is the whole method, you are also missing the appWidgetmanager.updateWidgetAppWidget(...) call.
EDIT 2: You use getBroadcast(...) when you actually want to broadcast a message to a receiver. For calling activities you need getActivity(...).

A: Use ACTION_DIAL, not ACTION_CALL.
See the documentation. E.g. the guide on Common Intents to get the requirements for a system intent, e.g. how to initiate a phone call and the documentation on ACTION_CALL says:

Note: there will be restrictions on which applications can initiate a
  call; most applications should use the ACTION_DIAL.

Also:

... the Log.d method works, suggesting that the widgets update fine ...

The successful Log.d() demonstrates that the code got there (a breakpoint would be another way to determine this), but it doesn't give evidence that the widgets got updated successfully. You have a useful hypothesis there, that the widgets got updated and the problem is after that, e.g. the wrong Intent. One way to test that hypothesis would be make your update visibly change the widget, e.g. text in a TextView.


text:
Q: Can Windows be setup to use multiple monitors but not have a primary monitor? I work as a support developer for an ISV that makes accounting software for Windows.  A customer has reported a strange error.
I tracked the error down to the possibility that the .NET Framework property Screen.PrimaryScreen can return null if multi-monitor support is enabled, but there is no primary monitor.  I want to test this scenario with our application.  I have multiple monitors, but I do not see a way to control Windows without a primary monitor enabled.
Is there a way in Windows to use multiple monitors but not have a primary monitor enabled?  Changing registry settings would be acceptable.
I have tried unplugging the power and DVI from the primary monitor, disabling it in Windows, and deleting it in Device Manager, but this does not seem to affect anything.
I did find this discussion that says "primary screen is not defined under special conditions on Citrix Servers":

*

*Running under seamless mode

*Having a Citrix client using dual screen with primary screen set on the right

*Having a total resolution X color depth of client screens over the maximal video memory allowed on Citrix server

I am not trying to solve this issue from a Citrix perspective.  I was hoping to simulate it in Windows.


text:
Q: Legend on pie chart matplotlib I am trying to make the box for my legend smaller and placed in the upper left hand corner of my pie chart. So far I have:
pumsData = pd.DataFrame.from_csv('ss13hil.csv')
pieLabels = ['English Only','Spanish','Other Indo-European','Asian and Pacific Island Languages','Other']
plt.pie(pumsData.HHL.value_counts())
plt.axis('equal')
plt.title('Household Languages')
plt.legend(pieLabels,loc=2,borderpad=0.05)

the output for my chart is:
http://i.stack.imgur.com/WbO4U.png

but I would like it to look like this:
http://i.stack.imgur.com/cBxLz.png

enter code here

A: If you explicitly create an axes instance as object instead of just using functions from the pyplot module, you can easier access plot properties. with bbox_to_anchor=(0.5,0.90) as argument in ax.legend() you can shift the legend in the figure. Try this code:
import matplotlib.pyplot as plt

pieLabels = ['English Only',
             'Spanish',
             'Other Indo-European',
             'Asian and Pacific Island Languages',
             'Other']

fig, ax  = plt.subplots(1,1,figsize=(4,4))

ax.pie([1,2,3,4,5], labels=pieLabels, labeldistance=9999999)
ax.set(adjustable='box-forced', aspect='equal')
ax.set_title('Household Languages')

handles, labels = ax.axes.get_legend_handles_labels()
ax.legend(handles, labels, prop={'size':6},
          bbox_to_anchor=(0.5,0.90),
          bbox_transform=fig.transFigure)

plt.show()

It should produce this figure:


text: Q: Browser back button to go back to specific route I am on a certain link when I click on the browser back button I want to send it back to the homepage which is the "/" route. How can I implement this feature in Next js?


text:
Q: Caffe does not make snapshots on SIGINT When I'm pressing CTRL+C in terminal, caffe stops training but does not make snapshots. How to fix it?
My solver:
net: "course-work/testing/model.prototxt"
test_iter: 200
test_interval: 500

base_lr: 0.001
momentum: 0.9
weight_decay: 0.005
lr_policy: "fixed"

display: 50
max_iter: 60000

snapshot: 5000
snapshot_format: HDF5
snapshot_prefix: "course-work/testing/by_solver_lr0"
snapshot_after_train: true

solver_mode: CPU

Bash script:
TOOLS=./build/tools
NET_DIR=course-work/testing

$TOOLS/caffe train \
    --solver=$NET_DIR/solver_lr0.prototxt 2>&1 | tee $NET_DIR/1.log

A: Redirecting caffe's output through tee and pipes might alter the way the OS handles and transfers signals to processes. Try avoiding | tee to make sure SIGINT reaches caffe.
Note that caffe tool has two flags
DEFINE_string(sigint_effect, "stop",
             "Optional; action to take when a SIGINT signal is received: "
              "snapshot, stop or none.");
DEFINE_string(sighup_effect, "snapshot",
             "Optional; action to take when a SIGHUP signal is received: "
             "snapshot, stop or none.");

These flags can help you define caffe's behavior on SIGINT and SIGHUP.

A: A good way to log caffe output is
GLOG_log_dir=/path/to/log/dir $CAFFE_ROOT/bin/caffe.bin train
—solver=/path/to/solver.prototxt

This does live logging of caffe output and SIGINT definitely reaches caffe.


text:
Q: Plot gradient of a function which is a matrix in MATLAB I would like to plot the gradient of the following function in MATLAB.
g(x,y) = [(x^2)-1; -y]

My code is:
x = linspace(-3,3);
y = linspace(-3,3);
[xx, yy] = meshgrid(x,y);
z = [xx.^2-1;-yy];
[dx,dy] = gradient(z,.3,.3);
contour(x,y,z)
hold on
quiver(x,y,dx,dy)

But I'm just getting this error:
The size of Y must match the size of Z or the number of rows
of Z.

I've no idea how I could make the size of both match. y is a 1x100 matrix and z a 200x100. To match them I would need y to be a 1x200 or z to be 100x100, but would I be able to plot it then?

A: Instead of
z = [xx.^2-1;-yy];

try each component separately:
z1 = [xx.^2-1];
z2 = [-yy];
[dx,dy] = gradient(z1,.3,.3);
contour(x,y,z1)
%etc.

Use hold on again if you really want them in the same plot.


text:
Q: Why "rows["epic_week"] = epic_week" does not work? I try to add a new column to pandas data frame. When I want to update the by using iterrows() function, the "rows["epic_week"]  = epic_week" does not work.
date_counter = 5
pre_date = df.Date[0]
epic_week = 9
df["epic_week"] = 0
for index, rows in df.iterrows():
    if rows["Date"] != pre_date:
        date_counter += 1
        pre_date = rows["Date"]
        if date_counter > 7:
            date_counter = 1
            epic_week += 1
        rows["epic_week"] = epic_week

A: Check out the second note here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html. You are iterating over your dataframe so you shouldn't try to modify it as you iterate over it.
You could try making a copy of the df and iterating over the copy while updating the original, or save the changes you'd like to add in a data structure while you're in the loop then add them to the df once you're done iterating over it.

A: Try this, change the last line as shown below
date_counter = 5
pre_date = df.Date[0]
epic_week = 9
df["epic_week"] = 0
for index, rows in df.iterrows():
    if rows["Date"] != pre_date:
        date_counter += 1
        pre_date = rows["Date"]
        if date_counter > 7:
            date_counter = 1
            epic_week += 1
        rows.at[index, "epic_week"] = epic_week # This will work


text:
Q: NSNumberFormatter returning null in Xamarin.iOS + ShinobiChart I'm trying to get a string parsed into a NSNumber that has the % character in the end where I can use the in the ShinobiChart value property of the series.
Given the following code, I'm creating the NSNumberFormatter:
var formatter = new NSNumberFormatter ();
            formatter.NumberStyle = NSNumberFormatterStyle.Percent;
            var locale = new NSLocale ("en_US");
            formatter.Locale = locale;

Now, I'll try to use the formatter to get the value for the chart slice label:
var value = formatter.NumberFromString (answer.RepliesShare.ToString () + "%");

This will give me the value 0.33... The point is, if I remove the "%" from the string, I'll get null on the value.
So, I need get a NSNumber that has the value of (i.e.) 30%(in other words, numberString+"%").
How can I get it?
To be more clear, I'm trying to achieve this:

Since ShinobiChart takes a Value of Type NSNumber and my RepliesShare is a decimal I'm trying just convert my decimal from 33.00 to 33%. The ShinobiChart don't take a string, otherwise I would have it handled. I found that NSNumber can be formatted with NSNumberFormatted so I thought I can use it since the Chart takes a number.

A: NSNumberFormatters do 2 things (amongst others):

*

*Translate a formatted numeric NSString into an NSNumber (@"25.4%" → @"0.254")

*Translate an NSNumber into a formatted NSString (@"0.254" → @"25.4%")

It's not terribly clear from your question, but I think you're trying to do the latter of these two options, but you're using the method for the first.
The following will take an NSNumber object and turn it into a %age formatted string:
var formatter = new NSNumberFormatter();
formatter.NumberStyle = NSNumberFormatterStyle.Percent;
formatter.Locale = NSLocale.CurrentLocale;
var value = formatter.stringFromNumber(new NSNumber(0.254));

This will result in value being an NSString representing 25.4%.
Provided that RepliesShare property on your answer object is an NSNumber then you can do the following to get the string you require:
var value = formatter.stringFromNumber(answers.RepliesShare);

Hope that helps.
Note: Rather than using new NSLocale ("en_US") here I used NSLocale.CurrentLocale. This will ensure that the resultant string is formatter appropriately for the current user's device. The most obvious effect that this will have with percentages is that in some European countries, a comma , is used as the decimal separator instead of a period ..

A: A SChartDonutSeries (and consequently SChartPieSeries) object has a LabelFormatString property. This takes a string and is used to format those labels. It has the same syntax as is used in NSNumberFormatter. Therefore, to get the behaviour you want, set the LabelFormatString after you've created the series object in your SChartDataSource subclass:
var series = new SChartDonutSeries();
series.LabelFormatString = "%0.2f%%";

This will format numbers as 2 decimal placed with a percentage sign on the end. i.e. 25.462 → 25.46%. Adjust the format string appropriately to get the format you desire. Remember that to get a % sign to appear you need to escape it - %%.
Further details on creating an appropriate format string are available here:
https://developer.apple.com/library/ios/documentation/cocoa/conceptual/Strings/Articles/formatSpecifiers.html

A: I think you're misunderstanding what NSNumberFormatter does. It has nothing at all to do with NSNumber objects.
NSNumberFormatter is an object for working with strings that happen to contain numeric values. It is not for working with NSNumber.

Since ShinobiChart takes a Value of Type NSNumber and my RepliesShare is a decimal I'm trying just convert my decimal from 33.00 to 33%.

You do not want to convert anything, just give 33.00 as a decimal type to ShinobiChart. I think Xamarin will convert your C# decimal to an NSNumber automatically.
If it doesn't work, try giving new NSNumber(33.00) to ShinobiChart. There should be no percents anywhere. You definitely do not want to create an NSNumberFormatter


text:
Q: Is negative_mean_squared greater the more accuracy or less computes to more accuracy? -0.567
-4.235
Which of the above negative_mean_squared error value computes to more accuracy?

A: Higher the value better it is. So in your case -0.567 is better. A per the documentation sklearn scoring functions maintain the following convention higher return values are better than lower return values.  But when you look at mean_squared_error or for that matter even mean_absolute_error lower the value better it is. So they just flip the sign of the value to make sure it follows the convention. For your example, -0.567 results in a mean_squared_error of just 0.567 whereas, -4.235 has a mean_squared_error of 4.235 which is much higher than the former.


text:
Q: MutationObserver doesn't trigger when text changes I have a simple tag on my html page

My text

Im new to JavaScript. I need that MutationObserver detect when text changes in "My text"
here is my JavaScript code

var target = document.querySelector("#myid");

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        console.log(mutation.type);
    });
});

var config = {
    childList: true,
    attributes: true,
    characterData: true,
    subtree: true,
    attributeFilter: ["myid"],
    attributeOldValue: true,
    characterDataOldValue: true
}

observer.observe(target, config);

observer.disconnect();

A: If you want to detect changes of a text field you can simply use onChange event, for example:
<input type="text" id="myid"/>

MutationObserver is good to use when you want to subscribe on DOM changes - like attribute changes etc. That's why youк code doesn`t work, because you don't have any changes related to DOM structure.
See example with additionally adding new attribute:
const targetNode = document.getElementById('myid');

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
    // Use traditional 'for loops' for IE 11
    for(const mutation of mutationsList) {
        if (mutation.type === 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type === 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

//MODIFY THE ATTIBUTE TO SEE THE CHANGE
targetNode.style["color"] = "red";

If you want to play with it, please see: https://jsfiddle.net/a0vdxt5n/40/


text:
Q: Symfony phpunit functional test edit confirm inconsistent I added some functionality where if you edit an item that somebody edited in the meantime, you go to an "edit confirm" page where you can select which changes you want to overwrite.
How it's done:
if ($request->isMethod('GET')) {
    $session->set('overwriteDate', $language->getUpdatedAt()?->format('Y-m-d H:i:s'));
    $session->set('language_referer',  $request->headers->get('referer'));
}

$form = $this->createForm(LanguageFormType::class, $language);
$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    var_dump($language->getUpdatedAt());
    var_dump($session->get('overwriteDate'));
    if ($session->get('overwriteDate') !== $language->getUpdatedAt()?->format('Y-m-d H:i:s')) {
        $session->set('overwriteItem', $language);

        return $this->redirectToRoute('languages_edit_confirm', ['id' => $language->getId()]);
    } else {
        $baseEntityService->save($language);

        return $this->redirect($session->get('language_referer'));
    }
}

return $this->render('admin/language/edit.html.twig', [
    'language' => $language,
    'form' => $form->createView()
]);

If the overwriteDate in the session doesn't match the updatedAt from the object, it will redirect to the edit confirm page. This all works fine in the browser (tested it manually a lot, never had an issue).
However, now I try to write a functional test for this, and it's inconsistent. This is the begin of the test:
$crawler1 = $this->client->request('GET', '/admin/languages');
$crawler1 = $this->filterTable($crawler1, $originalEnglishName);
$crawler1 = $this->client->click($crawler1->filter('a.edit-language')->link());

$crawler2 = $this->client->request('GET', '/admin/languages');
$crawler2 = $this->filterTable($crawler2, $originalEnglishName);
$crawler2 = $this->client->click($crawler2->filter('a.edit-language')->link());

$form = $crawler1->selectButton('saveLanguage')->form();
$form['language_form[abbreviation]'] = $firstEditAbbreviation;
$form['language_form[englishName]'] = $firstEditEnglishName;
$form['language_form[name]'] = $firstEditName;
$form['language_form[flag]'] = $firstEditFlag;

$form2 = $crawler2->selectButton('saveLanguage')->form();
$form2['language_form[abbreviation]'] = $secondEditAbbreviation;
$form2['language_form[englishName]'] = $secondEditEnglishName;
$form2['language_form[name]'] = $secondEditName;
$form2['language_form[flag]'] = $secondEditFlag;

$this->client->submit($form);
$this->client->submit($form2);
$crawler2 = $this->client->followRedirect();

$tbody = $crawler2->filter('table#difference-table tbody')->first();

After this I try to assert some stuff from $tbody however sometimes the test works fine but sometimes it gives errors because it acts like a normal edit and redirects to the homepage and the data from $tbody I search on doesn't exist.
Edit:
I tried changing the session stuff to putting it in the form as hidden input, but this gives the same issues.

A: You'll need to preserve the session cookie between then requests in your test(s).
The Symfony HTTPClient does not do this by default.

The HTTP client provided by this component is stateless but handling cookies requires a stateful storage (because responses can update cookies and they must be used for subsequent requests). That's why this component doesn't handle cookies automatically.
You can either handle cookies yourself using the Cookie HTTP header or use the BrowserKit component which provides this feature and integrates seamlessly with the HttpClient component.

Example usage:
// Request using the client
$crawler = $client->request('GET', '/');

// Get the cookie Jar
$cookieJar = $client->getCookieJar();

// Get the history
$history = $client->getHistory();

// Get a cookie by name
$sessionCookie = $cookieJar->get('PHPSESSID');

// create cookies and add to cookie jar
$cookie = new Cookie('PHPSESSID', 'XYZ', strtotime('+1 day'));
$cookieJar = new CookieJar();
$cookieJar->set($cookie);

// create a client and set the cookies
$client = new Client([], null, $cookieJar);


text:
Q: C# application doesn't run if out of build folder I'm having a weird problem.
I made a C# "Windows Forms Application" project from VS2012. It has some 3rd party DLL linked. The build was fine and I had no problem to run the exe file which was right in project's build folder, ie \myproject\bin\Debug\x.exe. But if I copied out the exe to anywhere and double click the exe, it didn't run any more. I tried this on my own PC and other's PC as well.
I am using windows 8 and .NET 4.5.
Please shed some light to me.

A: When moving the executable of an application that uses 3rd party libraries, make sure you move the .DLL files along with it.
.NET applications use the local execution path to first check for dll dependencies, then query the Global Assembly Cache (a.k.a. GAC). The GAC contains all the built-in libraries of the .NET framework but custom libraries may also be added to it.
The common scenario of referenced DLLs, however, is to keep them along with the executable, since installing a library in GAC is a more-complex scenario and requires the prerequisites on any machine where the exe should run.


text:
Q: Construct the linear functional $\phi$ Let
$A$=$\begin{bmatrix}
1 &1  &1 \\
0 & 2 & 1\\
0 &0  & 2
\end{bmatrix}$

let  $W=\{x \in \mathbb{R^3} \mid Ax=2x\}$

Construct a linear functional $\phi$ on $\mathbb{R^3}$ such that $\phi(x_0)=1$ where $x^t_0=(1,2,3),$   and $\phi(x)=0$ $\forall x \in W$
The solution I tried - Here the eigenvalues of given matrix are $1,2$ and the set $W$ is set of all the eigenvalues corresponding to eigenvalue $2$. Here I have to find the functional, I don't have that much idea about functionals.
Please help
Thank you

A: Hint: A functional in this context is a linear map $\phi:\Bbb R^3 \to \Bbb R$.  Every functional on $\Bbb R^3$ can be written in the form $\phi((x_1,x_2,x_3)^T) = a_1x_2 + a_2 x_2 + a_3 x_3$ for some $a_1,a_2,a_3$.  In other words, you can think of $\phi$ as being a row-vector $(a_1,a_2,a_3)$.
$W$ is one-dimensional; find a vector $v = (v_1,v_2,v_3)^T$ which forms a basis of $W$.  Once you have done that, you want a that satisfies $\phi(v) = 0$ and $\phi(x) = 1$.  In other words, you need a solution $(a_1,a_2,a_3)$ to the system of equations
$$
\phi(v) = a_1 v_1 + a_2 v_2 + a_3 v_3 = 0\\
\phi(x) = a_1(1) + a_2(2) + a_3(3) = 0.
$$

A: It is easy to check that if $Ax=2x$ then $x$ is a multiple of $(1,1,0)$. Any linear functional has the form $\phi(a,b,c)=\lambda a+\mu b+\nu c$. We have $\phi(1,1,0)=0$ and $\phi(1,2,3)=1$, so we have $$\lambda+\mu=0\text{ and }\lambda+2\mu+3\nu=1$$ So we find $$\mu=-\lambda,\nu=\frac{1+\lambda}{3}$$ In particular, we can take $\lambda=2,\mu=-2,\nu=1$. So $\phi(a,b,c)=2a-2b+c$.
Check: $\phi(1,1,0)=2\cdot1-2\cdot1+0=0$ and $\phi(1,2,3)=2\cdot1-2\cdot2+1\cdot3=1$.

A: A linear functional is just a linear function that takes a vector and outputs a scalar. The Riesz representation theorem tells us that if we have an inner product $\langle\cdot,\cdot\rangle:\mathbb R^n\times\mathbb R^n\to\mathbb R$, then for any linear functional $\phi$ on $\mathbb R^n$, there is a unique element $y\in\mathbb R^n$ such that for all $x\in\mathbb R^n$, $\phi(x)=\langle x,y\rangle$.
Now, you can find either by inspection or other methods that the eigenspace of $2$ is spanned by $(1,1,0)$, so, taking the standard Euclidean inner product (dot product) for our inner product on $\mathbb R^3$, this problem is equivalent to finding some vector $y$ such that $y\cdot(1,1,0)=0$ and $y\cdot(1,2,3)=1$. The first equation tells us that $y$ is orthogonal to $(1,1,0)$, so we can write $y=\lambda(1,-1,0)+\mu(0,0,1)$. Substituting this into the second equation and simplifying produces $3\mu-\lambda=1$. Any pair of real numbers that satisfy this equation produce a linear functional that satisfies the given conditions.


text:
Q: Take an object out of a MutableArray and place it in a new object Here is my code simplified:
NSMutableArray* buildBlocks = [[[NSMutableArray alloc] initWithCapacity:0] retain];
Block* selectedBlock = [[[Block alloc] init] retain];

// Add several blocks to "buildBlocks"

for( int i=0; i < [buildBlocks count]; i++)
{
    Block* tempBlock = [buildBlocks objectAtIndex:i];

    if( tempBlock.selected )
    {
        // Move the block to the selected block
        selectedBlock = tempBlock;

        // Take the block out of the array
        [buildBlocks removeObjectAtIndex:i];
    }
}

// Some code later

if( selectedBlock.selected )  // <---- Crashes here
{
     // Do stuff
}

I want to copy the selected block to "SelectedBlock," delete the block out of the array, then use the "SelectedBlock" later.  When I used this code I always get "EXC_BAD_ACCESS.  I feel like the program is releasing the data in "SelectedBlock" before I want it to.  What am I doing wrong?
UPDATE:
Thanks for the help everyone.  I fixed it.

A:
Block* selectedBlock = [[[Block alloc] init] retain];

This creates (and unnecessarily retains, since you already own it) a new Block. Why would you want to create a new one when your aim is to retrieve one that you already have?

// Move the block to the selected block
selectedBlock = tempBlock;

That comment doesn't make sense. Nothing is moved from one block to another; you are setting the selectedBlock variable to point to the block you got from the array. After that point, selectedBlock and tempBlock both point to the same block, which is the block in the array.

// Take the block out of the array
[buildBlocks removeObjectAtIndex:i];

The array owns all of the blocks it contains, so when you remove the block you got from the array, the array releases it. If that was the only ownership of that block, the block consequently gets deallocated. Any use of it thereafter is invalid.
Such as…

if( selectedBlock.selected )  // <---- Crashes here

selectedBlock points to the block you got and then removed from the array. Assuming the array was the only thing owning it, it is a dead object by this point, so yes, sending it a message causes a crash.
You retained the object that you initialized selectedBlock with, but not the object that you replaced that object with later. Retaining that initial object did not pre-actively retain any future objects you assigned to the variable; it retained only that initial object.
There are several things you need to change:

*

*Initialize selectedBlock to nil, not a pointer to a new Block.

*Don't retain things at random. Always retain with a purpose. If you don't fully understand why retaining something is the right thing to do ("makes it not crash" is not, by itself, an acceptable reason), don't just throw a retain on it. Understand the memory-management rules in the Advanced Memory Management Programming Guide and you'll know when you need to retain, and why your retain in [[[Block alloc] init] retain] is unnecessary.

*When you retain something, always balance it out with a release or autorelease message. A retain that you don't balance out is a leak, and leaks cause problems eventually. Under iOS, they cause what is effectively, from the user's perspective, a crash (more accurately, you use too much memory and the system kills your app).

*When you assign the object from the array to selectedBlock, retain it and autorelease it before you remove it from the array. The retain makes you an owner, and the autorelease makes that temporary; being an owner, for as long as that lasts, will keep the object alive long enough for you to use it, preventing the crash.

*Don't bother asking the selected block whether it's selected. You only assign a Block's pointer to selectedBlock if it's selected, so by the time you go to use selectedBlock, you already know that it's selected. Combined with #1 above, you can simply test whether selectedBlock is nil; if it isn't nil, there is a selected block, and if it is nil, you did not find (i.e., there is not) a selected block.

*After you get this code working, convert it to ARC. (There's a menu item for this in the Edit/Refactor menu.) Then you don't have to retain or release or autorelease anything; most things just work.

A: I would say that the block is being released from under you when you remove it from the array, but you've put in spurious (and unnecessary) retains in there so it's hard to tell what is going on without seeing the code that you are leaving out.
Normally, when I remove and object from an array and want to keep hold of it, I retain it. But you're over-retaining anyway so that might not be the problem, but without seeing the rest of the method, I can't be sure.

A: Here you go:
NSMutableArray* buildBlocks = [[[NSMutableArray alloc] initWithCapacity:0] retain];
Block* selectedBlock;

// Add several blocks to "buildBlocks"

for( int i=0; i < [buildBlocks count]; i++)
{
    Block* tempBlock = [buildBlocks objectAtIndex:i];

    if( tempBlock.selected )
    {
        // Move the block to the selected block
        selectedBlock = tempBlock;
        [selectedBlock retain];  // Retain selectedBlock here

        // Take the block out of the array
        [buildBlocks removeObjectAtIndex:i];
    }
}

// Some code later

if( selectedBlock.selected )  // <---- Crashes here
{
     // Do stuff
}

[selectedBlock release]; // release when done.

Basically, you were retaining a brand new, never used Block in line 2.  selectedBlock never got retained and when you removed it from the array, it was destroyed.  Thus selectedBlock was pointing to an old stale destroyed piece of memory causing a crash.


text:
Q: Как исправить змейку? Всем привет, написал простую змейку и возникла ошибка в том, что красные клетки расположены далеко друг от друга, как это можно исправить?
import pygame

SIZE_BLOCK = 14
WHITE = (180, 180, 200)
BLUE_BLACK = (225, 225, 225)
BLACK = (0, 0, 0)
HEADER_COLOR = (255, 255, 255)
SNAKE_COLOR = (255, 0, 0)
COUNT_BLOCK = 25
HEADER_MARGIN = 70
MARGIN = 1
size = [SIZE_BLOCK * COUNT_BLOCK + 2 * SIZE_BLOCK + MARGIN * COUNT_BLOCK,
        SIZE_BLOCK * COUNT_BLOCK + 2 * SIZE_BLOCK + MARGIN * SIZE_BLOCK + HEADER_MARGIN + 10]
screen = pygame.display.set_mode(size)
print(size)
pygame.display.set_caption('snake')
timer = pygame.time.Clock()

def draw_block(color, row, column):
    pygame.draw.rect(screen, color,
                     [SIZE_BLOCK + column * SIZE_BLOCK + MARGIN * (column + 1),
                      HEADER_MARGIN + SIZE_BLOCK + row * SIZE_BLOCK + MARGIN * (row + 1),
                      SIZE_BLOCK,
                      SIZE_BLOCK])

class SnakeBlock:
    def __init__(self, x, y):
        self.x = x
        self.y = y

snake_block = [SnakeBlock(9, 8), SnakeBlock(9, 9), SnakeBlock(9, 10)]
d_row = 0
d_col = 1

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and d_col != 0:
                d_row = -1
                d_col = 0
            elif event.key == pygame.K_DOWN and d_col != 0:
                d_row = 1
                d_col = 0
            elif event.key == pygame.K_LEFT and d_row != 0:
                d_row = 0
                d_col = -1
            elif event.key == pygame.K_RIGHT and d_row != 0:
                d_row = 0
                d_col = 1

    screen.fill(WHITE)
    pygame.draw.rect(screen, HEADER_COLOR, [0, 0, size[0], HEADER_MARGIN])
    for row in range(COUNT_BLOCK):
        for column in range(COUNT_BLOCK):
            if (row + column) % 2 == 0:
                color = BLACK
            else:
                color = BLACK
            draw_block(color, row, column)

    for block in snake_block:
        draw_block(SNAKE_COLOR, block.x, block.y)
        block.x += d_row
        block.y += d_col

        head = snake_block[-1]
        new_head = SnakeBlock(head.x + d_row, head.y + d_col)
        snake_block.append(new_head)
        snake_block.pop(0)

    pygame.display.flip()
    timer.tick(2)

A: создания новой части надо вынести из цикла for
import pygame

SIZE_BLOCK = 14
WHITE = (180, 180, 200)
BLUE_BLACK = (225, 225, 225)
BLACK = (0, 0, 0)
HEADER_COLOR = (255, 255, 255)
SNAKE_COLOR = (255, 0, 0)
COUNT_BLOCK = 25
HEADER_MARGIN = 70
MARGIN = 1
size = [SIZE_BLOCK * COUNT_BLOCK + 2 * SIZE_BLOCK + MARGIN * COUNT_BLOCK,
        SIZE_BLOCK * COUNT_BLOCK + 2 * SIZE_BLOCK + MARGIN * SIZE_BLOCK + HEADER_MARGIN + 10]
screen = pygame.display.set_mode(size)
print(size)
pygame.display.set_caption('snake')
timer = pygame.time.Clock()

def draw_block(color, row, column):
    pygame.draw.rect(screen, color,
                     [SIZE_BLOCK + column * SIZE_BLOCK + MARGIN * (column + 1),
                      HEADER_MARGIN + SIZE_BLOCK + row * SIZE_BLOCK + MARGIN * (row + 1),
                      SIZE_BLOCK,
                      SIZE_BLOCK])

class SnakeBlock:
    def __init__(self, x, y):
        self.x = x
        self.y = y

snake_block = [SnakeBlock(9, 8), SnakeBlock(9, 9), SnakeBlock(9, 10)]
d_row = 0
d_col = 1

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and d_col != 0:
                d_row = -1
                d_col = 0
            elif event.key == pygame.K_DOWN and d_col != 0:
                d_row = 1
                d_col = 0
            elif event.key == pygame.K_LEFT and d_row != 0:
                d_row = 0
                d_col = -1
            elif event.key == pygame.K_RIGHT and d_row != 0:
                d_row = 0
                d_col = 1

    screen.fill(WHITE)
    pygame.draw.rect(screen, HEADER_COLOR, [0, 0, size[0], HEADER_MARGIN])
    for row in range(COUNT_BLOCK):
        for column in range(COUNT_BLOCK):
            if (row + column) % 2 == 0:
                color = BLACK
            else:
                color = BLACK
            draw_block(color, row, column)

    for block in snake_block:
        draw_block(SNAKE_COLOR, block.x, block.y)
        block.x += d_row
        block.y += d_col

    head = snake_block[-1]
    new_head = SnakeBlock(head.x + d_row, head.y + d_col)
    snake_block.append(new_head)
    snake_block.pop(0)

    pygame.display.flip()
    timer.tick(2)


text:
Q: Component not updating even though useState value has changed I am trying to create a dynamic dropdown using bootstrap. The items in this dropdown will change dependent on the value selected in the previous dropdown. The value in the previous dropdown changes successfully and the state also changes but {userName} does not re-render after each select.
const users = ... // API call from server

const [userName, setUserName] = useState([]);

useEffect(() => {
   console.log(userName) // userName successfully changes at each select
}, [userName]);

function handleSelect(event) {
   setUserName(event.target.value)
}

return (
   ...
   <Form.Group>
      <Form.Label>
         Select User
      </Form.Label>

      // This part works fine
      <Form.Control
          as="select"
          onChange={handleSelect}
          className="form-select"
      >
           {users.map(names => {
               <option key={names.value} > {names.name} </option>
           }
     </Form.Control>

    <Dropdown>
       // userName doesnt change
       <Dropdown.Item> {userName} </Dropdown.Item>
    <Dropdown>
   ...
 )

A: Note https://reactjs.org/docs/hooks-reference.html#usestate
Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:
        function handleSelect(event) {
           setUserName((prevValues) => return [...prevValues, event.target.value])
        }

A: I have used the same code which you have provided and it is working for me.
Maybe this snippet helps you.

// Get a hook function

const { useState, useEffect, Fragment } = React;
const { Form, Dropdown, Row, Col, Container } = ReactBootstrap;

const Example = ({}) => {
    const [userName, setUserName] = useState([]);
    const users = [
        { name: "abc", value: "abc" },
        { name: "xyz", value: "xyz" }
    ];

    function handleSelect(event) {
        setUserName(event.target.value);
    }

    return (
        <Container>
            <Row>
                <Col sm={6}>
                    <Form.Label>Select User</Form.Label>
                    <Form.Control as="select" onChange={handleSelect} className="form-select">
                        {users.map((val) => {
                            return <option key={val.value}> {val.name} </option>;
                        })}
                    </Form.Control>
                </Col>
            </Row>
            <Row>
             <Form.Label>Selected Value:</Form.Label>
                <Dropdown>
                    <Dropdown.Item>{userName}</Dropdown.Item>
                </Dropdown>
            </Row>
        </Container>
    );
};

// Render it
ReactDOM.render(<Example title="Example using Hooks:" />, document.getElementById("react"));
<link
  rel="stylesheet"  href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"
  integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l"
  crossorigin="anonymous"
/>


text:
Q: oracle sql count case statements returning sum of all columns I have a query where I am trying to count the number of transactions per day by pers id for each day of the week and I am seeing something I can't figure out. Instead of showing the count per day, I'm getting the sum of the count for all days in each days' column. Here's my script:
    Select distinct
    pers.prsid,

    count(case when trim(to_char(transaction.actdatetime, 'day')) = 'Monday' THEN transaction.rtxnnbr ELSE 0 END) as "Monday",

    count(case when trim(to_char(transaction.actdatetime, 'day')) = 'Tuesday' THEN transaction.rtxnnbr ELSE 0 END) as "Tuesday",

    count(case when trim(to_char(transaction.actdatetime, 'day')) = 'Wednesday' THEN transaction.rtxnnbr ELSE 0 END) as "Wednesday",

    count(case when trim(to_char(transaction.actdatetime, 'day')) = 'Thursday' THEN transaction.rtxnnbr ELSE 0 END) as "Thursday",

    count(case when trim(to_char(transaction.actdatetime, 'day')) = 'Friday' THEN transaction.rtxnnbr ELSE 0 END) as "Friday"

    FROM PERS, TRANSACTION

    WHERE
    ((TRANSACTION.POSTDATE between TO_DATE('03-05-2018','MM-DD-YYYY') AND TO_DATE('03-09-2018','MM-DD-YYYY'))
AND ((TRANSACTION.ORIGPERSNBR = PERS.PERSID(+)))

Output:
prsid   Monday  Tuesday Wednesday   Thursday    Friday
1050    60      60      60          60          60
1090    66      66      66          66          66

What I was expecting to see:
prsid   Monday  Tuesday Wednesday   Thursday    Friday
1050    10      15      5           19          11
1090    15      11      20          6           14

EDIT: Added the table join that I forgot to copy over

A: I would suggest the following query:
SELECT
    p.prsid,
    SUM(CASE WHEN TRIM(TO_CHAR(r.actdatetime, 'day')) = 'Monday' THEN t.rtxnnbr ELSE 0 END) AS "Monday",
    SUM(CASE WHEN TRIM(TO_CHAR(t.actdatetime, 'day')) = 'Tuesday' THEN t.rtxnnbr ELSE 0 END) AS "Tuesday",
    SUM(CASE WHEN TRIM(TO_CHAR(t.actdatetime, 'day')) = 'Wednesday' THEN t.rtxnnbr ELSE 0 END) AS "Wednesday",
    SUM(CASE WHEN TRIM(TO_CHAR(t.actdatetime, 'day')) = 'Thursday' THEN t.rtxnnbr ELSE 0 END) AS "Thursday",
    SUM(CASE WHEN TRIM(TO_CHAR(t.actdatetime, 'day')) = 'Friday' THEN t.rtxnnbr ELSE 0 END) as "Friday"
FROM PERS p
INNER JOIN TRANSACTION t
    ON p.TRANS_ID = t.ID
WHERE
    t.POSTDATE BETWEEN TO_DATE('03-05-2018','MM-DD-YYYY') AND
    TO_DATE('03-09-2018','MM-DD-YYYY'
GROUP BY
    p.prsid

The key points are that you likely intended to join the person and transaction tables.  Also, from your case expressions you might have intended to sum the rtxnnbr field rather than counting it.  You don't need to use distinct, but rather aggregate by person using GROUP BY.

A: Well, you need a join condition:
FROM PERS JOIN
     TRANSACTION
     ON PERS.? = TRANSACTION.?

If you always use explicit JOIN syntax, you won't have this problem.
As for writing the query, I would go for:
SELECT pers.prsid,
       sum(case when to_char(t.actdatetime, 'DY') = 'MON' THEN 1 ELSE 0 END) as "Monday",
       sum(case when to_char(t.actdatetime, 'DY') = 'TUE' THEN 1 ELSE 0 END) as "Tuesday",
       sum(case when to_char(t.actdatetime, 'DY') = 'WED' THEN 1 ELSE 0 END) as "Wednesday",
       sum(case when to_char(t.actdatetime, 'DY') = 'THU' THEN 1 ELSE 0 END) as "Thursday",
       sum(case when to_char(t.actdatetime, 'DY') = 'FRI' THEN 1 ELSE 0 END) as "Friday"
FROM PERS p JOIN
     TRANSACTION t
     ON p.? = t.?  -- probably prsid
WHERE t.POSTDATE >= DATE '2018-03-05' AND
      t.POSTDATE < DATE '2018-03-10'
GROUP BY p.prsid;

Notes:

*

*Use DATE constants for, well, date constants.  Also, the >= and < helps avoid problems -- particularly in a database where the DATE data type has a time component and often prints out only using the date.

*Use an explicit GROUP BY.  You have an aggregation query.  Be proud and use GROUP BY.

*The use of TRIM() with the full weekday name is correct.  However, the use of three character abbreviations is simpler.

A: When you count you count all not null values and the ELSE 0 always returns a value.
Either remove it:
count(case when trim(to_char(transaction.actdatetime, 'day')) = 'Monday'
           THEN transaction.rtxnnbr END) as "Monday",

or switch to SUM(0/1):
SUM(case when trim(to_char(transaction.actdatetime, 'day')) = 'Monday'
         THEN 1 ELSE 0 END) as "Monday",


text:
Q: No route matches [POST] "/articles/new" - Why? I made the following introduction:
http://guides.rubyonrails.org/getting_started.html
And after that, I wanted to create a new field (like title) and got the error notification:
Here is my code:
routes.rb
Rails.application.routes.draw do
  get 'welcome/index'

  resources :articles do
    resources :comments
    resources :description
    root 'welcome#index'

    # For details on the DSL available within this file, see guides.rubyonrails.org/routing.html
  end
end

I know that this question has been asked a lot but their solutions didn't helped me.
What should I do?
Regards

A: The problem is in your new.html.erb form, you are missing url: articles_path, if you don't specify it, the form will be sent to the same action (i.e. new). So, since submitting the form uses POST (by default) method, you get:

No route matches [POST] "/articles/new"

You need to change your form_for and specify the url, like this:
<%= form_for :article, url: articles_path do |f| %>

From the same link your provided:

There's one problem with this form though. If you inspect the HTML
  that is generated, by viewing the source of the page, you will see
  that the action attribute for the form is pointing at /articles/new1.
  This is a problem because this route goes to the very page that you're
  on right at the moment, and that route should only be used to display
  the form for a new article.

1 My emphasis.

A: By default rails new resource route has a GET HTTP verb, not POST. Unless you specified otherwise.

A: Seems like you are using new_article_path or articles/new in the form
<%= form_for :article, url: new_articles_path do |f| %>

Change it to
<%= form_for :article, url: articles_path do |f| %>


text:
Q: Rstudio-server on RHEL 6.5 pandoc error ifluatex.sty not found OS: RHEL 6.5 x64
Rstudio-server Version 0.98.1062
R version 3.1.1 (2014-07-10)
knitr version 1.6
When attempting to knit an Rmarkdown file I get  a failure during the pandoc stage of the compilation:
pandoc: Error producing PDF from TeX source.
! LaTeX Error: File 'ifluatex.sty' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: sty)

Enter file name:
! Emergency stop.

Tried the (9-hour-long) full manual LiveTeX install, just to be sure, and luatex is now installed, but there is still no ifluatex.sty to be found. How do I tell RStudioServer/knitr/pandoc where the installation directory for that file is?

A: Many thanks to Homer White's blog for sending me in the right direction. I'm more or less posting his answer verbatim, with minor modifications for RHEL 6.5 and 2014 LiveTex.
Even the full manual install had not solved the problem. Following Homer's advice, I downloaded from the internet a copy of ifluatex.sty
You can get it either directly or via wget from the CTAN archive.
wget http://www.ctan.org/tex-archive/macros/latex/contrib/oberdiek/ifluatex.dtx
tex ifluatex.dtx

Copy the resulting file into the shared folder for your LaTeX Distribution. In RHEL 6/CentOS for the 2014 LiveTex distribution installed via install-tl this was:
/usr/share/texmf/tex/generic/oberdiek

Easy, right? Next step was to get the framed package:
wget http://mirrors.ctan.org/macros/latex/contrib/framed.zip
unzip framed.zip

This should create a folder in the download location. Now copy the entire folder to the Shared LiveTeX folder for LaTeX:
/usr/share/texmf/tex/latex

Finally, let LiveTeX know it should update its library by running
texhash

PS: Note that I had root access. You might need it as well, of if you're a wheel user, prefix with sudo.

A: Here is quick'n'dirty rpm spec file for those who do not want to install non-packaged files to /usr.
    Name: texlive-rstudio-addon-el6
    Version: 0.1
    Release:        1%{?dist}
    Summary: addon stylesheets for Rstudio pandoc
    Group:  Publishing
    License: LPPL1.3c+
    URL: http://www.ctan.org/tex-archive/macros/latex/contrib/oberdiek/
    Source0: http://www.ctan.org/tex-archive/macros/latex/contrib/oberdiek/ifluatex.dtx
    Source1: http://mirrors.ctan.org/macros/latex/contrib/framed.zip
    BuildRequires:  texlive
    BuildRequires:  texlive-texmf
    BuildRoot:      %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n)
    BuildArch:      noarch

    %description
    Couple styles addons which are required by RStudio pandoc when processing Rmarkdown documents

    %prep
    %setup -q -c -T
    cat %{SOURCE0} > ifluatex.dtx
    unzip %{SOURCE1}

    %build

    %install
    rm -rf %{buildroot} && mkdir -p %{buildroot}
    tex ifluatex.dtx
    mkdir -p %{buildroot}/%{_texmf_main}/tex/generic/oberdiek
    mkdir -p %{buildroot}/%{_texmf_main}/tex/latex/
    cp ifluatex.sty %{buildroot}/%{_texmf_main}/tex/generic/oberdiek
    cp -a framed %{buildroot}/%{_texmf_main}/tex/latex/

    %clean
    rm -rf %{buildroot}

    %post
    [ -x %{_bindir}/texconfig-sys ] && %{_bindir}/texconfig-sys rehash 2> /dev/null

    %files
    %defattr(-,root,root)
    %{_texmf_main}/tex/generic/oberdiek/ifluatex.sty
    %{_texmf_main}/tex/latex/framed/*

    %doc
    %changelog

A: For my fix root was needed and ifluatex and frame file permissions needed to be updated.


text: Q: Post ads in own web and mobile application I'm creating my own website. In the admin side of it I would like to create a feature of posting my own advertisement without going to the actual site (ebay etc.). Is it possible  to integrate different advertisement sites to post ads in my own website or mobile application?


text:
Q: Compare two periodic sets of data At my company, we have two tools (old and new) to measure the same thing (user requests/hits every 5 min).  If you graph the data with time on the X axis and user hits on the Y, the data looks periodic (more requests at peak usage and fewer requests when people are sleeping).  I will have control data sets where I will generate requests, so I will know what the correct curves are supposed to look like.  But I'll also have "production" data sets which have hits for customers where I won't know what the right answer is.
I am trying to verify the accuracy/precision of the new tool by comparing it to the results from the old.  I was thinking of doing a moving average of the two data sets.  I could then compare the moving averages to each other (and  collect things like standard deviation around the moving average).
Is there a better/standard way in statistics for comparing cyclical data? I'm going to write a computer program to do this, so I can do just about anything.

A: The way I solved this was to subtract the measurements from old and new at a particular point in time.  Ideally, the difference should be zero.  Subtraction also cancels out the cyclical nature of the data since they both should have about the same slope.  From there, you can see how closely the trend is to zero, ie, find the mean, the standard deviation, etc of the difference.
You can also roughly detect data quality by counting the number outlier data points.


text:
Q: How to fix the image preprocessing difference between tensorflow and android studio? I'm trying to build a classification model with keras and deploy the model to my Android phone. I use the code from this website to deploy my own converted model, which is a .pb file, to my Android phone. I load a image from my phone and everything worked fine, but the prediction result is totally different from the result I got from my PC.
The procedure of testing on my PC are:

*

*load the image with cv2, and convert to np.float32

*use the keras resnet50 'preprocess_input' python function to preprocess the image

*expand the image dimension for batching (batch size is 1)

*forward the image to model and get the result
Relevant code:
img = cv2.imread('./my_test_image.jpg')
x = preprocess_input(img.astype(np.float32))
x = np.expand_dims(x, axis=0)
net = load_model('./my_model.h5')
prediction_result = net.predict(x)

And I noticed that the image preprocessing part of Android is different from the method I used in keras, which mode is caffe(convert the images from RGB to BGR, then zero-center each color channel with respect to the ImageNet dataset). It seems that the original code is for mode tf(will scale pixels between -1 to 1).
So I modified the following code of 'preprocessBitmap' to what I think it should be, and use a 3 channel RGB image with pixel value [127,127,127] to test it. The code predicted the same result as .h5 model did. But when I load a image to classify, the prediction result is different from .h5 model.
Does anyone has any idea? Thank you very much.
I have tried the following:

*

*Load a 3 channel RGB image in my Phone with pixel value [127,127,127], and use the modified code below, and it will give me a prediction result that is same as prediction result using .h5 model on PC.

*Test the converted .pb model on PC using tensorflow gfile module with a image, and it give me a correct prediction result (compare to .h5 model). So I think the converted .pb file does not have any problem.
Entire section of preprocessBitmap
// code of 'preprocessBitmap' section in TensorflowImageClassifier.java
TraceCompat.beginSection("preprocessBitmap");
        // Preprocess the image data from 0-255 int to normalized float based
        // on the provided parameters.
        bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());

        for (int i = 0; i < intValues.length; ++i) {
            // this is a ARGB format, so we need to mask the least significant 8 bits to get blue, and next 8 bits to get green and next 8 bits to get red. Since we have an opaque image, alpha can be ignored.
            final int val = intValues[i];

            // original
            /*
            floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - imageMean) / imageStd;
            floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - imageMean) / imageStd;
            floatValues[i * 3 + 2] = ((val & 0xFF) - imageMean) / imageStd;
            */

            // what I think it should be to do the same thing in mode caffe when using keras
            floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - (float)123.68);
            floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - (float)116.779);
            floatValues[i * 3 + 2] = (((val & 0xFF)) - (float)103.939);
        }
TraceCompat.endSection();

A: This question is old, but remains the top Google result for preprocess_input for ResNet50 on Android.  I could not find an answer for implementing preprocess_input for Java/Android, so I came up with the following based on the original python/keras code:
/*
    Preprocesses RGB bitmap IAW keras/imagenet

    Port of https://github.com/tensorflow/tensorflow/blob/v2.3.1/tensorflow/python/keras/applications/imagenet_utils.py#L169
    with data_format='channels_last', mode='caffe'

     Convert the images from RGB to BGR, then will zero-center each color channel with respect to the ImageNet dataset, without scaling.
     Returns 3D float array
*/
static float[][][] imagenet_preprocess_input_caffe( Bitmap bitmap ) {
    // https://github.com/tensorflow/tensorflow/blob/v2.3.1/tensorflow/python/keras/applications/imagenet_utils.py#L210
    final float[] imagenet_means_caffe = new float[]{103.939f, 116.779f, 123.68f};

    float[][][] result = new float[bitmap.getHeight()][bitmap.getWidth()][3];   // assuming rgb
    for (int y = 0; y < bitmap.getHeight(); y++) {
        for (int x = 0; x < bitmap.getWidth(); x++) {

            final int px = bitmap.getPixel(x, y);

            // rgb-->bgr, then subtract means.  no scaling
            result[y][x][0] = (Color.blue(px) - imagenet_means_caffe[0] );
            result[y][x][1] = (Color.green(px) - imagenet_means_caffe[1] );
            result[y][x][2] = (Color.red(px) - imagenet_means_caffe[2] );
        }
    }

    return result;
}

Usage with a 3D tensorflow-lite input with shape (1,224,224,3):
Bitmap bitmap = <your bitmap of size 224x224x3>;
float[][][][] imgValues = new float[1][bitmap.getHeight()][bitmap.getWidth()][3];
imgValues[0]=imagenet_preprocess_input_caffe(bitmap);

... <prep tfInput, tfOutput> ...

tfLite.run(tfInput, tfOutput);


text:
Q: .NET CE 3.5 WinForm Hiding main form right after Application.Run(); I found an answer that shows a nice technique to use in order to accomplish this, but the answer was from 2008 and it doesn't appear to be valid today?
It recommended to remove the parameter from Application.Run() in order to manually show/hide form as required. But in .NET Compact Edition 3.5, parameter must be provided.
I have the following code with no luck, form still displays. I wish to hide the main form upon the program starting.
static class Program
{
    public static Form1 MainForm = new Form1();
    [MTAThread]
    static void Main()
    {
        Application.Run(MainForm);
        MainForm.Visible = false;
        MainForm.Hide(); //Also tried this...
    }
}

A: You don't have to use Application.Run() (with or w/o parameter):
static class Program
{
    private static Form1 _mainForm = new Form1();
    public static Form1 MainForm { get { return _mainForm; } }

    [MTAThread]
    static void Main()
    {
        // blablabla

        // do not call this until you want to show main window
        MainForm.ShowDialog();
    }
}


text:
Q: One Wordpress Install, Two Categories. Each Category Gets a Domain Ok here is a setup I am aiming for, hopefully someone knows how to get me there:

*

*One Wordpress Install on www.mainsite.com

*www.mainsite.com will be a landing page that points to two Category links: Work, Play

*Work Category defaults to domain www.worklife.com

*Play Category defaults to www.play.mainsite.com

*Any other Wordpress Pages will maintain www.mainsite.com as domain (ex. www.mainsite.com/contact)

Right now the old blog resides on worklife.com, so I am hoping to prevent the URLs of individual postings from changing (ex. www.worklife.com/2010/01/01/post) as I migrate the install to mainsite.com
For now, I have built the site, and all of the loops and pages are functioning correctly. The only thing left to do is get the domains to play nice so I can make the move.
All of my research keeps pointing me towards creating a network, but I'm hoping there is a way to keep it all running on a single install.
Can it be done?

A: Did you check out WordPress' Multisite feature? Simply put, it allows you to create a network of sites under different sub-directories, sub-domains, or domains. As with your case, each site in the network can work like a category.

A: This may be possible with a combination of website redirection and htaccess.
You can park (or addon) your domain names to their respective categories such as:
www.worklife.com goes to mainsite.com/work
play.mainsite.com goes to mainsite.com/play
Then, use htaccess to rewrite the URLs to show how you would like them to appear using this as a guide.


text:
Q: Cloud run service invoke I would like to know if there is a way to invoke a cloud run service with a service account from a compute engine VM without a JWT token. The idea is to restrict the cloud run service access only from the VM. The request from the VM towards the cloud run service cant have more than one token.So I cannot use the service account jwt in the request

A: Note that there is no way for you to use only one token to authorize your requests (if you plan on communicating with your Cloud Run service through periods of time):

The ID tokens are JSON Web Tokens (JWTs) that expire approximately an hour after creation. If you fetch tokens from the metadata server, you will always get a valid token.

After 1 hour, you need to use another token as the old one is no longer valid. This can be a problem if you manually generate the ID token from gcloud auth for example. You can however, simply fetch them from the metadata server programmatically (see the code samples). This is possible as any Google Cloud services can have access to the metadata server (that includes Cloud Run and Compute Engine). The tokens fetched will still expire, but the refresh is automatically done for you.

"The idea is to restrict the cloud run service access only from the VM."

If your Cloud Run service requires authorization, any user or service account without a run.routes.invoke permission won't be able to access your Cloud Run Service even if they have a valid request. This permission can be found of Cloud Run Invoker role or an IAM role with general access to Cloud Run services such as Cloud Run Admin or Editor role.
In this case, I recommend that you fetch tokens from the metadata server programmatically and then assign the Cloud Run Invoker role to the service account your Compute Engine VM is using as it is the least privilege role needed to invoke a Cloud Run service.

A: In a very special case, you can achieve what you want. You need

*

*To have only 1 VM (the VM that you talk about) in your VPCs of your project

*Set the Cloud Run ingress control to internal. Like this, only the component connected to your VPC will be able to call your Cloud Run service.

Because of the latest condition, you shouldn't connect anything to your VPC

*

*No other VMs in your project

*No external connection to the VPC (cloud VPN, interconnect, VPC Peering)

*No VPC SC

*No serverless VPC connector used by another serverless product

Because you don't want to rely on the identity (The JWT token), you need to rely on the existence in the network.


text:
Q: Azure web app deployment does not follow ASPNETCORE_ENVIRONMENT configuration in selecting appsettings.json We have appsettings.Production.json to define some settings overrides for the appsettings.json. This seems to work when testing locally and setting the launch settings to define ASPNETCORE_ENVIRONMENT.
After deployment with Azure DevOps pipeline and debloymen job the Web App does not work due to clearly using the default appsettings.json. Even setting the ASPNETCORE_ENVIRONMENT to App Service configuration does not have any effect and the value should anyways default to Production.
On the deployed web app, Kudu shows all definitions of ASPNETCORE_ENVIRONMENT to be set to Production as expected with App Settings as well as in environment variables.
Deployment job is defined as follows:
  - deployment: deployWebAPI
    displayName: 'Deploy WebApi'
    dependsOn: fanOut
    variables:
      environmentName: $[ stageDependencies.build.setParameters.outputs['setParametersStep.environmentName'] ]
      appServiceName: $[ stageDependencies.build.setParameters.outputs['setParametersStep.appServiceName'] ]
      resourceGroupName: $[ stageDependencies.build.setParameters.outputs['setParametersStep.resourceGroupName'] ]
    environment: $(environmentName)
    strategy:
      runOnce:
        deploy:
          steps:
          - task: DownloadBuildArtifacts@0
            displayName: 'Download webApp artifact'
            inputs:
              buildType: 'current'
              downloadType: 'single'
              artifactName: $(webAppArtifactName)
              downloadPath: '$(System.ArtifactsDirectory)'
          - task: AzureWebApp@1
            inputs:
              azureSubscription: $(azureSubscription)
              appName: $(appServiceName)
              deployToSlotOrASE: true
              resourceGroupName: $(resourceGroupName)
              package: $(System.ArtifactsDirectory)/**/$(webAppArtifactName)/MyWebApi.zip
              deploymentMethod: zipDeploy

A: The deployment job variable environmentName must be the significant part here. It was defined as follows in beginning of our pipeline definition yml:
variables:
  environmentName: 'test-dev'

This seems to generate a Web.Config with ASPNETCORE_ENVIRONMENT defined as environment variable:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\MyWebApi.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess">
        <environmentVariables>
          <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" />
        </environmentVariables>
      </aspNetCore>
    </system.webServer>
  </location>
</configuration>

Changing that variable to correct value Production fixed the issue.
Some debugging notes:

*

*Logging following variable on startup can be useful as you cannot rely even on Kudu:
hostingContext.HostingEnvironment.EnvironmentName

*Strangely this web.config is in place already in build artifacts on pipeline although local publish package creation with dotnet publish --configuration Release does not set the env variable.

*Direct publish from local env worked, so when in doubt diff your locally created publish package to the one deployed to the server by pipeline.


text:
Q: Forcing laptop to use integrated graphics so that Nvidia GPU can be used for CUDA computing in Ubuntu 20.04 I have a Dell Precision 3541 laptop with Nvidia Quadro P620, using Ubuntu 20.04 and CUDA 11.4. In order to accomplish GPU computing for deep learning tasks, I must:
sudo prime-select intel
sudo reboot
sudo prime-select nvidia

Which forces Xorg to use the Intel integrated graphics upon reboot, and then sudo prime-select nvidia makes the GPU visible for deep learning applications. The problem is that if a reboot occurs without issuing sudo prime-select intel beforehand, then the nvidia card is used for Xorg which makes it unusable for deep learning tasks.
Is there a way to make the nvidia card visible for deep learning tasks without making it the default Xorg output?


text:
Q: Can I loop an Azure Pipelines task on a runtime array variable instead of an array parameter? In Azure Pipelines, I understand that you can define tasks which are iterated based on an array of values provided as a parameter, like follows:
template.yml
parameters:
  param: []

jobs:
- ${{each p in parameters.param}}:
  - script: 'echo ${{ p }}'

pipeline.yml:
steps:
- template: template.yml
  parameters:
    param: ["a", "b"]

However, in this case, you have to know your desired values for param at the pipeline's compile time. In my use case, I want to run the Cache@2 task to create unique cache items for an unknown number of files produced by my build with potentially unknown names.
I know that I can use a bash task to find and list these files, similar to this:
steps:
- bash |
    FILE_LIST=''
    while IFS= read -r; do
      FILE_LIST+=" $REPLY "
    done < <(find ../../build -name '*.desired_extension' -type d | xargs basename)

And then, presumably, I could expose this to other tasks as a variable by doing something along the lines of this (not sure if the array syntax is right, but the intention should be clear):
echo "##vso[task.setvariable variable=fileList]\"[$FILE_LIST]\""

But my plan breaks down here: since the task looping is driven by parameters rather than variables, I don't think I can trigger a dynamic number of Cache@2 tasks based on this runtime-computed variable. Is there some other way I can achieve this goal of creating multiple cache instances where the count isn't known until runtime?

A: It should be possible to do this using output variables and matrix configuration. First you need to create output variables with json content and then pass it to matrix configuration. Please tak a look on this example:
jobs:
- job: JobA
  steps:
  - pwsh: |
      $json="{'job1': {'Work': 'work1'}, 'job2': {'Work': 'work2'}}"
      Write-Host "##vso[task.setvariable variable=targets;isOutput=true]$json"
    name: setTargets
  - script: echo $(setTargets.targets)
    name: echovar

- job: buildSrc
  dependsOn: JobA
  displayName: Build source
  strategy:
    matrix: $[ dependencies.JobA.outputs['setTargets.targets'] ]
  variables:
    targets: $[ dependencies.JobA.outputs['setTargets.targets'] ]
  steps:
  - pwsh: Write-Host "${{ convertToJson(variables) }}"
    displayName: 'Print all variables via expression'

And voila we have dunamiclly created jobs. Now you need to put cache task inside this job, get values provided via matrix confoguration and you should have this solved.


text:
Q: read big data in r with read.big.matrix I am trying to get 1.36 GB data into R, somewhat above 87 million rows and two columns, both numeric. I found the bigmemory and related packages, however am not succeeding with it, not even with reading the data. The original data form is xyz, where I simply changed the file extenstion to txt. I guess it is space delimited.
This is my input:
x <- read.big.matrix("mydata.txt", type="double", header=F,backingfile="mydata.bin",descriptorfile="mydata.desc")

And this error message is returned:
Fehler in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  :
  could not allocate memory (1024 Mb) in C function 'R_AllocStringBuffer'

I also tried
x <- read.big.matrix("mydata.txt",header=F, type="double",sep=" ")

with and without specifying the separator (in which case I read, the separator is guessed). This resulted however in reading only the first column of my data.
(I don't know too much about computers, but I think the one I am working on should be fine enough - CPU 3.3GHz, RAM 8 GB?).
Any ideas what's wrong? Thanks for all hints!


text:
Q: Using RigidBody2D in Unity My buddy and I recently teamed up to create a top-view space shooting game, like asteroids. We've watched a lot of tutorials, and we've managed to work with translate.Transform() and get our object to move.
Now we want to apply force to our ship using RigidBody2D:
Here is a screenshot of our Unity window:

As seen in the screenshot above, we made a Player Ship prefab with a spaceship sprite, a circle collider, a rigidbody 2D and a PlayerThrust script.
In Thrust.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Thrust : MonoBehaviour
{
    // Thrust script components
    public  Rigidbody2D rigidBody;     // GameObject's Rigidbody2D component
    public  float       thrustAmount;  // amount of thrust applied to be defined in unity
    private float       thrustInput;   // float variable to keep track of user input of the 'up' arrow key/'up' axis tilt on joystick

    // Start is called before the first frame update
    void Start() {}

    // Update is called once per frame
    void Update()
    {
        // handle input
        thrustInput = Input.GetAxis("Vertical");  // float ranging from -1.0 to +1.0

        // Debug
        Debug.Log(Vector2.up * thrustInput * thrustAmount);
    }

    // Fixed Update is called every fixed framerate frame
    // use for physics
    void FixedUpdate() {
        // only accelerate forward
        if (thrustInput > 0)
        {
            // Apply thrust in direction ship is facing
            rigidBody.AddRelativeForce(transform.up * thrustInput * thrustAmount);
        }
    }
}

Why doesn't the ship move?
Debug.Log(Vector2.up * thrustInput * thrustAmount); outputs a number which makes sense, it goes up to the thrust amount when the ↑ button is pressed, and goes back to 0.0 when the button is released.

A: Here's a test to see what is going on. 2 scripts. One will spawn a ship (A cube), and the other will use thrusters. Hold down the up key a bit to engage the thrusters, as the cube falls quickly.
This should work on at least Unity 5.6 up to 2020.
#1 -
Create a new blank scene. Make sure you're in 2D view. Don't change anything. Add this script to the camera (All it does is spawn an object):
using System.Collections;
using UnityEngine;

public class SpawnShipTest : MonoBehaviour
{
    private void Start()
    {
        //Create a new scene, put this script on your camera.
        StartCoroutine(SpawnTestObject());
    }

    IEnumerator SpawnTestObject()
    {
        //Spawn object
        var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
        var col = go.GetComponent<BoxCollider>();
        Component.Destroy(col);

        yield return new WaitForSeconds(.2f);

        go.transform.position = new Vector3(0f, 0f, -2f);
        go.AddComponent<ShipThrustTest>();

        go.AddComponent<Rigidbody2D>();

    }
}

#2 -
Add this script in your projects folder somewhere (then press play, and view the Game Window):
using UnityEngine;

public class ShipThrustTest: MonoBehaviour
{
    // Thrust script components
    public Rigidbody2D rigidBody;
    public float thrustAmount;   // amount of thrust applied to be defined in unity
    private float thrustInput;    // float variable to keep track of user input of the 'up' arrow key/'up' axis tilt on joystick

    void Start()
    {
        rigidBody = GetComponent<Rigidbody2D>();
        thrustAmount = 10f;
    }

    void Update()
    {
        thrustInput = Input.GetAxis("Vertical");
    }

    void FixedUpdate()
    {
        if (thrustInput > 0)
        {
            rigidBody.AddRelativeForce(transform.up * thrustInput * thrustAmount * 2f,  ForceMode2D.Force);
        }
    }
}

A: Thanks for the help.
The main thing that was wrong was that we were using Rigidbody2D with 3-D objects, and not simply Rigidbody...we got confused by the fact that the game was a "2-D" game, even though our assets were 3 dimensional.
We also never thought about using rigidBody = GetComponent<Rigidbody2D>(); or using the parameter ,  ForceMode2D.Force. Those were really good tips. Great test scripts @Kale_Surfer_Dude !


text:
Q: Create a list of check box by using the records from MySQL datebase as values I have asked this question before but no one could find the solution, so I'm asking again with updated code to see if anyone else can help me.
As the title says I am trying to create check boxes in my site. However, the values will come from the mysql database. I can't figure out where I have gone wrong as my php code wont execute.
I have a database called "my computer", table named campus and it has the 2 columns id and room.
Below is the screenshot of my database and the output of the code in the web browser:

<?PHP

$hostname = "localhost";
$username = "root";
$password = "root";
$databaseName = "my computer";

$connect = mysqli_connect($hostname, $username, $password, $databaseName);

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

?>

<html>
<body>

<form name="aform">

Choose a room:

    <?php

    $sql = "SELECT * FROM `campus`";
    $result = mysqli_query($sql);
    mysqli_query($connect, $sql);

    while ($line = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

    ?>

    <input type="checkbox" name="car" value="<?php echo $line['room'];?>" />

    <?php
    }
    ?>

</form>

</body>
</html>

A: I look at your code and think the php block after "Choose a room" can be improved like this:
<?php
  $s = '';
  $j = 0;
  if ($q = $dbCon->query("SELECT * FROM `campus`")) {
    while ($line = $q->fetch_assoc()) {
      $s.= '<input type="checkbox" name="car'.$j.'" value="'.$line['room'].'">';
    }
  }
  echo $s;
?>

The $j variable is to avoid having all the inputs with same name.


text:
Q: What can prevent an attribute from being created in rails? Everything doesn't seem to be too hard but I've spent hours yet still can't get it working.
If I do Category.create(:name => "foo") in the rails console, a new category with its name gets created beautifully.
(0.2ms)  begin transaction
SQL (0.3ms)  INSERT INTO "categories" ("created_at", "name", "updated_at") VALUES (?, ?, ?)  [["created_at", "2014-09-16 15:40:01.218700"], ["name", "foo"], ["updated_at", "2014-09-16 15:40:01.218700"]]
(14.5ms)  commit transaction
=> #<Category id: 38, created_at: "2014-09-16 15:40:01", updated_at: "2014-09-16 15:40:01", name: "foo">

However, if I do it on the pages something goes wrong. My Category model has only one attribute which is "name", and I want all of them to be listed on my category index page.
<% @categories.each do |category| %>

        <%= category.name %>

        <% category.products.each do |product| %>
            <%=  product.title %>

        <% end %>

<% end %>
<%= link_to "Create new category", categories_new_path %>

If I create a new category with its name in the console, it appears on the page with its name with no problem. But if I create it on the page, there's a category created with its name attribute being "nil". So please help me figure out where the problem is. I'm quite new to rails.
Here's my categories_controller.erb
class CategoriesController < ApplicationController
  # load_and_authorize_resource
  def new
    @category = Category.new
  end

  def create
    @category = Category.new(params[:name])
    if @category.save
        redirect_to categories_path
    else
        render 'new'
    end
  end

  def index
    @categories = Category.all
  end
end

And here's my new.html.erb

New Category

<%= form_for(@category) do |f| %>

    <%= f.label :name %>

    <%= f.text_field :name %>

    <%= f.submit %>

<% end %>
<%= link_to 'Back', categories_path %>

Here's what appears in the server after I hit the submit button.
Started POST "/categories?locale=en" for 127.0.0.1 at 2014-09-17 00:02:42 +0800
Processing by CategoriesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ZdXcC/uEMA/jhGoGhYvp4lSHHfi/tmlm3CovJcYizJ0=", "category"=>{"name"=>"fwefewfw"}, "commit"=>"Create Category", "locale"=>"en"}
(0.1ms)  begin transaction
SQL (0.2ms)  INSERT INTO "categories" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2014-09-16 16:02:42.806041"], ["updated_at", "2014-09-16 16:02:42.806041"]]
(21.2ms)  commit transaction

Note that there's no "name" being inserted in the sql statement.
I sense I missed something that is very basic. Well forgive me for being a newbie and thank you for the help!!

A: Looking at your tags, i think you are using rails 4 so you need to permit your attributes first. You can do it by this:
class CategoriesController < ApplicationController
  # load_and_authorize_resource

  def create
    @category = Category.new(category_params)
    if @category.save
      redirect_to categories_path
    else
      render 'new'
    end
  end

  private
    def category_params
      params.require(:category).permit(:name)
    end
end

For details checkout Strong Parameters in Rails

A: It should be:
@category = Category.new(params[:category])

If you're on Rails 4, you should use the strong params and add the following method to your controller:
def category_params
   params.require(:category).permit(:name)
end

And then change the Category.new line to:
@category = Category.new(category_params)

That's the new "safe" way to accept user-generated data in Rails models, and works really well once you get used to it.


text:
Q: Booting Linux minimally I am trying to boot just linux itself. It's mostly for the learning experience.
I got a small HDD with only one ext4 partition looking like this:
/bin/bash
/dev/console
/boot/vmlinuz
/boot/grub/grub.cfg
/boot/grub/i386-pc/*.mod

bash is version 3.0 statically linked, vmlinuz is version 3.16.2, and grub is version 2.00rc1. grub.cfg looks like this:
insmod linux
insmod search
insmod ext2
insmod part_msdos
set timeout=5

menuentry 'Linux' {
    set the_root_uuid=a0225737-71c9-4d60-81e2-275dc078c3c1
    search --fs-uuid $the_root_uuid --set=root
    linux /boot/vmlinuz root=$root ro init=/bin/bash
}

when booting I get the following:
kernel panic: VFS could not open device root (hd0,msdos1), or unknown block(0,0) error -6

What am I missing?

A: Your kernel doesn't include the drivers needed to access the root filesystem (e.g. the ahci sata module and possibly also the ext4 module).
You either need to provide an initrd/initramfs that loads the appropriate modules or you need to compile a kernel that includes the necessary drivers statically (not as modules).
Since your rootfs doesn't include tools to load modules anyway, I suggest you build a non-modular kernel.