text:
Q: Put pairwise differences of matrix rows in 3-d array I have a matrix Y of shape (n, d). I already calculated the pairwise row-differences in the following way:
I, J = np.triu_indices(Y.shape[0], 0)
rowDiffs = (Y[I, :] - Y[J, :])

No i want to create a 3d-array, containing the differences of the rows i and j of Y at position (i,j, :). How would you do it?
The aim of it is to replace this inefficient loop:
   for i in range(Y.shape[0]):
        for j in range(Y.shape[0]):
            C[i,:] = C[i,:] + W[i, j] * (Y[i, :]-Y[j, :])

A: I have found some success with this:
row_diffs = Y[:, np.newaxis] - Y

Y[:, np.newaxis] creates a version of Y with dimensions (n, 1, 3). Then, the subtraction uses broadcasting to do what you want.
Unfortunately, I've found this approach to be relatively slow and I haven't yet found a better way.
Full example:
>>> x = np.random.randint(10, size=(4, 3))
>>> x
array([[4, 0, 8],
       [8, 5, 3],
       [4, 1, 6],
       [2, 2, 4]])
>>> x[:, np.newaxis] - x
array([[[ 0,  0,  0],
        [-4, -5,  5],
        [ 0, -1,  2],
        [ 2, -2,  4]],

       [[ 4,  5, -5],
        [ 0,  0,  0],
        [ 4,  4, -3],
        [ 6,  3, -1]],

       [[ 0,  1, -2],
        [-4, -4,  3],
        [ 0,  0,  0],
        [ 2, -1,  2]],

       [[-2,  2, -4],
        [-6, -3,  1],
        [-2,  1, -2],
        [ 0,  0,  0]]])

A: Here's a vectorized approach using broadcasting and np.einsum -
np.einsum('ij,ijk->ik',W,Y[:,None] - Y)

Runtime test -
In [29]: def original_app(Y,W):
    ...:     m = Y.shape[0]
    ...:     C = np.zeros((m,m))
    ...:     for i in range(Y.shape[0]):
    ...:         for j in range(Y.shape[0]):
    ...:             C[i,:] = C[i,:] + W[i, j] * (Y[i, :]-Y[j, :])
    ...:     return C
    ...:

In [30]: # Inputs
    ...: Y = np.random.rand(100,100)
    ...: W = np.random.rand(100,100)
    ...:

In [31]: out = original_app(Y,W)

In [32]: np.allclose(out, np.einsum('ij,ijk->ik',W,Y[:,None] - Y))
Out[32]: True

In [33]: %timeit original_app(Y,W)
10 loops, best of 3: 70.8 ms per loop

In [34]: %timeit np.einsum('ij,ijk->ik',W,Y[:,None] - Y)
100 loops, best of 3: 4.01 ms per loop


text:
Q: How to force Doctrine to read new mapping information I am working on a Symfony project that uses the Sonata bundle. I have just added the following to my Page.orm.xml file:
    <many-to-many field="equivalents" target-entity="AppBundle\Entity\Equivalent">
        <cascade>
            <cascade-all />
        </cascade>
        <join-table name="page_equivalent">
                <join-columns>
                    <join-column name="page_id" referenced-column-name="id" />
                </join-columns>
                <inverse-join-columns>
                    <join-column name="equivalent_id" referenced-column-name="id" unique="true" />
                </inverse-join-columns>
        </join-table>
    </many-to-many>

... and I find that when I run app/console doctrine:schema:update --dump-sql I get a message telling me that my schema is up to date, even though it clearly is not.
Am I misusing this command? If so, is there another way of generating the necessary new table?

A: This turned out to be a duplicate of Symfony doctrine:schema:update not working
I found that running php app/console doctrine:cache:clear-metadata solved the problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to tell RestKit which mapping to use when using sendObject I'm new to RestKit so this question may be dumb: When using [objectManager sendObject:...], how do I tell RestKit which mapping it should use for the result? More specific: I am sending GET and POST data to a server which in return responds with a JSON encoded message:
{"purchaseresult":{"status":"ok","errormsg":""}}

The Objective-C code I use looks like this:
RKObjectMapping *purchaseResultMapping = [RKObjectMapping mappingForClass:[PurchaseResult class]];
[purchaseResultMapping mapKeyPathsToAttributes:@"status", @"status", @"errormsg", @"errorMessage",nil];
[objectManager.mappingProvider setMapping:purchaseResultMapping forKeyPath:@"purchaseresult"];
[[RKObjectManager sharedManager].mappingProvider setErrorMapping:purchaseResultMapping];

[objectManager sendObject:queryParams toResourcePath:@"/purchase/post" usingBlock:^(RKObjectLoader* loader) {
    loader.method = RKRequestMethodPOST;
    loader.resourcePath = @"/purchase/post";
    loader.params = queryParams;
    loader.objectMapping = purchaseResultMapping;
}];

This returns an RestKit error:
restkit.network:RKObjectLoader.m:216 Encountered errors during mapping: Expected an object mapping for class of type '__NSDictionaryI', provider returned one for 'PurchaseResult'
Any ideas what I am doing wrong here?
Thanks
      Christian

A: The object that you're sending is a NSDictionary so RestKit is looking for an object mapping for an NSDictionary but you are providing a PurchaseResult mapping. If you send an instance of PurchaseResult or provide your mapping for the NSDictionary class then this error should be avoided.
An alternative to this would be as follows:
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/purchase/post" usingBlock:^(RKObjectLoader *loader) {
  loader.delegate = **Your loader delegate here**;
  loader.method = RKRequestMethodPOST;
  loader.params = queryParams;
}];

Just make sure you've defined your mapping for the objects coming back in and you should be good.


text:
Q: Dynamic columns from a LEFT JOIN in SQL Server I have a problem and I hope you can guide me, I have 3 tables in sql server with the following characteristics:
Table Invoice
ID         Folio
------------------
1          101010
2          202020

Table Additional
ID           Name
--------------------------
1            Order Number
2            Branch

Table AdditionalInvoice:
ID_INVOICE           ID_ADDITIONAL          VALUE
------------------------------------------------------------
1                    1                      1234/1
1                    2                      NORTH
2                    1                      5678/9
2                    2                      SOUTH

The table 3 depends on table 1 and 2 and the ratio is one to many, I look for the following result:
Query results
ID          Folio          Order Number          Branch
------------------------------------------------------------
1           101010         1234/1                NORTH
2           202020         5678/9                SOUTH

Investigating I can use PIVOT or CROSS APPLY, but I find myself a little lost :( or someone who has another solution to the problem of dynamic columns?

A: While this can be done with PIVOT and/or CROSS APPLY, I would just use conditional aggregation, which is an efficient and cross-database solution:
select
    i.id,
    i.folio,
    max(case when a.name = 'Order Number' then ai.value end) OrderNumber,
    max(case when a.name = 'Branch' then ai.value end) Branch
from Invoice i
inner join AdditionalInvoice ai on ai.id_invoice = i.id
inner join Additional a on a.id = ai.id_additional
group by i.id, i.folio

Note: rereading your question I notice a mention of dynamic columns at the end.
Please note that the above query (or any other pure-sql solution, PIVOT and CROSS APPLY included) only works for a fixed set of columns. This is because a pure SQL query can only returned a pre-defined, fixed set of columns. If you want a dynamic solution, then you need dynamic SQL (that is: prepare a query string, then execute it).
On the other hand, the above statement can easily be extended to handle more values from the additional table, by adding max(case when ... then ... end) expressions.


text:
Q: How Do I Decrease the Size of a Preexisting Swap File Without Removing it? After seeing this post: How do I increase swapfile in Ubuntu 18.04?, I was wondering, how do I decrease the size of the swap file without removing it?

A:
how do I decrease the size of the swap file without removing it?

This question is rather irrelevant. Swap space must be taken out of use before changing it. The command sudo fallocate -l 4G /swapfile (with an adjusted size) will overwrite your existing swapfile if you do not delete it first.


text:
Q: Графика в Windows Forms приложении (построение геометрических фигур) Мне нужно построить квадрат, на одной стороне которого, как на основании, построен равносторонний треугольник со стороной a.
Как составить формулу для построения равностороннего треугольника по заданной стороне и заданным координатам квадрата(чтобы треугольник строился без искажения),код:
namespace Project1 {

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;

    /// <summary>
    /// Сводка для MyForm
    /// </summary>
    public ref class MyForm : public System::Windows::Forms::Form
    {
    public:
        MyForm(void)
        {
            InitializeComponent();
            //
            //TODO: добавьте код конструктора
            //
            Count = -1; // количество прямоугольников (не более 25)
            Koord = gcnew array<int>(4); // координаты прямоугольников
            tr = gcnew array<int>(4);

        }

    protected:
        /// <summary>
        /// Освободить все используемые ресурсы.
        /// </summary>
        ~MyForm()
        {
            if (components)
            {
                delete components;
            }
        }
    private:int Count; // количество фигур
            array <int> ^Koord; // координаты
            array <int>^tr;
    private: System::Windows::Forms::PictureBox^  pictureBox1;

    private: System::Windows::Forms::Label^  label1;
    private: System::Windows::Forms::Button^  button1;

    private: System::Windows::Forms::Label^  label2;

    private: System::Windows::Forms::Label^  label3;
    private: System::Windows::Forms::Label^  label4;
    private: System::Windows::Forms::NumericUpDown^  numericUpDown1;
    private: System::Windows::Forms::NumericUpDown^  numericUpDown2;
    private: System::Windows::Forms::NumericUpDown^  numericUpDown3;

    protected:

    protected:

    protected:

    protected:

    private:
        /// <summary>
        /// Обязательная переменная конструктора.
        /// </summary>
        System::ComponentModel::Container ^components;

    #pragma region Windows Form Designer generated code

        /// <summary>
        /// Требуемый метод для поддержки конструктора — не изменяйте
        /// содержимое этого метода с помощью редактора кода.
        /// </summary>
        void InitializeComponent(void)
        {
            this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox());
            this->label1 = (gcnew System::Windows::Forms::Label());
            this->button1 = (gcnew System::Windows::Forms::Button());
            this->label2 = (gcnew System::Windows::Forms::Label());
            this->label3 = (gcnew System::Windows::Forms::Label());
            this->label4 = (gcnew System::Windows::Forms::Label());
            this->numericUpDown1 = (gcnew System::Windows::Forms::NumericUpDown());
            this->numericUpDown2 = (gcnew System::Windows::Forms::NumericUpDown());
            this->numericUpDown3 = (gcnew System::Windows::Forms::NumericUpDown());
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->BeginInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown1))->BeginInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown2))->BeginInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown3))->BeginInit();
            this->SuspendLayout();
            //
            // pictureBox1
            //
            this->pictureBox1->Location = System::Drawing::Point(12, 12);
            this->pictureBox1->Name = L"pictureBox1";
            this->pictureBox1->Size = System::Drawing::Size(365, 177);
            this->pictureBox1->TabIndex = 0;
            this->pictureBox1->TabStop = false;
            this->pictureBox1->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &MyForm::pictureBox1_Paint);
            //
            // label1
            //
            this->label1->AutoSize = true;
            this->label1->Location = System::Drawing::Point(202, 205);
            this->label1->Name = L"label1";
            this->label1->Size = System::Drawing::Size(176, 13);
            this->label1->TabIndex = 5;
            this->label1->Text = L"Задайте сторону треугольника а:";
            //
            // button1
            //
            this->button1->Location = System::Drawing::Point(11, 259);
            this->button1->Name = L"button1";
            this->button1->Size = System::Drawing::Size(185, 23);
            this->button1->TabIndex = 6;
            this->button1->Text = L"нарисовать ";
            this->button1->UseVisualStyleBackColor = true;
            this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click);
            //
            // label2
            //
            this->label2->AutoSize = true;
            this->label2->Location = System::Drawing::Point(202, 244);
            this->label2->Name = L"label2";
            this->label2->Size = System::Drawing::Size(246, 13);
            this->label2->TabIndex = 11;
            this->label2->Text = L"Задайте координаты расположения квадрата: ";
            //
            // label3
            //
            this->label3->AutoSize = true;
            this->label3->Location = System::Drawing::Point(216, 269);
            this->label3->Name = L"label3";
            this->label3->Size = System::Drawing::Size(14, 13);
            this->label3->TabIndex = 14;
            this->label3->Text = L"X";
            //
            // label4
            //
            this->label4->AutoSize = true;
            this->label4->Location = System::Drawing::Point(263, 269);
            this->label4->Name = L"label4";
            this->label4->Size = System::Drawing::Size(14, 13);
            this->label4->TabIndex = 15;
            this->label4->Text = L"Y";
            //
            // numericUpDown1
            //
            this->numericUpDown1->Location = System::Drawing::Point(240, 221);
            this->numericUpDown1->Name = L"numericUpDown1";
            this->numericUpDown1->Size = System::Drawing::Size(37, 20);
            this->numericUpDown1->TabIndex = 16;
            //
            // numericUpDown2
            //
            this->numericUpDown2->Location = System::Drawing::Point(205, 285);
            this->numericUpDown2->Name = L"numericUpDown2";
            this->numericUpDown2->Size = System::Drawing::Size(37, 20);
            this->numericUpDown2->TabIndex = 17;
            //
            // numericUpDown3
            //
            this->numericUpDown3->Location = System::Drawing::Point(248, 285);
            this->numericUpDown3->Name = L"numericUpDown3";
            this->numericUpDown3->Size = System::Drawing::Size(37, 20);
            this->numericUpDown3->TabIndex = 18;
            //
            // MyForm
            //
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(450, 321);
            this->Controls->Add(this->numericUpDown3);
            this->Controls->Add(this->numericUpDown2);
            this->Controls->Add(this->numericUpDown1);
            this->Controls->Add(this->label4);
            this->Controls->Add(this->label3);
            this->Controls->Add(this->label2);
            this->Controls->Add(this->button1);
            this->Controls->Add(this->label1);
            this->Controls->Add(this->pictureBox1);
            this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::FixedSingle;
            this->Name = L"MyForm";
            this->Text = L"MyForm";
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->EndInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown1))->EndInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown2))->EndInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown3))->EndInit();
            this->ResumeLayout(false);
            this->PerformLayout();

        }
    #pragma endregion

    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
        Koord[0] = int(numericUpDown1->Value);
        Koord[1] = int(numericUpDown2->Value);
        Koord[2] = int(numericUpDown3->Value);
        tr[0] = int(numericUpDown1->Value);
        tr[1] = int(numericUpDown2->Value);
        tr[2] = int(numericUpDown3->Value);
        pictureBox1->Refresh();

    }
    private: System::Void pictureBox1_Paint(System::Object^  sender, System::Windows::Forms::PaintEventArgs^  e) {
        int X1 = Koord[1];
        int Y1 = Koord[2];
        int X2 = Koord[0];
        int Y2 = Koord[0];
        int x1 = tr[1];
        int y1 = tr[2];
        int x2 = tr[0];
        int y2 = tr[0];
        int x3 = tr[1] + tr[0] + tr[1]/2 + tr[0]/2;
        int y3 = double((tr[0] + tr[2]/2));
        e->Graphics->DrawRectangle(Pens::Black, X1, Y1, X2, Y2);
        e->Graphics->FillRectangle(Brushes::Yellow, X1, Y1, X2, Y2);
        e->Graphics->DrawPolygon(Pens::Black, gcnew array<Point>{
            Point((x1 + x2), y1),
                Point((x1 + x2), (y1 + y2)),
                Point(x3, y3)
        });
        e->Graphics->FillPolygon(Brushes::Green, gcnew array<Point>{
            Point((tr[1] + tr[0]), tr[2]),
                Point((tr[1] + tr[0]), (tr[2] + tr[0])),
                Point(x3, y3)

        });
        String^st1 = "Квадрат с равносторонним треугольником";
        e->Graphics->DrawString(st1,this->Font,Brushes::Black,tr[0],tr[0]+60)
        ;

    }

    };
}

A: Треугольник можно построить с помощью DrawPolygon (и заполнить соответственно FillPolygon)
Если даны координаты двух вершин равностороннего треугольника (x1,y1) и (x2,y2), то координаты третьей стороны рассчитать несложно:
//вектор разности
dx = (x2 - x1)
dy = (y2 - y1)
//средняя точка
mx = (x1 + x2) / 2
my = (x1 + x2) / 2
//перпендикулярный вектор
px = -dy
py = dx
//третья вершина
x3 = mx + px * Sqrt(3) / 2
y3 = my + py * Sqrt(3) / 2
// ещё зеркальная вершина, если знаки + заменить на -


text:
Q: Is a destructor the right place to mark the end of a script's execution? I'm doing some broad performance investigation in an application I maintain and I've set up a simple solution to track the execution time of requests, but I'm unable to find information to verify if this is going to be satisfyingly accurate.
This appears to have netted some good information and I've already eliminated some performance issues as a result, but I'm also seeing some confusing entries that make me question the accuracy of the recorded execution time.
Should I add an explicit method call at the end of each calling script to mark the end of its execution or is this (rather tidy) approach using the destructor good enough?
The calling code at the top of the requested script:
if( file_exists('../../../bench') )
{
    require('../../../includes/classes/Bench.php');
    $Bench = new Bench;
}

And here is the class definition (reduced for clarity):
require_once('Class.php');

class Bench extends Class
{
    protected $page_log = 'bench-pages.log';
    protected $page_time_end;
    protected $page_time_start;

    public function __construct()
    {
        $this->set_page_time_start();
    }

    public function __destruct()
    {
        $this->set_page_time_end();
        $this->add_page_record();
    }

    public function add_page_record()
    {
        $line = $this->page_time_end - $this->page_time_start.','.
                base64_encode(serialize($_SERVER)).','.
                base64_encode(serialize($_GET)).','.
                base64_encode(serialize($_POST)).','.
                base64_encode(serialize($_SESSION))."\n";

        $fh = fopen( APP_ROOT . '/' . $this->page_log, 'a' );
        fwrite( $fh, $line );
    }

    public function set_page_time_end()
    {
        $this->page_time_end = microtime(true);
    }

    public function set_page_time_start()
    {
        $this->page_time_start = microtime(true);
    }
}

A: What you need to do is use Xdebug.  It is very simple once you set it up and don't have to change anything about your code to get full coverage of what took how long.


text:
Q: android:gravity fails on API 18+ I have some TextViews on my app, I don't know why but the android:gravity attribute is not centering the text content where it should be on devices running the API 18+ (4.3+).
There is the code I use on my custom TextView, this is a child of RelativeLayout:
<com.package.custom.CustomTextFont
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/seekbar"
    android:layout_alignParentLeft="true"
    android:layout_alignTop="@+id/seekbar"
    android:layout_marginLeft="@dimen/margin_tiny_double"
    android:layout_toLeftOf="@+id/seekbar"
    android:gravity="center_vertical|left"
    android:paddingRight="@dimen/margin_tiny"
    android:text="@string/text1"
    android:textColor="@color/black"
    android:textSize="@dimen/size_text_normal" />

This code should take the edges of this TextView and align it to the top and bottom and put it to the Left of the SeekBar, this is working, but the TextView gets big, so with android:gravity I center the text to the center and left from it self. It works, but I don't know why, the text is not centered at center|left on devices running android 4.3 and 4.4. This issue can be reproduced on real devices and as well on the layout preview (Graphic layout) of Eclipse.
There is any changes made on API 18+ or on android:gravity that I'm missing?
PS: I'm targetting the API 19 on the project and on AndroidManifest.xml
PS2: My TextView is custom just to set an external font.tff
This is how it looks like on API 17-

This is how it looks like on API 18+

Thanks in advance!
= UPTADATE =
On my Manifest, I changed the android:targetSdkVersion to 17 instead of 19 and the problem disappeared, but this is a "trick", not a solution, what can I do since it could be an issue from the API ? And yes, I have the latest version of the API 18 and 19 (today, 01/30/2014).

A: This appears to be a known issue in API 18+:
https://code.google.com/p/android/issues/detail?id=59368
https://code.google.com/p/android/issues/detail?id=59700
The problem seems to occur when a TextView is part of a scrollable container (e.g. ListView), making the view ignore the vertical gravity for some reason (some sources suggest this has to do with the TextView being the child of a RelativeLayout, though it's been my experience that this can happen even when no such layout is involved).
A possible workaround (albeit not a particularly elegant one), would be to wrap the TextView in a LinearLayout.  You can then use "layout_gravity" on the TextView to center it inside the LinearLayout, instead of relying on "gravity" (just make sure to wrap_content so the text itself is properly centered).
E.g., in your example:
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignBottom="@+id/seekbar"
    android:layout_alignParentLeft="true"
    android:layout_alignTop="@+id/seekbar"
    android:layout_toLeftOf="@+id/seekbar"
    android:layout_marginLeft="@dimen/margin_tiny_double" >

    <com.package.custom.CustomTextFont
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:gravity="left"
        android:paddingRight="@dimen/margin_tiny"
        android:text="@string/text1"
        android:textColor="@color/black"
        android:textSize="@dimen/size_text_normal" />

</LinearLayout>

This method does have the disadvantage of adding an otherwise-unnecessary level to your view hierarchy, but it currently seems to be the only way around this (other than reverting to an earlier API level).
Also see similar question at:
Android sdk 18 TextView gravity doesn't work vertically

A: Your textview height is "wrap_content", which means the height of the textview will be the same as the height of the text. If you change the background of the textview to black, it might be easier to see the bounds of the view. I'm guessing you'll find that the textview doesn't have as much height as you expect.
Try setting the height of the textview to match_parent. You can wrap the textview inside another view if needed and modify its height as appropriate.


text:
Q: Return custom response to successful POST request in django rest framework I want to return a custom response to the user when they hit the API with a POST request and it's a success. Here are the code snippets :
views.py
class BlogPostAPIView(mixins.CreateModelMixin,generics.ListAPIView):
    # lookup_field = 'pk'
    serializer_class = BlogPostSerializer
    def get_queryset(self):
        return BlogPost.objects.all()
    def perform_create(self, serializer):
        serializer.save(user=self.request.user)
    def post(self,request,*args,**kwargs):
        return self.create(request,*args,**kwargs)

urls.py
app_name = 'postings'
urlpatterns = [
    re_path('^$', BlogPostAPIView.as_view(),name='post-create'),
    re_path('^(?P<pk>\d+)/$', BlogPostRudView.as_view(),name='post-rud'),
]

Right now it's returning the details of the post request as successful response, is there any way I can return some other response based on my own custom queryset?

A: You can write custom api on views.py. I want to for example;
from rest_framework.views import APIView
from rest_framework.response import Response

class Hello(APIView):
    @csrf_exempt
    def post(self, request):
        content = "Hi"
        type = "message"
        return Reponse({"content":content,"type":type})

and than define url.
app_name = 'postings'
urlpatterns = [
    re_path('^$', BlogPostAPIView.as_view(),name='post-create'),
    re_path('^(?P<pk>\d+)/$', BlogPostRudView.as_view(),name='post-rud'),
    re_path('^hello/$', Hello.as_view(),name='Hello'),
]

That's it.
Also you can manage permessions : https://www.django-rest-framework.org/api-guide/permissions/#setting-the-permission-policy
and you can use serializer on views : https://www.django-rest-framework.org/api-guide/serializers/#saving-instances


text:
Q: Why do we use cross entropy instead of Kullback-Leibler divergence as loss function? Why do we use forward KL divergence and not the reverse? Was just having a discussion with a colleague, and realize I have the following questions about cross-entropy that is typically used in classification problems.

*

*We know that cross entropy contains both the entropy of the ground truth and the forward KL divergence between ground truth and prediction. From a minimizing loss function perspective, minimizing cross-entropy should be equivalent to minimizing the forward KL divergence. Why do we use cross entropy and not just the forward KL divergence?

*What is the intuition behind using forward KL and not the reverse KL? (or JS divergence that is symmetrical?)
I have seen another post discussing this very topic, where my takeaway is that because ground truth has hard 0s and we want to avoid encountering log(0) in loss function, so we stick with $true \times log(pred)$. Is this indeed the broadly accepted view?
Thanks!


text:
Q: Show the equivalence of arc length definitions Definition 1:

Let $r: [a,b] \to \Bbb R^d$ be a continuous differentiable function. Then the arc length is given by $$L(r) = \int_a^b || r'(t) || \, dt$$

Definition 2:

Let $r: [a,b] \to \Bbb R^d$ be a continuous function. Then the arc length is given by $$ V(r) = \sup_P \sum_{k=1}^n || r(x_k)-r(x_{k-1}) ||$$ where the supremum is taken over all partitions $P = \{a=x_0 \lt x_1 \lt \ldots \lt x_n = b \}$ of $[a,b]$.

How can I show that for a continuous differentiable $r(t)$ the two definitions are equivalent, i.e. $L(r)=V(r)$?
What I've done so far:
I found this question, which shows that I can convert the supremum to a limit
$$V(r) = \sup_P \sum_{k=1}^n || r(x_k)-r(x_{k-1}) || = \lim_{n \to \infty} \sum_{k=1}^n || r(x_k)-r(x_{k-1}) ||$$
by choosing an appropriate sequence of partitions $P_n$ of which I take the $x_k$'s. This gives
$$ \lim_{n \to \infty} \sum_{k=1}^n || r(x_k)-r(x_{k-1}) || = \lim_{n \to \infty} \sum_{k=1}^n || \frac{r(x_k)-r(x_{k-1})}{x_k-x_{k-1}} || (x_k-x_{k-1})$$
Now I somehow need to show that
$$\lim_{n \to \infty} \sum_{k=1}^n || \frac{r(x_k)-r(x_{k-1})}{x_k-x_{k-1}} || (x_k-x_{k-1}) = \int_a^b ||r'(t)|| \, dt$$
How can I justify this step of converting the sum to an intergral and taking the limit of the inside simultaneously?

A: Claim. For a parametrized curve $\gamma \in \mathcal C^1([a,b], \Bbb R^d)$, we have
$$\bbox[5px,border:2px solid #C0A000]{
\lim_{n\to\infty} \sum_{i=1}^n \| \gamma(x_{i,n})-\gamma(x_{i-1,n})\| = \int_a^b \|\gamma'(x)\| \,\mathrm dx,
}$$
where $x_{i,n} := a \cdot (1-\frac in) + b\cdot\frac in$.
Proof. Note that the left hand side equals
\begin{equation}
\lim_{n\to\infty}
\underbrace{
\sum_{i=1}^n \left\| \frac{\gamma(x_{i,n})-\gamma(x_{i-1,n})}{\frac{b-a}n}\right\|\cdot {\frac{b-a}n}
}_{=: \kappa_n}
\end{equation}
and observe that $x_{i,n}-x_{i-1,n}=\frac{b-a}n$.
By definition of the derivative, which is continuous on a compact interval and thus also uniformly contiuous, there exists a $\delta$ for every $\varepsilon > 0$ such that whenever $\frac{b-a}n < \delta$,
$$\left\|\bigg\|\frac{\gamma(x_{i,n})-\gamma(x_{i-1,n})}{\frac{b-a}n}\bigg\|-\bigg\|\gamma'(x_{i,n})\bigg\|\right\| < \varepsilon.$$
In particular, for any $\varepsilon > 0$, we have
\begin{equation}\tag{*} \label{*}
\left\|\rule{0cm}{1cm}
\underbrace{
  \sum_{i=1}^n
  \left\|
  \frac{\gamma(x_{i,n})-\gamma(x_{i-1,n})}{\frac{b-a}n}
  \right\|
  \cdot\frac{b-a}n
}_{=\kappa_n}
-\underbrace{
  \sum_{i=1}^n
  \Big\|\gamma'(x_{i,n})\Big\|\cdot\frac{b-a}n
}_{=:\rho_n}
\right\|
< \varepsilon \cdot (b-a)
\end{equation}
whenever $n>\frac{b-a}\delta$ (note that $\delta$ depends on $\varepsilon$).
Since $\rho_n$ are just Riemann approximation sums, we have $\lim_{n\to\infty} \rho_n = \int_a^b \|\gamma'(x)\| \,\mathrm dx$.
By \eqref{*}, we can conclude that $\lim_{n\to\infty} \kappa_n = \lim_{n\to\infty} \rho_n$, which proves our claim. $\square$


text:
Q: Degrees of freedom "The number of degrees of freedom is a measure of how certain we are that our sample population is representative of the entire population - the more degrees of freedom, usually the more certain we can be that we have accurately sampled the entire population."
Can someone please explain this statement?

A: There is a sentence prior to the passage quoted by the OP that I believe helps to interpret this:

In statistics, the number of degrees of freedom (d.o.f.) is the number
  of independent pieces of data being used to make a calculation. (...).
  The number of degrees of freedom is a measure of how certain we are
  that our sample population is representative of the entire population
  - the more degrees of freedom, usually the more certain we can be that we have accurately sampled the entire population.

So here
"more degrees of freedom"$\equiv$ "greater number of independent pieces of data"
This starts to sound familiar, since it points to the size of a sample of independent draws from the population. Moreover, on focus here are experimental data, so all nice properties I guess are assumed to be guaranteed, and therefore the larger the sample size of independent pieces of data, the more strongly the consistency property of estimator will actually emerge and reflect upon the estimates obtained.
So it appears that, for the author of the passage, the logical chain here goes as follows:

"more degrees of freedom"$\equiv$ "greater number of independent
  pieces of data"

and

"greater number of independent pieces of data" $\Rightarrow$"greater
  accuracy in recovering the population moments from the data"

and

"greater accuracy in recovering the populations moments from the data"
  $\Rightarrow$ "the more representative of the population is the sample"

So

"more degrees of freedom"$\Rightarrow$ "the more representative of the population is the sample"

It appears therefore that the author of the passage employs the term "representative sample" with the meaning of "miniature population" or of  "typical or ideal case", to follow the typology of Kruskal and Mosteller as re-relayed here.


text:
Q: How to prevent dehydratedState overwrite when using in Higher Order Component in Nextjs? I am facing a problem when dehydrating data to SSR in custom HOC, Specifically, I want to hydrate two keys test1 and test2 from server to client to support SSR but I'm getting undefined value returned from test1. I think the reason is because the dehydratedState was overwrited. How do I fix this problem?
My code here:
const withHOC = (gssp) => async (context) => {
    const queryClient = new QueryClient();
    await queryClient.prefetchQuery('test1', () => 'abc123');
    const childProps = await gssp(context);

    return {
        props: {
            dehydratedState: dehydrate(queryClient),
            ...(childProps.props ? childProps.props : {}),
        },
    };
};

export const getServerSideProps = withHOC(async context => {
    const queryClient = new QueryClient();
    await queryClient.prefetchQuery('test2', () => 'profile-example-data');

    return {
        props: {
            dehydratedState: dehydrate(queryClient),
        },
    };
});

// when trying test to get data in component:

queryClient.getQueryData('test1'); // undefined
queryClient.getQueryData('test2'); // profile-example-data

A: The props have the same name dehydratedState, so they overwrite each other. This is not a problem of react-query, but of the getServerSideProps composition.
My best guess on why you wanted to split it into two functions is because there are some pages where you only need 'test1', and other pages where you'd want to "enhance" that to prefetch 'test1' and 'test2'.
If that's the case, I would either just duplicate the logic or extract just the prefetching part, but not the whole "getServerSideProps" part, to a reusable function. It should also use the same queryClient because that's where the data goes that you'd want to dehydrate just once:
export const prefetchTest1 = (queryClient) => queryClient.prefetchQuery('test1', () => 'abc123');

export const getServerSideProps = async context => {
    const queryClient = new QueryClient();
    await prefetchTest1(queryClient)
    await queryClient.prefetchQuery('test2', () => 'profile-example-data');

    return {
        props: {
            dehydratedState: dehydrate(queryClient),
        },
    };
};


text:
Q: Android NullPointerException being thrown in Synchronized Method I have an android app written in java.
The app basically connects to a device which sends the app messages. The app waits for the messages to come in and then reports them, before processing each message.
I have a Connection class and a Listener class.
The Connection class is started via the constructor, which sets up the Listener class to listen for messages coming in from the device.
When a message comes in, the Listener sends the message to a method in the Connection class, reportMessage(). This is where the message is processed.
The Listener class is on a separate thread.
The code is shown below.
public class Connection
{
    private String response;
    private String newResponse;

    private DataInputStream reader;

    private DataOutputStream writer;

    private Socket socket;

    private boolean keepListening;

    private Listener listener;

    public Connection (String _ipAddress, int portNumber)
    {
        try
        {
            socket = new Socket(_ipAddress, _port);   //Connect to the server and its socket

            writer = new DataOutputStream(socket.getOutputStream()); //Connect to the server to receive and send messages

            reader = new DataInputStream(socket.getInputStream());

            listener = new Listener(reader, this); //Create a new listener for the client

            new Thread(listener).start(); //Set the listener off running
        }
        catch (Exception e)
        {
            ...
        }
    }

    public synchronized void reportMessage(String message)
    {
        try
        {
            if("".equals(newResponse))
            {
                newResponse = new String();
            }

            newResponse = newResponse + message;

            System.out.println("Message Received: " + newResponse);

            processMessage(); //Process the message
        }
        catch (Exception e)
        {
            response = e.getCause().toString();
        }
    }
}

public class Listener implements Runnable
{
    private DataInputStream reader = null;

    private boolean keepListening;

    private String serverMessage;

    private Connection connection;

    public Listener (DataInputStream inFromServer, Connection connection)
    {
        reader = inFromServer;
                               //Get the client connection's message transfer
        keepListening = true;

        this.connection = connection;
    }

    public void run()
    {
        while (keepListening)
        {
            try
            {
                if (reader.available() > 0)
                {
                    byte[] readInData = new byte[reader.available()];  //Initialise the array

                    reader.read (readInData);  //Read in the data

                    serverMessage = Utils.byteToString(readInData);

                    connection.reportMessage(serverMessage);   //Report the message
                }
            }
            catch (IOException e)
            {
                System.out.println("Error reading." + e.getLocalizedMessage().toString());

                keepListening = false;
            }

            keepListening = connection.getKeepListening();
        }
    }
}

This works well for a time, then sometimes I receive an error which crashes the program.
When running in debug mode, I get a NullPointerException thrown on whatever is the first line of reportMessage() in the Connection class.
The program is suspended on whatever line is the first line, whether it is a System.out.println or a line of actual code.
And the error doesn't get caught by the try and catch. It crashes the program and there is no handling of the error even though it occurs in the try and catch.
This leads me to believe the error is not being thrown by anything in the reportMessage() method. If this is the case, then perhaps the error is being thrown in the Listener class .run().
However, I cannot see where any NullPointerException can be thrown from, as I have tried to make all the checks and when it is thrown, it is thrown when there are messages being sent.
The debugger says "An exception stack trace is not available".
The LogCat says:
  08-21 10:35:57.894: E/AndroidRuntime(1118): FATAL EXCEPTION: Thread-12
  08-21 10:35:57.894: E/AndroidRuntime(1118): java.lang.NullPointerException
  08-21 10:35:57.894: E/AndroidRuntime(1118):atCom.que.wifiaudio.Connection.reportMessage(Connection.java:339)
  08-21 10:35:57.894: E/AndroidRuntime(1118):   at com.que.wifiaudio.Listener.reportIncomingMessage(Listener.java:93)
  08-21 10:35:57.894: E/AndroidRuntime(1118):   at com.que.wifiaudio.Listener.run(Listener.java:67)

  08-21 10:35:57.894: E/AndroidRuntime(1118):   at java.lang.Thread.run(Thread.java:1102)

Can anyone help me?
I need to know what is throwing the NullPointerException and how to stop it!

A: Turns out it was the
catch (Exception e)
{
    response = e.getCause().toString();
}

The processData() method was throwing an exception which was being caught, but the Exception's cause was Null, which was throwing the error.


text:
Q: How to turn an IEnumerable into a javascript array I'm working on an MVC 5 project and I have two datalist. One holds a list of documents and the other holds formatting information. What I'm trying to achieve is when I select one of the documents the format list would then be filtered down to what applies to that document. So my thought with this was to take my @Model.documents and store it to an array so I could look for the doc id.
 <input list="doc" id="document" />
                    <datalist id="doc" name="Doc" placeholder="Please select a document type">
                        @foreach (var item in Model.docType)
                        {
                            <option id="@item.DocumentTypeID" value="@item.DocumentTypeName"></option>
                        }
                    </datalist>

<input list="tribute" />
                    <datalist id="format">
                        @foreach (var item in Model.format)
                        {
                            <option value="@item.formatName"></option>
                        }
                    </datalist>

$(document).ready(function () {
        $('#document').change(function () {
            var x = $("#doc option[value='" + $('#document').val() + "']").attr('id');

            var trib = [];

            @foreach (var d in Model.documents)
            {
                @:trib.push("@d");
            }
            console.log(trib);
        });
    });

However, this is just putting into the array as Model.documents which I believe is due to it having multiple columns. Any help is appreciated thank you!

A: Convert your C# list to js array and use it inside of "change" event:
var jsArray = @Html.Raw(Json.Encode(Model.documents));

A: Your passing C# object (server side) into JS array (client). All you will get is type name in the array.
See if you can add document type as class name for format type options. so that based the document selection you can filter the format options with respective document type class only. you can do this filtering using javascript


text:
Q: Close connection in DAO object My DAO object
package com.myselect;

import java.sql.*;
import java.sql.DriverManager;

import java.util.logging.Level;
import java.util.logging.Logger;

public class DataAccess {

    Connection conn;
    PreparedStatement pst;
    ResultSet rs;

    public DataAccess() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/db", "root", "root");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public String getAge(String name) {
        String userage = null;
        try {
            pst = conn.prepareStatement("select age from mydb where name= ?");
            pst.setString(1, name);

            rs = pst.executeQuery();

            while (rs.next()) {
                userage = rs.getString("age");
                System.out.println(userage);
            }

        } catch (Exception ex) {
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
        }

        return userage;
    }

    public int insertRecord(String name, int addage) {
        int b = 0;
        try {
            pst = conn.prepareStatement("insert into mydb values(?,?)");
            pst.setString(1, name);
            pst.setInt(2, addage);
            b = pst.executeUpdate();

        } catch (Exception ex) {
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
        }

        return b;
    }

}

I want to close the connection. I have several servlets which calls insertRecord and getAge methods.What is the best way to close my connection? Create another method and call from insertRecord and getAge method or in constructor?

A: Connections should be opened and closed when needed. In your case, you are opening a connection at one point, and then, using it at another. This means that you open a connection and potentially not use it for some time.
What you would need to do, would be to make the methods self contained, meaning that the methods should open the connection, and when done, close it. The closing part should be done within a finally block, this will ensure that regardless what happens, the collection will always be closed.
Something like so:
public String getAge(String name) {
        String userage = null;
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/db", "root", "root");

            PreparedStatement pst = conn.prepareStatement("select age from mydb where name= ?");
            pst.setString(1, name);

            rs = pst.executeQuery();

            while (rs.next()) {
                userage = rs.getString("age");
                System.out.println(userage);
            }

        } catch (Exception ex) {
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally {
            if(conn != null) {
                conn.close();
            }

            if(pst != null) {
                pst.close();
            }

            if(rs != null) {
                rs.close();
            }
        }

        return userage;
    }

EDIT: As per @virtualpathum suggestion, you can also take a look at 3rd party frameworks which provide you with means to manage your connection pool, usually through the implementation of the Singleton programming pattern.

A: Before considering the connection, you should also always close the ResultSet and Statement objects every time you use them. Don't keep them as state in your DataAccess object. Have them as local variables and close them after using them:
public String getAge(String name) {
    PreparedStatement pst = null;
    ResultSet rs = null;
    String userage = null;
    try {
        pst = conn.prepareStatement("select age from mydb where name= ?");
        pst.setString(1, name);

        rs = pst.executeQuery();

        while (rs.next()) {
            userage = rs.getString("age");
            System.out.println(userage);
        }

    } catch (Exception ex) {
        Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
       // closing JDBC resources
       if(rs != null) {
          rs.close();
       }

      if(pst != null) {
          pst.close();
       }

    return userage;
}

Same for the connection: Ideally, every method should create a Connection object and close it after its use. Depending on how frequently you open and close a connection in a method, you may want to use a connection pool to share open connections for more efficiency.
For closing connections and its resources, you can create a method to do that:
public void closeConnection(Connection connection, Statement statement, ResultSet resultSet) {
     ... // close resources here
}


text:
Q: Loop through array and create a ListItem for each item I am trying to loop through the array passed in named tools and create a ListItem for each item in the list based on its properties. Currently all I have being displayed is my ListSubheader. No Buttons display. I would like to confirm that my problem is here rather than what is being passed down.
tools looks like:
[
   {
      icon: PropTypes.object.isRequired,
      text: PropTypes.string.isRequired,
      route: PropTypes.string.isRequired
   }, ...
]

My code is as follows:
const ToolSidebar = ({ sidebarTitle, tools }) => {
  return (
    <Fragment>
      <List subheader={<ListSubheader>{sidebarTitle}</ListSubheader>}>
        {tools.forEach(tool => {
          return (
            <ListItem button href={tool.route}>
              <ListItemIcon>{tool.icon}</ListItemIcon>
              <ListItemText primary={tool.text} />
            </ListItem>
          );
        })}
      </List>
    </Fragment>
  );
};

UPDATE: For anyone who may stumble on this answer, while unrelated to the question, you will still get an error. Instead of:
<ListItemIcon>{tool.icon}</ListItemIcon>

use
<ListItemIcon> <SvgIcon component={tool.icon} /> </ListItemIcon>

A: You should be using Array.prototype.map not Array.prototype.forEach.
{tools.map(tool => {
     return (
        <ListItem button href={tool.route}>
           <ListItemIcon>{tool.icon}</ListItemIcon>
           <ListItemText primary={tool.text} />
        </ListItem>
    );
  })}
}


text:
Q: Works with libc++, segmentation fault with listdc++. [MacOs Sierra, Boost, Clang] I want to get Mitsuba working on my Mac, I manage to compile it and I got an error at the runtime. I tried to manage to generate a simple test, to show you the bug :
#include <boost/filesystem/operations.hpp>
#include <iostream>

namespace fs = boost::filesystem;

int main(int argc, char*argv[])
{
        fs::path test = fs::canonical("/Users/Stephane-lb/Projects/");
        return 0;
}

if I compile it using the following command, everything is working
    clang++ boostTest.cpp -lboost_filesystem -lboost_system
but if I use:
    clang++ boostTest.cpp -lboost_filesystem -lboost_system -stdlib=libstdc++
I think it is happening because boost was compiled using homebrew so using libc++ and I want to use libstdc++. Is there any ways to make these two working together ?
Thank you very much for your help,
Stephane-lb


text:
Q: Countup will be start when reached scroll point in countup div I am creating one page template. I have create a countup section. I want to display countup animation, when display countup section in screen. That mean, when scroll point reached countup section, animation will be start.
activation script
$('.count').jQuerySimpleCounter({
    start:  0,
    end:10,
    duration: 10000
});

Please help me.

A: You would watch the window scroll event (debounced for performance) and when the distance from the scroll to your element is < X amount of pixels trigger your animation
(function($, window){
    var $window = $(window);
    var $countupSection = $('.countup-section');
    var countupTop = $countupSection.offset().top;

    var debounce = function(func, wait, immediate) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    };

    var checkPosition = function(){
        var scrollTop = $window.scrollTop();

        if(scrollTop - countupTop < 20){
            //unbind the event so animation triggers only once
            $window.off('scroll', debouncedScroll);
            $('.count').jQuerySimpleCounter({
                start:  0,
                end:10,
                duration: 10000
            });
        }
    };

    var debouncedScroll = debounce(checkPosition, 50);

    $window.on('scroll', debouncedScroll);
})(jQuery, window);


text:
Q: VBA certain Part of a String I have an excel column with strings like this one: ABC-1234-GLK-1234-10TH8E10-21 71-D
I need to give to a variable the value GL-1234 (the substring between the 2nd dash and the 4th). I tried
x=Mid(string, 10, 8)
but the problem is that not all the strings have the same length, however the only constant is that the substring that i want is between the 2nd and the 4th dash.
Any ideas?

A: Split the string and extract what you want:
Dim dataSplit() As String
Dim dataString As String

dataSplit = Split(Sheet1.Range("C14").Value2, "-")

dataString = dataSplit(2) & "-" & dataSplit(3)

A: You can try the following, although I don't think it is the most elegant or the easiest solution:
x = ""
p1 = InStr(1, string, "-")
If p1 <> 0 Then
    p2 = InStr(1 + p1, string, "-")
    If p2 <> 0 Then
        p3 = InStr(1 + p2, string, "-")
        If p3 <> 0 Then
            p4 = InStr(1 + p3, string, "-")
            If p4 <> 0 Then
                x = Mid(string, p2 + 1, p4 - p2 - 1)
            End If
        End If
    End If
End If

A: this will return 2nd dash and 4th dash, B1 is string : ABC-1234-GLK-1234
=MID(B1,FIND("-",B1,FIND("-",B1)+1),FIND("-",B1,FIND("-",B1,FIND("-",B1,FIND("-",B1)+1)+1)+1) - FIND("-",B1,FIND("-",B1)+1))


text:
Q: Rational integral representation of inverse logarithm. Suppose $x\in(0,1)$. Let $p_i(x,z)$ generically denote a sequence of multivariate polynomials in $(x,z)$.
Is it possible to write:
$$\frac{1}{\ln(x)} = \int_0^1\frac{p_2(x,z)}{p_3(x,z)}dz?$$
I know for example that:
$$\ln(x) = \int_0^1\frac{(1-x)dz}{1-(1-x)z},$$
but unfortunately I don't know a trick for the inverse logarithm (maybe it doesn't even exist). The only one I know is:
$$\frac{1}{\ln(x)}=\frac{1}{x-1}\int_0^1 x^tdt,$$
which isn't in the right form.
Note that I'm willing to allow multiple integrals, e.g. another example:
$$\ln^2(x)=\int_0^1\int_0^1\frac{(1-x)^2dwdz}{(1-(1-x)w)(1-(1-x)z)}$$


text:
Q: Trouble labeling an angle within a picture My tikz does not want to label the angle within the figure. Whenever I try to use the command "$\alpha$" inside the pic arguments tikz ignores it. I do not know how to proceed. Any suggestions for the code are welcome. Thank you for the help.
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{calc,intersections,through,backgrounds,angles,quotes}
\begin{document}
\begin{tikzpicture}
\draw (0,0) -- (0,2) -- (5.46,2) -- (2,0) -- (0,0);
\coordinate [label=below:\(A\)] (A) at (0,0);
\coordinate [label=below:\(B\)] (B) at (2,0);
\coordinate [label=above:\(C\)] (C) at (5.46,2);
\coordinate [label=above:\(D\)] (D) at (0,2);
\coordinate [label=left:\(2\)] (E) at (0,1);
\coordinate [label=below:\(2\)] (F) at (1,0);
\coordinate (G) at (3.5,0);
\draw[dashed] (2,0) -- (3.5,0);
\draw (G) -- (B) -- (C)
pic [draw=black, thick, angle radius=1cm, "$\alpha$"] {angle=G--B--C};
\end{tikzpicture}
\end{document}


text:
Q: Max10 LVCMOS input setup and hold timing I am struggling to find the minimum setup and hold timings for single-ended 3.3V LVCMOS inputs in the datasheet. I'm especially puzzled that the datasheet and handbook differentiate between low-speed and high-speed pins without stating the actual difference between the two.
I really would like to have some ballpark numbers prior to coding.


text:
Q: Separator data received via post request My problem is: I get through a post request the variable "data" in Javascript, like this:
var data = name1 text1 name2 text2 name3 text3;

How do I divide each data element in a variable like this:
var group1 =  name1 - text1;
var group2 =  name2 - text2;
var group3 =  name3 - text3;

Then I decided to put a separator in php, the character "-" in each group (variable) that would form, and then deal with the javascript function "split()" the string. The problem is that in the text there could also be the "-" character and any other character, how do I saparare as in example without using JSON? I control both the server side (PHP) or client-side (Javascript).

A: I'm going to make a wide assumption about what your php code looks like, since you so conveniently left it out. I imagine it looks like this (off the top of my head, may not actually work):
$response = '';
mysql_query('select name, text from mytable');
while ($row = mysql_fetch_assoc()) {
    $response = $row['name'] . ' ' . $row['text'] . ' ' .$response;
}
echo $response;

You should instead respond with an object like this:
$response = array();
mysql_query('select name, text from mytable');
while ($row = mysql_fetch_assoc()) {
    $response[$row['name']] = $row['text'];
}
echo json_encode($response);

Then, in your javascript, it will look like this:
var data = {"name1": "text1", "name2": "text2", "name3": "text3"};

And you can create your groups like this:
var groups = [];
for (var name in data) {
    groups.push(name + " - " + data[name]);
}

to create an array of those groups you wanted.


text:
Q: libfuse: How should I set fuse(8) options internally? I want to set default_permissions option as default.
http://man7.org/linux/man-pages/man8/mount.fuse.8.html

default_permissions
...
Filesystems that do not implement any permission checking
  should generally add this option internally.

The simplest way is adding -o default_permissions to argv and pass it to fuse_main, like:
int main(int argc, char *argv[]) {
  char **new_argv = malloc(sizeof(char *)*(argc+3));
  memcpy(new_argv, argv, sizeof(char *)*argc);
  new_argv[argc] = "-o";
  new_argv[argc+1] = "default_permissions";
  new_argv[argc+2] = NULL;

  return fuse_main(argc+2, new_argv, &hello_oper, NULL);
}

But I'm not sure if it's the best way... It looks ugly.
Does anyone have an idea?


text:
Q: Why i need to have DevExpress Installed to use XPF.Core We are using DevExpress in my team to develop WPF application. We have limited licences but this is not a problem because you can ask someone to add DLL et work on a project without DevExpress installed.
But, because i need the combobox edit control from XPF.CORE, i saw that i need to have Dev Express installed to build the code.
SO the issue is no one can compile the code if they don't have devexpress installed.
Is someone got this issue before and find a solution?Is DevExpress.Xpf.Core the pnly one DLL with the issue?

A: You are violating the licensing terms of DevExpress if you copy the assemblies around. From their licensing FAQ:

Is your license on a per-developer basis? Does each developer using your products require a license?
  Yes. Each developer that uses our products must have their own license. We don't license per machine, per server, or demand any royalties or run-time fees. For more information, refer to our End-User License Agreement. If you have a testing team and they need to compile the application, then those testers will also each need a license. Testers who just test the completed, compiled application (that is, use it much as an end-user does) do not need a license.

Now, when you say:

We have limited licences but this is not a problem because you can ask someone to add DLL et work on a project without DevExpress installed.

then it might not be a problem for you but do you realize that they can only dedicate so much resources to their product development if they get paid for what they deliver? I'd say take it up with your managers and convince them that the right way is to buy more licenses or cut down on the number of people working on the product because otherwise they are facilitating illegal use of the product.

A: So the issue was about the default theme of the application.

Starting with version 16.1, applications with DevExpress components
  use the Office2016White theme by default, and the
  DevExpress.Xpf.Themes.Office2016White library has to be deployed to a
  client machine.

If you don't want to use the Office2016White theme in your application, specify a theme of your choice in the application constructor using the DevExpress.Xpf.Core.ApplicationThemeHelper.ApplicationThemeName property or set the ApplicationThemeHelper.UseLegacyDefaultThemeproperty to true.
Reference - DevExpress QA thread


text:
Q: Scroll snaps to position of anchor link - unwanted behaviour and inefficient implementation I've created a simple tabbed content display using CSS and HTML. This code will be embedded around halfway down a much longer page with other content.
Here's the jsFiddle: http://jsfiddle.net/ollyf/R9rq2/
I've made use of :target but I'm not entirely sure how it works. Read a few tutorials but I don't fully understand the behaviour. I feel like this is bad/inefficient code.

*

*Is there a more efficient way to achieve this tabbed content effect?

*If not, how can I reveal the content without the scroll position snapping to the top of the DIV?

A: The :target pseudo selector is triggered by on page anchors.  This means when your URL is http://www.example.com/#anchor1 #anchor1:target styles would be activated.  The page is also scrolled to the #anchor1 element.  This is the default functionality in browsers.
The other option for achieving a tab effect is through the use of javascript.  The concept is the same with javascript, you are still toggling the display attribute via click handlers.  There are several ready made scripts available for tabs.  Here is one example http://jquerytools.org/demos/tabs/index.html
Hope this helps clear things up.


text:
Q: How to Open a Custom Spinner Item from MainActivity? I have two activities viz., Activity A and B and I have a spinner in Activity B with 5 options(like country names). On clicking an item, a toast is shown to the user.
//Performing action onItemSelected
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
    Toast.makeText(getApplicationContext(),country[position] ,Toast.LENGTH_LONG).show();
}

In my Activity A, I use a button to open Activity B using Intent. The activity B is opened with the first item of the spinner.
Question
Is there a way so that on clicking the button in Activity A, second spinner item is opened and the respective toast is shown?

A: you can use the setSelection(int item) method of your spinner (see: https://developer.android.com/reference/android/widget/AbsSpinner.html#setSelection(int)).
For example:
//Activity B
@Override
public void onCreate(Bundle savedInstanceState)
{
    //find spinner
    spinner.setSelection(1)
}

A: This answer is based on the assumption that you want to set 2nd item of the array as the default selection.
Use the following code:
    final Spinner spinner = (Spinner) view.findViewById(R.id.spinner1);
    final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
            getActivity(), android.R.layout.simple_spinner_dropdown_item,
            getResources().getStringArray(R.array.names));
     spinner.setAdapter(arrayAdapter);
    spinner.post(new Runnable() {
        @Override
        public void run() {
            spinner.setSelection(1);
        }
    });

I am late now I think...


text:
Q: Using underscore to group a objects properties into separate smaller objects based on a name Currently I have a object that has multiple keys that are prefixed with a "_id(actually a number)", like a so:
    var obj = {
outFieldType_25669: "Select a type"
outFieldType_97327: "Select a type"
outfieldWallType_25669: "Select a type"
outfieldWallType_97327: "Select a type"

scoreboardDetailsShown_25669: "e.g. players name, photo, stats, etc..."
scoreboardDetailsShown_97327: "e.g. players name, photo, stats, etc..."
scoreboardOperatedBy_25669: "Select a type"
scoreboardOperatedBy_97327: "Select a type"

warningTrackType_25669: "Select a type"
warningTrackType_97327: "Select a type"
};

What i would like to do is split that object into smaller objects that are grouped by the ending prefix, a example of what the outcome is envisioned to be:
objA = {
    outFieldType_97327: "Select a type",
    outfieldWallType_97327: "Select a type",
    scoreboardDetailsShown_97327: "e.g. players name, photo, stats, etc..."
    scoreboardOperatedBy_97327: "Select a type",
    warningTrackType_97327: "Select a type"
};

objB = {
   outFieldType_25669: "Select a type",
   outfieldWallType_25669: "Select a type",
   scoreboardDetailsShown_25669: "e.g. players name, photo, stats, etc...",
   scoreboardOperatedBy_25669: "Select a type",
   warningTrackType_25669: "Select a type"
};

A: Use _.each to iterate the object, split the id from the key and store it in a separate object, e.g.
var sorted = {};

var obj = {
    outFieldType_25669: "Select a type",
    outFieldType_97327: "Select a type",
    outfieldWallType_25669: "Select a type",
    outfieldWallType_97327: "Select a type",
    scoreboardDetailsShown_25669: "e.g. players name, photo, stats, etc...",
    scoreboardDetailsShown_97327: "e.g. players name, photo, stats, etc...",
    scoreboardOperatedBy_25669: "Select a type",
    scoreboardOperatedBy_97327: "Select a type",
    warningTrackType_25669: "Select a type",
    warningTrackType_97327: "Select a type"
};

_.each(obj, function (value, key) {
    var id = key.split("_")[1];
    if (sorted[id] === undefined) {
        sorted[id] = {}
    };
    sorted[id][key] = value;
});

console.log(sorted);

See this JSFiddle.


text:
Q: Trouble with lists and functions in python I'm a student and one of my tasks involves drawing with turtle based on a randomly generated number. The following code is similar to the task.
def aaa():
numbers = []
for number_list in range(2):
    bbb = randint(1, 6)
    numbers.append(bbb)

My assumption was to create an if/elif chain to determine what action to take for each number generated as seen below. However, I'm having trouble as the aaa function isn't a list.
if aaa == 1:
print('a')

if aaa == 2:
print('b')

if aaa == 3:
print('c')

if aaa == 4:
print('d')

if aaa == 5:
print('e')

if aaa == 6:
print('f')

A: You must return a value from the function. after that you must loop through the list.
import random

def aaa_func():
    numbers = []
    for number_list in range(2):
        bbb = random.randint(1, 6)
        numbers.append(bbb)
    return numbers

aaa_list = aaa_func()

for aaa in aaa_list:

    if aaa == 1:
        print('a')

    if aaa == 2:
        print('b')

    if aaa == 3:
        print('c')

    if aaa == 4:
        print('d')

    if aaa == 5:
        print('e')

    if aaa == 6:
        print('f')

A: aaa is a function, not a list. You need to call aaa, have it return the list and then iterate over the list.
def aaa():
    numbers = []
    for number_list in range(2):
        bbb = randint(1, 6)
        numbers.append(bbb)
    return numbers

numbers = aaa()

for number in numbers:
    if aaa == 1:
        print('a')

    elif aaa == 2:
        print('b')

    elif aaa == 3:
        print('c')

    elif aaa == 4:
        print('d')

    elif aaa == 5:
        print('e')

    elif aaa == 6:
        print('f')

A: *

*Your function needs indention so the interpreter will know which lines belong to the function.

*You want to get a list with the numbers from the function, so return the list numbers from the function.

*When calling the function, you need to add the brackets (otherwise you would just get the function object).

*Instead of using several if's, it is seen as best practice to use elif for all if's fol

*You need to iterate over all elements of the list you get as a return value from your function aaa().
Your overall code should look something like this:
def aaa():
    numbers = []
    for number_list in range(2):
        bbb = randint(1, 6)
        numbers.append(bbb)

    return numbers

for number in aaa():
    elif number == 1:
    print('a')

    elif number == 2:
    print('b')

    elif number == 3:
    print('c')

    elif number == 4:
    print('d')

    elif number == 5:
    print('e')

    elif number == 6:
    print('f')


text:
Q: Divi Anchor Links from another page I set up a page that has all of my previous pages in one with anchor links that allow the user to scroll quickly down the page with ease. That works fine.
However, each section is it's own page and I have the individual page links listed in my footer. I've created each menu link referencing back to the section of the page but the only one that works is the first one "About." The rest of the links FAQ, Privacy Policy, Disclaimer, Disclosure, and Contact receive a 404 error.
The URL I'm using for these menu items is https://partyfavorz.com/staging1/about/#about. This works but...
https://partyfavorz.com/staging1/privacy-policy/#privacy-policy does not; nor do the rest of the pages. What am I missing because most of the tutorials say to just put in the #page-name for the link which does not work at all, which is why I use the full URL.
I've got the correct Class ID and know it works because the actual page flows from one section to the next. It's just setting up the outside links within the menu that's not working. Any suggestions would be helpful.

A: So all of the tutorials are wrong across the board; at least for my site. I changed the menu URL structure to https://partyfavorz.com/staging1/pages/#name
This is not how my permalinks are set up as they are strictly set to {site-name} {post-title}. Theoretically, it should be https://partyfavorz.com/staging1/#name, but whatever. This works.


text:
Q: Can tuple variadic template recursion be improved with C++14 index sequences? I have many variadic template functions to process std::tuple instances in my code similar to these ones:
// Convert JSON object to `std::tuple`

template<int TI = 0, typename... TS>
std::enable_if_t<TI == sizeof...(TS)> toTpl(const JVal&, std::tuple<TS...>&)
{
    // Do nothing (end of the recursion)
}

template<int TI = 0, typename... TS>
std::enable_if_t<TI < sizeof...(TS)> toTpl(const JVal& mV, std::tuple<TS...>& mX)
{
    std::get<TI>(mX) = mV[TI].as<std::tuple_element_t<TI, decltype(mX)>;
    toTpl<TI + 1, TS...>(mV, mX);
}

Basically, I use a template int counter and  enable_if to instantiate the template 0 -> sizeof...(TS) times.
I was wondering if and how the new C++14 std::integer_sequence or std::index_sequence could help in these situations.
I'm looking to make the code more readable (and easier to maintain). Improving compilation time is also a big plus.
I tried using std::index_sequence but ran into issues - I'm confused about its usage, especially when passing it as an argument in the function.

A: I'd return the tuple by value to avoid unnecessary default construction and the nasty out parameter:
template <typename... Ts, std::size_t... Is>
auto toTpl(const JVal& mV, std::index_sequence<Is...>)
{
    return std::tuple<Ts...>{ mV[Is].as<Ts>()... };
}

template<typename... Ts>
auto toTpl(const JVal& mV)
{
    return toTpl<Ts...>(mV, std::index_sequence_for<Ts...>{});
}

// Usage:

auto t = toTpl<int, double, long>(mV);

Maybe rename the function as_tuple:
auto t = as_tuple<int, char, std::string>(some_json_value);

which seems elegant and consistent with the usage of JVal::as. (Live at Coliru)

A: Option #1
template <typename... TS, std::size_t... Is>
void toTpl(const JVal& mV, std::tuple<TS...>& mX, std::index_sequence<Is...>)
{
    using Tuple = std::tuple<TS...>;
    mX = std::forward_as_tuple(mV[Is].as<std::tuple_element_t<Is, Tuple>>()...);
}

template <typename... TS>
void toTpl(const JVal& mV, std::tuple<TS...>& mX)
{
    toTpl(mV, mX, std::make_index_sequence<sizeof...(TS)>{});
}

DEMO 1

Option #2
template <typename... TS, std::size_t... Is>
void toTpl(const JVal& mV, std::tuple<TS...>& mX, std::index_sequence<Is...>)
{
    using Tuple = std::tuple<TS...>;
    int dummy[] = { 0, ((void)(std::get<Is>(mX) = mV[Is].as<std::tuple_element_t<Is, Tuple>>()), 0)... };
}

template <typename... TS>
void toTpl(const JVal& mV, std::tuple<TS...>& mX)
{
    toTpl(mV, mX, std::make_index_sequence<sizeof...(TS)>{});
}

DEMO 2

Option #3
template <std::size_t N, typename... TS>
void op(const JVal& mV, std::tuple<TS...>& mX)
{
    using Tuple = std::tuple<TS...>;
    std::get<N>(mX) = mV[N].as<std::tuple_element_t<N, Tuple>>();
}

template <typename... TS, std::size_t... Is>
void toTpl(const JVal& mV, std::tuple<TS...>& mX, std::index_sequence<Is...>)
{
    int dummy[] = { 0, ((void)op<Is>(mV, mX), 0)... };
}

template <typename... TS>
void toTpl(const JVal& mV, std::tuple<TS...>& mX)
{
    toTpl(mV, mX, std::make_index_sequence<sizeof...(TS)>{});
}

DEMO 3

A: You may do something like:
template<typename Tuple, std::size_t... Is>
void toTpl(const JVal& mV, Tuple& t, std::index_sequence<Is...>)
{
    std::initializer_list<int> {
        (std::get<Is>(t) = mV[Is].as<std::tuple_element_t<Is, Tuple>>, void(), 0)...
    };
}

template<typename... TS>
void toTpl(const JVal& mV, std::tuple<TS...>& t)
{
    toTpl(mV, t, std::make_index_sequence<sizeof...(TS)>{});
}

A: What about
template <typename... T, std::size_t... I>
void toTpl_(const JVal& mV, std::tuple<T...>& mX, std::index_sequence<I...>)
{
    (void) std::initializer_list<int>{ (std::get<I>(mX) = mV[I].as<T>(), 0)... };
}

template <typename... TS>
void toTpl(const JVal& mV, std::tuple<TS...>& mX)
{
    toTpl_(mV, mX, std::index_sequence_for<TS...>() );
}

I don't think it gets much better than that. Returning a tuple and assigning that corresponds (after copy elision) to
template <typename... T, std::size_t... I>
void toTpl_(const JVal& mV, std::tuple<T...>& mX, std::index_sequence<I...>)
{
    mX = std::make_tuple( mV[I].as<T>()... );
}

template <typename... TS>
void toTpl(const JVal& mV, std::tuple<TS...>& mX)
{
    toTpl_(mV, mX, std::index_sequence_for<TS...>() );
}

Which obviously creates unnecessary copies.


text:
Q: Flex XML from Obix with the below xml   I'm trying to get the val  from the "real" name=sum element.
everything I try won't get me past the "obj" level  (not the root "obj" level)
I'm working with flex 4.5
  <obj href="http://10.1.151.163/obix/histories/Dashboard_ENC/WaterConsumtion/~historyRollup/" is="obix:HistoryQueryOut" xsi:schemaLocation="http://obix.org/ns/schema/1.0 /obix/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://obix.org/ns/schema/1.0">
     <list name="data" of="obix:HistoryRollupRecord">
        <obj>
          <abstime name="start" val="2011-06-13T10:00:00.000-04:00" tz="EDT"/>
          <abstime name="end" val="2011-06-13T11:00:00.000-04:00" tz="EDT"/>
          <int name="count" val="4"/>
          <real name="min" val="0.0"/>
          <real name="max" val="25.0"/>
          <real name="avg" val="14.105714559555054"/>
          <real name="sum" val="56.422858238220215"/>
       </obj>
       <obj>
         <abstime name="start" val="2011-06-13T11:00:00.000-04:00" tz="EDT"/>
         <abstime name="end" val="2011-06-13T12:00:00.000-04:00" tz="EDT"/>
         <int name="count" val="4"/>
         <real name="min" val="12.38690185546875"/>
         <real name="max" val="42.49167251586914"/>
         <real name="avg" val="29.935394763946533"/>
         <real name="sum" val="119.74157905578613"/>
       </obj>
   </list>
      <int name="count" val="2"/>
      <abstime name="start" val="2011-06-13T10:00:00.000-04:00" tz="EDT"/>
     <abstime name="end" val="2011-06-13T12:00:00.000-04:00" tz="EDT"/>
  </obj>

here is what I have ...
private function parseWater(ev:Event):void
{
    var _xmlWater:XML = new XML(ev.target.data);

    trace(_xmlWater);
    trace(_xmlWater..obj[1].real[3].@val);  // <-- this doesn't work -- undefined
}

Thanks

A: I think you need to have the node "list" in there. It kinda looks like you just made a typo however and the code you ran actually did refer to "list".
Here's a really detailed explanation of how to work with XML data in AS3:
http://www.kirupa.com/developer/flashcs3/using_xml_as3_pg1.htm

A: Try:
_xmlWater.list[0].obj[1].real[3].@val;


text:
Q: Won't turn on after dead battery I have mountain lion on MacBook pro mid 2012.
So if my battery dies, because I left noSleep on or just because of being sat untouched for a week off of 2%, when I turn my computer on, Instead of the picture of the screen last used with the loading bar under it, the apple logo with the loading bar. I let it sit for a while, and it stays at the last bar of the loading thing. I wait and wait and nothing. I have to reboot using the power button to get it to work. A message then appears that said "your computer shut down cuz of a problem" . I have always saved my work
, but I am assuming it would all be deleted if I had an unsaved word doc on low battery.
What is going on?
Things I have tried:
 reset SMC
Reinstall OS on network recovery
And eventually if I have to, I guesss I will have to factory reset it

A: This sounds like a defective hardware issue. Take your Mac to an authorized Apple repair/service center, or an Apple Store, and have them diagnose the problem. If it is under warranty, or if you purchased AppleCare to extend the warranty, they will replace any faulty components.

A: In my opinion this sounds like a missing or corrupt sleep image.
When your Mac loses power thanks to the battery draining it should enter Safe Sleep.  Safe sleep relies on a functioning sleep image to store the contents of memory once power is lost.  This sleep image is located at /private/var/vm/sleepimage.
I'm not familiar enough with noSleep to know if it removes/prevents this image but it wouldn't surprise me if this was the case since it's main function is to prevent the Mac from sleeping.

My first plan of action would be to remove the current sleep image using this command in terminal, you will be prompted to enter your admin password once you enter the command:
sudo rm /private/var/vm/sleepimage

Following that command I would restart the Mac using  > Restart...
Once the Mac restarts I would use the following command in terminal to check the size of the sleep image, it will likely be the same size as the amount of installed RAM in the Mac:
ls -lh /private/var/vm/sleepimage

If for whatever reason either command returns an error then your sleep image likely doesn't exist, which would explain the problem.  If this is the case then I would either uninstall noSleep or contact someone involved with the development (I believe it's open source) to ask about a change in it's behavior or a possible fix.
Hopefully that helps!


text:
Q: Apostrophe CMS + Express.js Backend + Angular integration I've been trying to integrate Apostrophe CMS with a CRM platform that we have running on a node.js+express.js backend, but am finding it a bit difficult.
I'll detail the setup before asking:

*

*We have two parallel platforms: client-cms and client-server, where -cms is APOS and -server is our backend API built with node.js and express.js

*client-server has a frontend built in angular that runs on the separate project client-ng.
The first step towards integration was to create a custom module in Apostrophe in /lib/modules/client-server/ with a copy of our node.js + express.js backend. client-server on Apos
Then we created /lib/modules/apostrophe-express/index.js which contains the following:

    module.exports = {
      session: {
        secret: 'xxxxxxxxxd80e52'
      },
      csrf: {
        exceptions: [
          '/user/login',
          '/api/v1/*/**'
        ]
      },
      port: 4000
      };

While navigating our site, the majority of the content is loaded from Apostrophe modules, but for logged in users there are specific sections that are rendered through angular components and that load data from client-server's API.
However, both Apostrophe and our Angular frontend should share a number of JS and CSS dependencias, as well as common data, such as Apostrophe's navigation menu.
The issues:

*

*We have recently been experiencing intermittent 403 errors when trying to load data from the client-server through its /api/v1/. We have added the exceptions, but would like to know if there is a way to debug those 403 errors.

*Our client-server handles the session and info for all logged in users, but we're not sure how to hand this down to Apostrophe for display. For example, how could we get my layout.html to pull the avatar and user_id from /api/v1/ in order to consistently display this info across the entire site?

One possible solution we're working on in order to solve the need for a unified UI is by using apostrophe-headless. Ideally we're aiming to create a fragment that sends a rendered UI to angular, ready for print, or in a less idea case, send the data object so that angular has all it needs to recreate the UI.
I think headless along with fragments could possibly solve the issue with the shared UI.
Thoughts?


text:
Q: How to run a workspace without using yarn workspace I'm building a Dockerfile for deploying a monorepo node based server, which is based in packages/server and depends on some other packages.
The resulting image is 750Mb and the reason is the large node_modules folder. Since this is a production compilation, I would like to:

*

*remove node_modules entirely

*basically run node packages/server/build/server.js
Normally I would use yarn workspace server start:prod for this.
I have two questions:

*

*What is the best way to start a node server package in Dockerfile? In order to have all the relevant path relations work correctly.

*How do I ensure that running the build doesn't bomb when I remove the node_modules (this happens now when I do this: it tries to load files from node_modules)

This is the current one:
FROM node:10.15.3-alpine AS builder

ENV NODE_VERSION 10.15.3
ENV YARN_VERSION 1.15.2

# Install installation environment
RUN apk add --no-cache --virtual .build-deps-yarn curl \
    && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
    && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/ \
    && ln -snf /opt/yarn-v$YARN_VERSION/bin/yarn /usr/local/bin/yarn \
    && ln -snf /opt/yarn-v$YARN_VERSION/bin/yarnpkg /usr/local/bin/yarnpkg \
    && rm yarn-v$YARN_VERSION.tar.gz \
    && apk del .build-deps-yarn
RUN apk add --no-cache --virtual build-dependencies \
        rsync \
        python \
        make \
        g++

RUN apk update && apk add git

# Create production node_modules only directory
WORKDIR /node_cache
RUN mkdir -p /node_cache/packages \
    && mkdir -p /node_cache/packages/server \
    && mkdir -p /node_cache/packages/social \
    && mkdir -p /node_cache/packages/common-lib
COPY package.json /node_cache
COPY lerna.json /node_cache
COPY yarn.lock /node_cache
COPY packages/server/package.json /node_cache/packages/server
COPY packages/social/package.json /node_cache/packages/social
COPY packages/common-lib/package.json /node_cache/packages/common-lib

# Install optimized production version
ENV NODE_ENV production
RUN yarn install --ignore-scripts --frozen-lockfile --production && npm rebuild

# Install development version for compilation
WORKDIR /app
COPY . /app

ENV NODE_ENV development
RUN yarn install --ignore-scripts --frozen-lockfile && npm rebuild

# Build the environment
RUN NODE_OPTIONS="--max_old_space_size=$MEMORY_LIMIT" yarn workspace server razzle build

# Copy production node_modules to production environment
RUN rm -rf ./node_modules
RUN rm -rf ./packages/server/node_modules
RUN rm -rf ./packages/social/node_modules
RUN rm -rf ./packages/common-lib/node_modules
RUN rsync -a /node_cache/ /app/

RUN apk del build-dependencies && yarn cache clean

# Deployment image
FROM node:10.15.3-alpine

ENV HOST 0.0.0.0
ENV PORT 3005
ENV NODE_ENV production

RUN apk add --no-cache --virtual .build-deps-yarn curl \
    && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
    && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/ \
    && ln -snf /opt/yarn-v$YARN_VERSION/bin/yarn /usr/local/bin/yarn \
    && ln -snf /opt/yarn-v$YARN_VERSION/bin/yarnpkg /usr/local/bin/yarnpkg \
    && rm yarn-v$YARN_VERSION.tar.gz \
    && apk del .build-deps-yarn

WORKDIR /app
COPY --from=builder /app .

# Start the server
USER node
ENTRYPOINT ["yarn"]
CMD ["workspace","server","start:prod"]

EXPOSE 3005


text:
Q: Microsoft.IdentityModel.Clients.ActiveDirectory not loading on Azure DevOps PowerShell Release Pipeline Recently I experienced some issue with Azure DevOps PowerShell when attempting to create a ClientCredential and or ClientAssertion. I have the following code which was working on the past for creating a ClientCredential based on the following variables:

*

*TenantId

*ClientID (SPN)

*Password (SPN Password)
$ResourceUrl = "https://database.windows.net/"
$AuthorityUrl = "https://login.microsoftonline.com/$($TenantId)"
$objClientCredential = [Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential]::new($ClientId, $Password)
$objAuthenticationContext = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext]::new($AuthorityUrl)
$objAuthenticationResult = $objAuthenticationContext.AcquireTokenAsync($ResourceUrl, $objClientCredential)
but recently this code stop working. It seems that the AzureAD module is not loading correctly. This only happens on Azure DevOps Powershell, on my machine it works fine (I am using PowerShell 7.1)
So far so now I attempted the following:

*

*Run the code as shown above
**Breaks on: **$objClientCredential = [Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential]::new($ClientId, $Password)
Error: Unable to find type [Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential]

*Install AzureAD before running the code
Install-Module -Name AzureAD -Force
Import-Module -Name AzureAD
**Breaks on: **$objClientCredential = [Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential]::new($ClientId, $Password)
Error: Unable to find type [Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential]

*Import the dll Microsoft.IdentityModel.Clients.ActiveDirectory.dll from my machine
Add-Type -Path ".\libraries\Microsoft.IdentityModel.Clients.ActiveDirectory.dll
Doesn't break, however ClientCredential is not created it is returned as null

Have anyone experienced a similar issue? Do you know how should I drive this?

A: If you run the scripts on local machine. You can check where the assembly is installed and manually import the .dll file. I tested on my local machine. It works fine when i just import the azureAd module:
Install-Module AzureAD -Force
Import-Module -Name AzureAD

If you are run the script in azure pipeline. When you install AzureAD module using Install-Module -Name AzureAD -Force in azure powershell task . You can see from the build log that AzureAD module is installed in folder C:\Program  Files\WindowsPowerShell\Modules\AzureAD\2.0.2.128:

And from the log, we can see assembly Microsoft.IdentityModel.Clients.ActiveDirectory.dll doesnot get loaded automatically.
So you can manually load it from module Azure AD installation folder: See below:
Install-Module AzureAD -Force
Import-Module -Name AzureAD
Add-Type -Path "C:\Program Files\WindowsPowerShell\Modules\AzureAD\2.0.2.128\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"

$TenantId= "..."

$ClientID ="..."

$Password = "..."
$ResourceUrl = "https://database.windows.net/"

$AuthorityUrl = "https://login.microsoftonline.com/$($TenantId)"
...
$objAuthenticationResult = $objAuthenticationContext.AcquireTokenAsync($ResourceUrl, $objClientCredential).Result

See below result.


text:
Q: Ключевое слово void, его особенности и return Пример:
public class Person {
    public static void main(String[] args) {
        Person person = new Person();
        person.run(12,2);
    }
    public void run(int a, int b){
        System.out.println(a+b);
    }
}

Выводится в консоль: 14
Пример 2:
public class Person {
    public static void main(String[] args) {
        Person person = new Person();
        System.out.println(person.run(12, 2));
    }

    public int run(int a, int b) {
        return a + b;
    }
}

Выводится в консоль: 14
Не могу понять зачем нам void, если мы можем написать public **int** run(...)
Пытаюсь разобраться с void и return.

A: Весь смысл функции с типом void - это действия без отчета. Если функция не void , то она по возвращает какой-то результат и заканчивает работу.
В первом примете, если у вас, к примеру, нет доступа к консоли, вы никогда не узнаете о том, что функция выполнена.
Во втором случаи, функция отсылает "отчет" о том, что она сделала, и вы видите результат.
И так, void используем для функций, которые работают независимо и мы не ждем от них "отчета".
Ключевое слово return прекращает выполнение функции. Можно использовать и в циклах (break), функциях.
Например,
public void count(int stop) {
     for(int i = 0; i < 100; i++) {
           System.out.println(i);
           if (i == stop) { return; }
     }
}

В данном случаи мы в функцию передаем число, после которого следует прекратить вывод чисел.

A: void означает что функция не возвращает результат, все остальные варианты (например int) будут обозначать тип возвращаемого значения и что функция обязана будет что-то вернуть.
Вот так компилироваться не будет, потому что нет return'а:
public int run(int a, int b) {
    int c = a + b;
    // return c;
}

void функции могут использовать return, но тот ничего не будет возвращать, например:
void log(String text) {
    // Если строка -- null, выходим из функции
    if (text == null) {
        return;
    }

    System.out.println("text: " + text);
}

log("123");
log(null);
log("abc");


text:
Q: Autowiring issue in Spring Cloud Stream I am trying to implement Kafka with Spring Cloud Stream. I followed instructions from the official website and developed a project. When I run the project in IntelliJ, I got following error
Parameter 0 of constructor in com.kafkastreams.service.GreetingsSender required a bean of type 'com.kafkastreams.stream.GreetingsStreams' that could not be found.

I am not sure where I did wrong, Any help would be really appreciated. Code uploaded to GitHub for reference.

A: The GreetingsConfig should be a class instead of an interface
@EnableBinding(GreetingsStreams.class)
public class GreetingsConfig
{

}


text:
Q: Exercício do livro Eloquent JavaScript Olá, sou iniciante em programação. Estou utilizando para meus estudos em JavaScript o livro Eloquent JavaScript. Não compreendo o funcionamento do código abaixo:
Código
var JOURNAL = [
   {
      "events":["carrot","exercise","weekend"],
      "squirrel":false
   },
   ...
];

function hasEvent(event, entry) {
   return entry.events.indexOf(event) != -1;
}

function tableFor(event, journal) {
   var table = [0, 0, 0, 0];
   for (var i = 0; i < journal.length; i++) {
      var entry = journal[i], index = 0;
      if (hasEvent(event, entry)) index += 1;
      if (entry.squirrel) index += 2;
      table[index] += 1;
   }
   return table;
}
console.log(tableFor("pizza", JOURNAL)); // → [76, 9, 4, 1]

JOURNAL
https://eloquentjavascript.net/2nd_edition/code/jacques_journal.js
Minha dúvida
De modo geral, sei que a função percorre o loop em busca do registro que corresponda ao evento determinado no argumento. Porém, como ela chega a esse resultado é uma incógnita para mim e pra variar não encontrei material pra tirar minhas dúvidas.

A:
function hasEvent(event, entry) {
   /*
   Retorna true/false se o array "events" do objeto "entry" contém o "event".
   Aqui, verifica-se se o índice em que o event está. Caso não exista o event selecionado,
   ele retorna -1.
   Na maioria dos casos 0 é um retorno equivalente à false no JS, mas como esta função
   retorna um índice e 0 é um índice válido, para não gerar confusão, aqui é retornado -1
   */

   return entry.events.indexOf(event) != -1;
}

function tableFor(event, journal) {
   // Esta é tabela de ocorrência de eventos
   var table = [0, 0, 0, 0];

   // Percorre o array
   for (var i = 0; i < journal.length; i++) {
      // entry é um objeto dentro de journal
      // index é definido como o primeiro índice da tabela
      var entry = journal[i], index = 0;

      // Se o event informado existe, adiciona 1 ao índice do array.
      // Se for true, index agora é 1 e aponta para o segundo índice da tabela
      if (hasEvent(event, entry)) index += 1;

      // Se a propriedade squirrel for true, adiciona 2 ao índice do array.
      // Se for true, index agora é 2 e aponta para o terceiro índice da tabela, mas se
      // a condição anterior também for true, index será na verdade 3 e apontará para
      // a quarta posição da tabela.
      if (entry.squirrel) index += 2;

      // Seleciona o índice que foi calculado anteriormente e soma um ao seu valor
      table[index] += 1;
   }
   return table;
}


text:
Q: htaccess add RedirectMatch 301 rules i add this rules to my .htaccess file:
RedirectMatch 301 /wp-content/my-image-5x5.jpg /wp-content/default-5x5.jpg

Redirect works well, but add the old image name into address.
Why? I don't need this.
What i'm get now:
www.mypage.lt/wp-content/default-5x5.jpg?file=/wp-content/my-image-5x5.jpg
What i need:
www.mypage.lt/wp-content/default-5x5.jpg

A:
Redirect works well, but add the old image name into address. Why? I don't need this.

This is because you have wordpress rules which does internal routing (to an index.php file) and the rewrite rules belong to mod_rewrite, while the RedirectMatch directive belongs to mod_alias. These modules both get applied at different points in the URL-file mapping pipeline, thus both get applied, and you end up with a mangled redirect URL. You should stick to only mod_rewrite in this instance. Try adding these rules before your wordpress rules:
RewriteEngine On
RewriteRule ^/?wp-content/my-image-5x5.jpg /wp-content/default-5x5.jpg [L,R=301]


text:
Q: Один стиль - Две анимации есть один css стиль:
.heart{
  color: transparent;
  background: linear-gradient(to left, #FF3008,#B91D28,#FF3008);
  background-size: 1000px 100%;
  animation: gradient_animate 25s linear infinite;
  animation: heart_beat 1.6s linear;
  transition: 0.25s;
}

и две анимации:
@keyframes heart_beat {
  0% {
    font-size: 15px;
  }
  25% {
    font-size: 17px;
  }
  50% {
    font-size: 15px;
  }
  75% {
    font-size: 17px;
  }
  100%{
    font-size: 15px;
  }

 @keyframes gradient_animate {
  0% {
    background-position-x: 0;
  }
  100% {
    background-position-x: 10000px;
  }
}

Как сделать, чтобы работали обе анимации, а не только одна?

A: Перечисляйте анимации через запятую:
animation: gradient_animate 25s linear infinite, heart_beat 1.6s linear;


text:
Q: Is there a way to pass an object using emit to the child component? (Angular) I've created a button whenever I click on it, it passes all values to this empty object 'product'. I'm trying to emit this object to the child component, so I can push it inside of the product empty array.
    import { Component, Input } from '@angular/core';
    import { Item } from 'src/app/Model/Item';
    import { EventEmitter } from '@angular/core';
    @Component({
      selector: 'app-item',
      templateUrl: './item.component.html',
      styleUrls: ['./item.component.css']
    })
    export class ItemComponent  {
      items: Item[] = []
      @Input() addProduct: EventEmitter<Item> = new EventEmitter
      constructor(private storeService: StoreService) {
        this.items = this.storeService.getItem()
      }
addProducts(item: Item) {
    const product = {
      id: item.id,
      img: item.img,
      name: item.name,
      type: item.type,
      price: item.price,
      available: item.available
    }
    console.log(product)
    this.addProduct.emit(product)
    }
    }

--
(template of the component)
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

{{item.name}}

{{item.type}}

{{item.available}}

{{item.price}}

                <button (click)="addProducts(item)">Add to Cart</button>

--
// another component (child)
import { Component, OnInit } from '@angular/core';
import { Item } from 'src/app/Model/Item';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit {
  product: Item[] = []
  ngOnInit(): void {
  }

addProduct(post: Item){
this.product.push(post)
}
}

--
Here is what I did in the child template.
<app-cart (addProduct)="addProduct($event)"></app-cart>

It give me an error saying, "Argument of type 'Event' is not assignable to parameter of type 'Item'.
Type 'Event' is missing the following properties from type 'Item': id, img, name, price, availablengtsc(2345)"

A: The most universal cross component solution is to use Subject. First create a service that will be used for communication (ng g service foo). Then create new subject on the service:

addProductSub = new Subject;

Import this new service to parent and to child component. To emit, just call next method on your subject and pass as argument what ever you wish to send:

this.importedService.addProductSub.next(product)

On child component, subscribe to subject and describe what to do when new data is received.

this.importedService.addProductSub.subscribe((data) => {
this.productEmptyArray = data; })

To prevent memory leakage assign subsciption (child component) to a variable and call .unsubscribe() in ngOnDestroy lifecycle hook

A: If you want to understand how things work in Angular, I suggest following the Angular tutorial.
But here's a simple example of how you can communicate between components.
Items List Component
@Component({
  selector: 'app-items-list',
  templateUrl: './app-items-list.component.html',
  styleUrls: ['./app-items-list.component.css']
})
export class ItemsListComponent {
  @Input() items: Item[] = [];
  @Output() addProduct = new EventEmitter<Item>();

  addProducts(item: Item) {
    this.addProduct.emit(item);
  }
}

You don't need to add the initial HTML markup outside of the main HTML file which is index.html

{{ item.name }}

{{ item.type }}

{{ item.available }}

{{ item.price }}

    <button (click)="addProducts(item)">Add to Cart</button>

Cart Component
@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
export class CartComponent {
  @Input() products: Item[] = [];

  addProduct(product: Item) {
    this.products.push(product);
  }
}

Parent Component (responsible for handling the business logic)
@Component({
  selector: 'app-root',
  template: `
    <app-items-list [items]="items" (addProduct)="addProduct($event)"></app-items-list>

    <app-card [products]="cartProducts"></app-card>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  readonly items = this.storeService.getItems();

  cartProducts: Item[] = [];

  constructor(private storeService: StoreService) {}

  addProduct(product: Item) {
    this.cartProducts.push(product);
  }
}

Your items list and cart components are dumb components, meaning they don't know where the data is coming from and they should stay that way (the dumb components are also reusable components). That is the role of the parent component.
The parent is fetching the data through a service and passes it to the items list component through an input.
The items list component emits an event when the Add Product button is clicked and sends the result to the parent.
The parent is responsible to distribute the selected products to the cart component.