text:
Q: Executing function on hundreds of databases I want to embed a simple piece of VBA Code in Access 2007. I need to execute this code on hundreds of different Access DBs, so I don't want to manually paste the code into each and every DB. Is it possible to do this? Maybe by way of an add-in?
Thanks
Karl
EDIT
I want to execute the following VBA code:
DoCmd.DeleteObject acTable, "LastNum"
DoCmd.TransferDatabase acLink, "ODBC Database", "ODBC;DSN=myDB;UID=User1;PWD=123;LANGUAGE=u s_english;" & "DATABASE=LastNumber", acTable, "LastNum", "LastNum"

How would I translate this into a VB addin?
The visual studio VB add-in template looks like this:
imports Extensibility
imports System.Runtime.InteropServices

<GuidAttribute("B61E2444-F46E-4591-A8BA-3D06A4E5D84C"), ProgIdAttribute("MyAddin1.Connect")> _
Public Class Connect

    Implements Extensibility.IDTExtensibility2

    Private applicationObject As Object
        Private addInInstance As Object

    Public Sub OnBeginShutdown(ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnBeginShutdown
    End Sub

    Public Sub OnAddInsUpdate(ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnAddInsUpdate
    End Sub

    Public Sub OnStartupComplete(ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnStartupComplete
    End Sub

    Public Sub OnDisconnection(ByVal RemoveMode As Extensibility.ext_DisconnectMode, ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnDisconnection
    End Sub

    Public Sub OnConnection(ByVal application As Object, ByVal connectMode As Extensibility.ext_ConnectMode, ByVal addInInst As Object, ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnConnection
        applicationObject = application
        addInInstance = addInInst

    End Sub

End Class

EDIT PART 2:
Ok, so I figured out I should do the following:
imports Extensibility
Imports System.Runtime.InteropServices
Imports Microsoft.Office.Core
Imports Access = Microsoft.Office.Interop.Access

<GuidAttribute("B61E2444-F46E-4591-A8BA-3D06A4E5D84C"), ProgIdAttribute("MyAddin1.Connect")> _
Public Class Connect

    Implements Extensibility.IDTExtensibility2

    Private applicationObject As Access.Application
    Private addInInstance As Microsoft.Office.Core.COMAddIn

    Public Sub OnBeginShutdown(ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnBeginShutdown
    End Sub

    Public Sub OnAddInsUpdate(ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnAddInsUpdate
    End Sub

    Public Sub OnStartupComplete(ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnStartupComplete
    End Sub

    Public Sub OnDisconnection(ByVal RemoveMode As Extensibility.ext_DisconnectMode, ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnDisconnection
    End Sub

    Public Sub OnConnection(ByVal application As Object, ByVal connectMode As Extensibility.ext_ConnectMode, ByVal addInInst As Object, ByRef custom As System.Array) Implements Extensibility.IDTExtensibility2.OnConnection

        applicationObject = CType(application, Access.Application)
        addInInstance = CType(addInInst, Microsoft.Office.Core.COMAddIn)

        ' This line enables VBA to call back into this object.
        addInInstance.Object = Me

    End Sub

    Public Sub ChangeLink()

        applicationObject.DoCmd.DeleteObject(Access.AcObjectType.acTable, "LastPolNum")
        applicationObject.DoCmd.TransferDatabase(Access.AcDataTransferType.acLink, "ODBC Database", "ODBC;DSN=ZACANTDB02;UID=EDIPolicyNumber;PWD=museum123;LANGUAGE=u s_english;" & "DATABASE=EDIPolicyNumber", Access.AcObjectType.acTable, "LastPolnum", "LastPolNum")

    End Sub

End Class

Now what I want is to be able to execute ChangeLink() from Access. How do I do that?

A: Depending on what the code is for, there are (at least) two different ways to do this, without working at the VB Extensions level (which is where you'd copy and paste code, at least in VBA):

*

*Make the code part of an add-in. It can then be loaded, and stay loaded and exposed, to any other application.

*If the code is working on data only, consider writing a procedure that links and unlinks the table(s) in each mdb file that needs processing.
The advantage of #2 over #1 (and, indeed, over copying and pasting code) is that you can invoke your simple routine once, not hundreds of times.

EDIT:
There are two ways to invoke an add-in, depending on who is meant to invoke its functionality, and how.

*

*Through the UI. Use this when you want an end user to be able to use it, especially practical for functionality you'll invoke often. How to:
a. Office button > Access options > Add-ins tab
b. If it's a .NET add-in (or any other non-Access add-in), choose COM Add-in from Manage dropdown. If it's Access, choose Access. Click go
c. Click Add button in the form that pops up, browse to the add-in.

You will still need to provide some sort of UI to it: a commandbar, a ribbon button, a form, something. That's a separate discussion

*

*Through code. Use this if you're just wanting to invoke it as part of some other VBA procedure.
a. VBE window > Tools > References
b. Browse button
c. Change the dropdown in file of type if you're setting up an Access add-in.

You can then call the line of code directly, as if it were part of your current project. If you wish to be more explicit, you can also invoke it by library name: MyAddInName.ChangeLink

A: Seems to me that you don't need to run this code from the Access databases -- all you need to do is run it on all the databases.
To do that, you'd use DAO to open each database in turn, delete the table, then create the link. You'll have to do both of those steps with DAO (deleting from the TableDefs collection, and adding to it) rather than with DoCmd operations (which are unavailable through DAO).
Of course, if the databases are no accessible from a central location, you can't do this. But if that's the case, how would you alter the code or invoke an add-in?
Another way to use a library database is to use Application.Run:
Application.Run "\Server\PathToAddIn\MyLibrary.FixTables"
This assumes:

*

*MyLibrary is an MDE/ACCDE.

*in MyLibrary database is a subroutine or function called FixTables that runs the code you want to execute.
Indeed, with that method, you can actually use DoCmd, since the add-in is running within Access and in the context of the currently opened database.
However, note that some people seem to have difficulties executing add-ins in this fashion (I'm currently in a long discussion with somebody in another forum who can't seem to get it to work). I've been using this method for library databases for years and years and have had no problems (as long as you specify a full path), so I'm puzzled why the ones I'm discussing it with can't seem to make it work.


text:
Q: How are I disable the RECAPTCHA on Flask appbuilder? Due to school asignment, I have to write a wedsite with flask appbuilder, when I try to add a register page, I don't need the RECAPTCHA.
So, how can I disable this?
I tried:
add RECAPTCHA_ENABLED = False in config.py  ---  [not working, the RECAPTCHA fleid still there]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Поведение сборщика мусора по отношению к структурам Недавно прочитал статью Предельная производительность: C#

Из-за того, что структуры хранятся в stack'е, они не требуют сборки мусора

поясните пожалуйста, это действительно так?
A: Краткое содержание. Нет, структуры не обязательно хранятся в стеке, а объекты — в куче. Да, с хорошими шансами структура всё же попадёт в стек. Нет, вам не стоит на это рассчитывать, пользоваться этим и пытаться оптимизировать таким образом.

На самом деле следует понимать простую вещь: выделение переменной на стеке дешевле, поскольку её можно легко уничтожить, не включая в цикл сборки мусора. Выгода на самом деле только в этом. (Аллокация что на стеке, что в куче — не более, чем увеличение одного указателя, она очень быстрая.)
Очевидно, оптимизатор будет размещать в стеке те переменные, которые, как он может доказать, не нужны после смерти текущего фрейма. Часто про структуры можно такое доказать, но не всегда. Например, структура может быть частью объекта класса, и должна умереть вместе с классом. Или метод будет неявно переписан в стиле продолжений, например, если это генератор (yield return & Co.) или Task<> с async/await. Или переменная попала в замыкание некоторой лямбда-функции. И так далее. Но обычно структуры не нужны после отработки метода, так что оптимизатор может вытеснить их в стек.
С другой стороны, про некоторые объекты можно тоже утверждать, что они не нужны после окончания фрейма — и тогда оптимизатор тоже имеет полное право (но не обязанность, конечно) разместить и их на стеке.
Обратите внимание на такую тонкость: если вы возвращаете из метода структуру, вы на самом деле возвращаете её копию, поэтому структура, с которой вы работали, может попасть в стек. С классами же не так: они копируются не по значению, а по ссылке, поэтому возвращаемый объект переживает создавшую его функцию, и следовательно не имеет права жить в стеке.
Использованы материалы из блога Эрика Липперта, на которые была ссылка выше.

Добавлю ещё пару цитат из Эрика:

Использование стека для локальных переменных-структур — всего лишь оптимизация, которую CLR выполняет для вас. Существенная особенность структур — семантика копирования по значению, а вовсе не то, что в некоторых случаях их уничтожение может быть оптимизировано рантайм-библиотекой.

В подавляющем большинстве программ, выделение и уничтожение локальных переменных не будут критически важным фактором производительности.

Превращение типа, который должен на самом деле быть ссылочным типом, в структуру — это нано-оптимизация, дающая выгоду в пару наносекунд, и вероятно не стоящая того. На вашем месте я бы проводил такую оптимизацию только если данные профилирования покажут, что существует реальная, большая проблема у ваших реальных клиентов, которую можно исправить использованием структур. Не имея таких данных на руках, я всегда бы делал выбор между классами и структурами основываясь на том, представляет ли тип семантически значение или ссылку на что-то. (То есть, имеет ли объект смысл помимо значения, содержащегося в нём, обладает ли он самостоятельной сущностью — VladD)

A:
Из-за того, что структуры хранятся в stack'е, они не требуют сборки мусора
поясните пожалуйста, это действительно так?

Если речь идет о локальных переменных, то это действительно так. GC работает с кучей.
Очевидно, что структуры не всегда хранятся в стеке. Например, если какой-то класс содержит поля, являющиеся структурами, то память под них однозначно будет выделена в куче, и, следовательно, будут уничтожаться GC.
P.S.: Если структура содержит управляемые поля, то память под эти поля выделится в куче, а в стеке окажутся лишь ссылки на эти управляемые поля. Довольно логично, но некоторые упускают это из виду.


text:
Q: Colspan is disturbing table layout Please see below html:

          Event Name

          City
          Date
          Price
          Status
          Select

                    adnanpo

                    adnanpo

                    04/20/2012
                    USD $30.00
                    Paid

                        <input class='orgOkButton' type='button' id='btnOpenOrder' name='btnOpenOrder' onclick='return openOrderWindow('/RealResource/submitorder.aspx?OId=35731&EvtId=771')

Below part is casuing the issue:

                    adnanpo

Please sse the image, the column width is disturbed!! Please help me to fix it!

A: The obvious solution is to remove the tr element that causes the problem. It does not seem to have a function here. If you just want some spacer there, put a div element between the two tables.
The problem arises because table-layout: fixed tells the browser to decide on column widths according to the first row, if widths have not been set in certain other ways. Here the first row has just one cell that spans all columns, and then the defined behavior is to divide the width evenly between the columns.
Alternatively, set the column widths explicitly, e.g. using
    <col width=220>
    <col width=120>

etc. right after each
 tag. But make sure that the sums of the widths add up to the number you set as the total width of the table (they currently don't). When col elements are used that way to set all column widths, browsers will use those exact widths without questioning (which may cause problems, but I presume you have considered them).

A: Remove 'table-layout' property in your second table and it will work fine. And close you input element (onclick="return openOrderWindow('/RealResource/submitorder.aspx?OId=35731&EvtId=771')"/>)

A: If I understand correctly, you are worried to the fact that your columns are not aligning to the top.
Let me first suggest that you use the below CSS:
table { empty-cells: show; }

This will allow the empty cell you have to fill in the space. (otherwise you can just put an   in it's blank space).
Also, I suggest you use one continuous table if you can.

A: Close your input-tag - the > is missing. If the problem is still there we can look further.

A: Yes this will be the case by using colspan in the "first row" of a table. To get around this you could do something like this (again just for the first row - you can use colspan fine further down):

adnanpo


text:
Q: Find DB principals accessing a table in Azure SQL My use case is as follows:
A table in my database is accessible by application A, B, C, etc each of whom has their own database principal. We want to start limiting the principals that can access certain table in my database, i.e. we want it such that only application A has access to said table. The idea is to relegate access to the table such that B and C calls application A instead of going to the table directly.
One naive way is to remove the principal B and C's access to the table straight away, but this will cause an application outage on B and C. A better approach is to reimplement B and C to call A first before taking away their access.
The challenge is that B and C might be accessing the table via an opaque library. We have been slowly phasing out the opaque library in favor of calling application A, but we are not 100% sure that B and C no longer accesses the table.
I have been thinking that I could check the database audit log to check which principals have been accessing that table. I have been using Azure SQL Auditing feature in my project which gives me the stats on individual statement, including its query string.
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-audit-log-format
However, the query string itself might be composed of JOINs of several tables, or the string is an EXEC of a stored procedure, i.e. the granularity of the audit is on the statement level. It doesn't tell me explicitly which tables are involved in a given statement.
Is there a way to effectively capture this information that table T has been used by principals A, B, C in the past X hours?


text:
Q: Push content to a the browser...Change the DOM? Ok. I have this passion project I've been working on.
I'm at the stage where I have a mobile app and a backend,
really I use a hosted messaging/cloud processing service as my NEW
backend, replacing my own servers.
The problem lies in my non ability to understand javascript.
I know how to go from mobile to backend and all that good stuff...
What i now what to do is simply change a DOM element.
From either GO code or Python code.
mobile ----> messaging/processing ----> browser/DOM
Basically push either a url or a string of html code so that it displays
in the browser
For this I understand my only choice is javascript.
I've looked at pusher and web sockets...
but i still dont understand how to ACTUALLY make the html element change.

A: Since you have considered Pusher, you can get the necessary keys from Pusher. Once you have access to that, in the client, you can add the Pusher js library to the html file you want to "push" events to.
Then you need to subscribe to a channel(js).
var channelName = "my-channel"
var channel = pusher.subscribe(channelName);

Once you subscribe to a channel from client. Trigger an event along with the data you need to send using python pusher server lib (python):
push = pusher.Pusher(app_id='your-pusher-app-id', key='your-pusher-key', secret='your-pusher-secret')
push['my-channel'].trigger('dom-change-event', {'data': 'data'})

You can listen to this event from your client side(js):
channel.bind("dom-change-event", function(data){ // the data you Pushed from backed
  $(".div-to-change").hide(); // with the help of jQuery select the dom, and hide it.
})

Pusher maintains a websocket connection with the client, and as soon as an event is triggered from the server, it is raised by Pusher at the client side.
DOM manipulation(change):
The DOM change that you were referring to can be done in many ways. Some are mentioned below:

*

*Have all the Content(html code) ready in your frontend and based on the server's push message you can show/hide different parts of your DOM like the one mentioned above.

*Construct the DOM on the fly with javascript based on the pusher message

*Send the HTML code from the server and simply append it to the DOM.

IMPORTANT thing to note here is that DOM manipulation is done using a library called jQuery in the above example. jQuery makes it easy for you do DOM manipulations. http://jquery.com/
Also refer to this article to get started on doing DOM manipulations(changes) using jQuery.

A: Maybe you can use reverse AJAX, I use DWR Framework
http://directwebremoting.org/dwr/documentation/reverse-ajax/index.html

A: JavaScript to change an element
HTML

some content

JavaScript
// selecting elements
var elementById = document.getElementById("myDiv");     // returns the element by id
var elements = document.getElementByClassName("divvy"); // returns array of all elements with this class

References

*

*Mozilla Developer Network


text:
Q: How do I prevent Eclipse from adding the 'final' keyword to a member variable declaration? When I type this
private MyKlass myklass;

and hit 'save' in Eclipse, it becomes this:
private final MyKlass myklass;

How do I stop Eclipse from doing this?

A: You can go to Project --> Properties --> Java Editor --> Save actions , Uncheck "Enable project specific settings"

A: You need to disable that option in your 'save actions'.
right click your project > properties, then go to java editor > save actions. go to 'configure', 'code style' tab, and you have it on the bottom ('private fields').

A: Window - Preferences - Java - Editor - Save Actions - Configure... - Code Style - Use modifier final when possible
The same option can be found in Java - Code Style - Clean up.

A: If you want to leave this feature enabled in general but turn it off for a specific field, I found a simple workaround. Just declare a protected method that assigns to this field.
protected void preventFinal() {
  field = null;
}

A: There is Section called Save Actions in Eclipse Window -> Preferences -> Java -> Editor. There You can Configure Aditional actions - > (tab) code style - > Variable declarations -> edit use of final keyword.

A: Initialize the field with null:
private File tempDir = null;


text:
Q: Qt Creator breakpoint won't stop on el capitan Last time I used Qt Creator, it was still using gdb (not lldb) and it's working just fine before upgrading to El Capitan.
Has anybody managed to debug using Qt Creator 3.4.2 and Qt 5.5.0 on El Capitan?
Can someone please give me any pointers of how to set it up correctly since mine does not even stop at breakpoint?

A: I had the same issue and clicking on Enable QML in the Debugger Settings (from Projects > Execution parameters) seems to make the breaking points work again.
I ignore why and it complains about not being able to connect to the QML debug process after the end of the debugging session, but at least the breaking points work now.
I also have lldb and not gdb.

A: QT5.6.2 with macOS 10.11.6, after a totally reinstall I finally solved it, my solution:

*

*in terminal,brew uninstal qt(maybe this is the problem)

*run MaintenanceTool.app,see Uninstall and Reinstall QtSDK on Mac system

*reboot

*reinstall Qt

A: This is just a blind guess, i had the same problem. I solved it with the following configuration the .pro:
CONFIG -= app_bundle

Looks like debugging doesn't work inside a bundle.


text:
Q: Skeleton CSS classes grids I'm creating a grid system in wordpress using Skeleton.css
The tutorial shows the following markup for the header, here you can see the logo has has a 3 classes, - five columns and clearfix

    get_template_directory_uri(); ?>/img/logo.svg">

But when I look at the skellton css I cannot see a class of 'five' So i changed it to .five.columns  But his make no difference, I i create a border around the class .five.columns, it does not show up am I missing something obvious?
  .one.column,
  .one.columns                    { width: 4.66666666667%; }
  .two.columns                    { width: 13.3333333333%; }
  .three.columns                  { width: 22%;            }
  .four.columns                   { width: 30.6666666667%; }
  .five.columns                   { width: 39.3333333333%; }
  .six.columns                    { width: 48%;            }
  .seven.columns                  { width: 56.6666666667%; }
  .eight.columns                  { width: 65.3333333333%; }
  .nine.columns                   { width: 74.0%;          }
  .ten.columns                    { width: 82.6666666667%; }
  .eleven.columns                 { width: 91.3333333333%; }
  .twelve.columns                 { width: 100%; margin-left: 0; }

  .one-third.column               { width: 30.6666666667%; }
  .two-thirds.column              { width: 65.3333333333%; }

  .one-half.column                { width: 48%; }

  /* Offsets */
  .offset-by-one.column,
  .offset-by-one.columns          { margin-left: 8.66666666667%; }
  .offset-by-two.column,
  .offset-by-two.columns          { margin-left: 17.3333333333%; }
  .offset-by-three.column,
  .offset-by-three.columns        { margin-left: 26%;            }
  .offset-by-four.column,
  .offset-by-four.columns         { margin-left: 34.6666666667%; }
  .offset-by-five.column,
  .offset-by-five.columns         { margin-left: 43.3333333333%; }
  .offset-by-six.column,
  .offset-by-six.columns          { margin-left: 52%;            }
  .offset-by-seven.column,
  .offset-by-seven.columns        { margin-left: 60.6666666667%; }
  .offset-by-eight.column,
  .offset-by-eight.columns        { margin-left: 69.3333333333%; }
  .offset-by-nine.column,
  .offset-by-nine.columns         { margin-left: 78.0%;          }
  .offset-by-ten.column,
  .offset-by-ten.columns          { margin-left: 86.6666666667%; }
  .offset-by-eleven.column,
  .offset-by-eleven.columns       { margin-left: 95.3333333333%; }

  .offset-by-one-third.column,
  .offset-by-one-third.columns    { margin-left: 34.6666666667%; }
  .offset-by-two-thirds.column,
  .offset-by-two-thirds.columns   { margin-left: 69.3333333333%; }

  .offset-by-one-half.column,
  .offset-by-one-half.columns     { margin-left: 52%; }

}

/* Larger than mobile */
@media (min-width: 400px) {}

Many thanks

A: Here is a fiddle with some styling for height and color to make it obvious. Is your div 0px height? Check it with your developer tools in the browser - Chrome Developer Tools website.
https://jsfiddle.net/p1w61hmt/.

.five.columns { width: 39.3333333333%; }
.columns { background: red; }

Its probably some pasting errors but your HTML is not valid and your css looks like an incomplete snippet.


text:
Q: How do I document the return type which comes from another method? When a method is returning the result of a call to another method, what is the sensible way to document the return type?
class A
{
    /**
     * @return [How do I know here what bar will return?]
     */
    public function foo()
    {
        $b = new B();
        return $b->bar();
    }
}

class B
{
    /**
     * @return string
     */
    public function bar()
    {
        return 'baz';
    }
}

How do I document A::foo() return type, when it is not certain what B::baz() will return? In the future, B::baz() may change, in which case the return type of A::foo() unknowingly changes.
Is this a code smell? Can the wider code be designed so that the return type of A::foo() is predictable even if B::baz() changes?

A: If we're speaking on higher type-strict and you should refactor your code and tell to bar() what kind of type will be returned : (PHP >7.0)
class A
{
    /**
     * @return string
     */
    public function foo()
    {
        $b = new B();
        return $b->bar();
    }
}

class B
{
    /**
     * @return string
     */
    public function bar() : string
    {
        return 'baz';
    }
}

Ref: http://php.net/manual/en/migration70.new-features.php
But in your case I'll put B\bar as return type, because you're returning instance of class B and method bar.
         * @return B\bar
         */
        public function foo()
        {

A: If you fear that the bar() return type could change without regard to what your foo() expects, then I'd say it is indeed a code smell.  There's apparently no contract between the two, so there's no trust from A to B.
More practically, bar() is documented to return string, so by having foo() coded to return bar()'s actual return, then foo() should be documented to also return string.  There won't be an automatic way for the doc generator / IDE to keep up with this for you, if that's what you're after.
The other doc-only option would be to mark foo()'s return as mixed, thereby telling the reader "I make no guarantees on what I return, because I'm only giving you what bar() gave me, and I don't know ahead of time what that will be".


text:
Q: Mixing Numerical Range and inner product Let $\mathbf{A}$ and $\mathbf{b}$ be a symmetric $N\times N$ real matrix and $N\times 1$ real vector respectively. Then consider the set of points in $\mathbb{R}^2$ defined as
\begin{align}
\mathbb{S}=\{\left(\mathbf{u}^T\mathbf{A}\mathbf{u},\mathbf{b}^T\mathbf{u}\right)\in\mathbb{R}^2,\mathbf{u}^T\mathbf{u}=1\}
\end{align}
That $\mathbb{S}$ is bounded is obvious. I was wondering if it had any other properties. In particular I am looking at convexity, similar to numerical ranges. If not, what are the conditions on $\mathbf{A}$ and $\mathbf{b}$ for the convexity and so on.
Motivation:
Consider the optimization problem
\begin{align}
&\min_{\mathbf{u}\in \mathbb{R}^N}\mathbf{u}^T\mathbf{A}\mathbf{u}+\mathbf{b}^T\mathbf{u}  \\\
\mbox{subject to }\\\
&\mathbf{u}^T\mathbf{u}=1
\end{align}
Then using the definition of $\mathbb{S}$ as earlier, I can write the above problem as
\begin{align}
\min_{(x,y)\in\mathbb{S}}x+y
\end{align}
Thus if $\mathbb{S}$ is convex, the above problem will be convex.

A: I don't know if your question admits a general answer, but for sure $\mathbb{S}$ is not always convex. Indeed, let us consider the following example:
$$\mathbf{A} = \begin{bmatrix}1 & 0 \\ 0 & 2\end{bmatrix}, \quad \mathbf{b} = \begin{bmatrix}1\\ 0\end{bmatrix}.$$
Then we have $\mathbb{S}=\{(u_1^2+2u_2^2,u_1): \mathbf{u}^T \mathbf{u} = 1\}$. With few simple manipulations, we can parametrize $\mathbb{S}$ in the following way:
$$\mathbb{S} = \{(2-\cos^2(t),cos(t)): t \in [0,2\pi)\},$$
and this is a continuous section of the parabola $\{x = 2-y^2\}$, that is not convex in $\mathbb{R}^2$.

A: We can solve directly your problem. We assume that $b$ is not an eigenvector of $A$. Let $f:u\rightarrow u^TAu+b^Tu,\;g:u\rightarrow u^Tu-1$.
There is a real $\lambda$ and a unitary $u=(u_i)_i$ s.t. $Df_u+\lambda Dg_u=0$, that is $(A+\lambda I)u=-b/2, \;u^Tu=1$. We may assume that $A=diag(\lambda_i)_i$ where the $\lambda_i$ are real. One obtains, for every $i$, $u_i=\dfrac{-b_i}{2(\lambda+\lambda_i)}$ with $\sum_i\dfrac{b_i^2}{(\lambda+\lambda_i)^2}=4$. Thus $\lambda$ is a root of a polynomial $P$ of degree $2N$. The sequel is easy.
EDIT: The degree of the previous polynomial $P$ is $2N$ (edited). Unfortunately, $P$ seems to have no special properties ; indeed numerical experiments, when $N=3,4$, give for $P$ a Galois group equal to $S_6,S_8$.


text:
Q: use plural verbs or singular verbs with the uncountable noun in this case? As far as I know, 'spending' is a uncountable noun. In the Cambridge dictionary, it means 'the money that is used for a particular purpose, especially by a government or organization' and is labelled as uncountable. But there is a confusing sentence in which I am not sure whether the word is still uncountable, at least semantically.

There were decreases in spending on things such as books and on other workers' salaries.

It seems to me there are two sums of money, one for books and another for workers' salaries. Although I know 'spending' is a uncountable word, it's a bit weird for me. How should I understand this usage in the example? If I use the noun phrase in the following sentence, the verb is still singular, isn't it?

The spending on things such as books and on other workers' salaries is $2,000 and $3,000 respectively.

A: Because spending is, as you say, a non-count noun, I would not use it when referring to specific amounts of money (like $2,000 or $3,000). I would use a different word, for example:

The expenditures for things such as books and salaries are $2,000 and $3,000 respectively.

But in the given example sentence specific amounts were not listed, so "decreases in spending" is perfectly acceptable.


text:
Q: Почему сайт долго грузится после простоя? Доброго времени суток. Уже который раз натыкаюсь на проблему - сайт (что на PHP, что на NodeJS) после длительного простоя (без обращений хотя бы минут 10, а то и меньше) грузится в 5-20 раз медленнее. К примеру на nodeJS вместо 35мс - 450мс, на php5 вместо 35мс - 980мс. Сразу после этого в два раза быстрее, третий запрос - как и должен.К архитектуре самих сайтов это никакого отношения не имеет (сам писал, кеш живёт далеко не 10 минут, а, как правило, 30 дней). К СУбД, возможно тоже - Nodejs-сайт использует mongodb, а все php сайты - mySQL. Соответственно, я делаю вывод, что это уже сама ОС как то оптимизирует свои расходы.Вопрос: что это и как от этого избавиться\это отключить? На данный момент у меня одна VPS, на OpenVZ, с Ubuntu-server на борту.
A: Логируйте "медленные" запросы к базе (MySQL) в конфиге my.cnf добавьте примерно так
*
*; логгируем запросы длиннее 5 секунд
*long_query_time = 10
*log-slow-queries = /var/log/mysqld-slow-query.log
*; логгируем запросы, не использующие индексы
*log-queries-not-using-indexesПотом внимательно изучаем логи


text:
Q: Only download audio from source mp4 link I want to be able to download just the audio track of an mp4 file from a source url, without actually having to first download the mp4 file and then extracting the audio. Is this possible? The motivation is that downloading the audio has much much smaller file size while downloading the video is a whole lot more.

A: Yes, It is possible. Just download the moov atom, looks at the chunks/chunk offsets for the audio track. Download those ranges and repackage into a suitable container for the codec.


text:
Q: Do While Loop Does not Stop I created this macro to delete rows with a 0 value on Column 5, starting on Row6. It should stop on the Row with an empty cell on Column 2.
My data has about 600 rows only. However, after Row 20 or so, the spreadsheet just kept waiting and I need to press Esc Key to stop it. When it stops, it is at the last row but it does not do the last part that is to sum column 4.
If I press the macro again, it works fine with the new data and adds the sum in column 4. (by the way, it is my first macro in excel).
Sub DeleteRows()
'
' DeleteRows Macro
' Keyboard Shortcut: Ctrl+d
'

    Cells(6, 5).Select
    Do While (Cells(ActiveCell.Row, 2) <> "")
        Do While (Cells(ActiveCell.Row, 5) = 0)
            Rows(ActiveCell.Row).Select
            Selection.Delete Shift:=xlUp
        Loop
        Cells(ActiveCell.Row + 1, 5).Select
    Loop

    Cells(ActiveCell.Row, 4).Select
    Dim cel1 As String, cel2 As String
    cel1 = ActiveCell.Offset(-1, 0).End(xlUp).Address
    cel2 = ActiveCell.Offset(-1).Address
    ActiveCell.Value = "=sum(" & (cel1) & ":" & (cel2) & ")"

End Sub

A: Loop from the bottom up when deleting rows or you risk skipping over rows.
sub deleteRows()
    dim i as long
    with worksheets("Sheet1")
        for i=.cells(.rows.count, "B").end(xlup).row to 6 step -1
            if .cells(i, "E").value2 =0 then
                .cells(i, "E").entirerow.delete
            end if
        next i
        with .cells(.rows.count, "D").end(xlup)
            .offset(1, 0).formula = "=sum(" & .parent.range(.cells(1), .cells(1).end(xlup)).address & ")"
        end with
    end with

end sub

*

*Indent your code.

*How to avoid using Select in Excel VBA

*Define a parent worksheet reference for all cells and range calls.


text:
Q: Multiple arguments in toast notification I can send and receive single params using
string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<wp:Notification xmlns:wp=\"WPNotification\">" +
                   "<wp:Toast>" +
                        "<wp:Text1>" + TextBoxTitle.Text.ToString() + "</wp:Text1>" +
                        "<wp:Text2>" + TextBoxSubTitle.Text.ToString() + "</wp:Text2>" +
                        "<wp:Param>/Evento.xaml?eid=3709626441465918</wp:Param>" +
                   "</wp:Toast> " +
                "</wp:Notification>";

But if I try to send multiple params like this:
string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<wp:Notification xmlns:wp=\"WPNotification\">" +
                   "<wp:Toast>" +
                        "<wp:Text1>" + TextBoxTitle.Text.ToString() + "</wp:Text1>" +
                        "<wp:Text2>" + TextBoxSubTitle.Text.ToString() + "</wp:Text2>" +
                        "<wp:Param>/Evento.xaml?eid=3709626441465918;lat=28.5146;lng=77.1972;EventName=aa</wp:Param>" +
                   "</wp:Toast> " +
                "</wp:Notification>";

On receiving end i get eid itself equal to
"3709626441465918;lat=28.5146;lng=77.1972;EventName=aa""3709626441465918;lat=28.5146;lng=77.1972;EventName=aa"

I tried "&" instead of ";" and toast notification won't even work.

A: The issue is that you are misusing the semi-colon character in the URI.
A semi-colon is a reserved, sub-delimiter character and should be encoded (as %3B) when used as you are.
/Evento.xaml?eid=3709626441465918;lat=28.5146;lng=77.1972;EventName=aa

should be
/Evento.xaml?eid=3709626441465918%3Blat=28.5146%3Blng=77.1972%3BEventName=aa


text:
Q: Save JSON in Local Storage after the fetch Sorry if this was posted a lot, I read through several articles but could not find the solution. So, I'm fetching a large JSON from this API, and I would like to cache the response somehow in the localStorage, so the next time the page loads, the scripts first checks if there is an object with the requested ID inside the JSON, and renders the content if there is one - and if there isn't, goes of to the API to fetch it.
I was thinking of setting up two fetch() functions, and this is what I have:
   fetch(url + id)
        .then((response) => {
            localStorage.setItem('myResponse', response);
        })
        .catch((error) => {
            console.log(error);
        })

Then, check if there is something saved inside the localStorage, and if it is good, use it to render the HTML, if not, go on to another fetch to get it from the API.
  if(localStorage) {
     createHTML(localStorage.myResponse);
  } else {
     fetch(url + id)
         .then(response => response.json())
         .then(data => createHTML(data))
  }

But, in the first fetch, if I use JSON.stringify(response), it just shows it as an empty object, so it the localStorage it looks like: myResponse - {}. If I do console.log(response.json()); on the first fetch, it shows Promise {<pending>}.
I've tried to make something out of that, but without results...any help much appreciated!

A: response.json() is a Promise, it needs to be either awaited, or chained a .then(); If you simply log it as is, all you'll get is Promise  {<pending>} because it hasn't resolved yet.
fetch(url + id)
        .then( response => response.json() )
        .then( json => {
            localStorage.setItem('myResponse', JSON.stringify(json));
        })

Or with the async/await syntax :
const response = await fetch(url + id);
const json = await response.json();
localStorage.setItem('myResponse', JSON.stringify(json));


text:
Q: Blender crashes when opens Shader Editor there!
I haven't been able to use the Shader Editor. Im using Blender 2.9.1. I have proved different versions and only works in my computer in Blender 2.69.
1- I open Blender 2.9.1 (empty project)
2-I switch to Shader Editor (Shift F3)
3- Blender crashes
This hapens with Cycles, Eevee and Workbench. Any suggestions?
PC info:
Ubuntu 14.04
Intel core i7
7.7 Gb RAM
Intel corporation 3rd Gen Core Graphics Controller (rev 09)
This is the crash log file of Blender:
Blender 2.90.1, Commit date: 2020-09-23 06:43, Hash 3e85bb34d0d7

bpy.context.space_data.context = 'RENDER' # Property
bpy.context.area.ui_type = 'ShaderNodeTree' # Property
backtrace

/snap/blender/47/blender(BLI_system_backtrace+0x20) [0x81fdd40]
/snap/blender/47/blender() [0xe2329d]
/lib/x86_64-linux-gnu/libc.so.6(+0x36cb0) [0x7f6f851e7cb0]
/usr/lib/x86_64-linux-gnu/dri/i965_dri.so(+0x2ea2fe) [0x7f6f6785d2fe]
/usr/lib/x86_64-linux-gnu/dri/i965_dri.so(+0x2e13f6) [0x7f6f678543f6]
/usr/lib/x86_64-linux-gnu/dri/i965_dri.so(+0x2e1496) [0x7f6f67854496]
/usr/lib/x86_64-linux-gnu/dri/i965_dri.so(+0x2e07c8) [0x7f6f678537c8]
/usr/lib/x86_64-linux-gnu/dri/i965_dri.so(+0x2e2c25) [0x7f6f67855c25]
/usr/lib/x86_64-linux-gnu/dri/i965_dri.so(+0x2a7b45) [0x7f6f6781ab45]
/usr/lib/x86_64-linux-gnu/dri/i965_dri.so(+0x2e2178) [0x7f6f67855178]
/usr/lib/x86_64-linux-gnu/dri/i965_dri.so(+0x2a7b45) [0x7f6f6781ab45]
/usr/lib/x86_64-linux-gnu/dri/i965_dri.so(+0x2e12ca) [0x7f6f678542ca]
/usr/lib/x86_64-linux-gnu/dri/i965_dri.so(+0x2e076c) [0x7f6f6785376c]
/usr/lib/x86_64-linux-gnu/dri/i965_dri.so(+0x2a7b45) [0x7f6f6781ab45]
/usr/lib/x86_64-linux-gnu/dri/i965_dri.so(+0x2eb3fa) [0x7f6f6785e3fa]
/usr/lib/x86_64-linux-gnu/dri/i965_dri.so(+0x423131) [0x7f6f67996131]
/usr/lib/x86_64-linux-gnu/dri/i965_dri.so(+0x37b1e0) [0x7f6f678ee1e0]
/usr/lib/x86_64-linux-gnu/dri/i965_dri.so(+0x21823e) [0x7f6f6778b23e]
/usr/lib/x86_64-linux-gnu/dri/i965_dri.so(+0x1308ea) [0x7f6f676a38ea]
/snap/blender/47/blender(GPU_shader_create_ex+0x687) [0x6f1a7a7]
/snap/blender/47/blender(GPU_shader_create+0x12) [0x6f1b032]
/snap/blender/47/blender(GPU_shader_create_from_arrays_impl+0xb7) [0x6f1b0f7]
/snap/blender/47/blender(GPU_shader_get_builtin_shader_with_config+0x1c2) [0x6f1b772]
/snap/blender/47/blender(GPU_batch_program_set_builtin_with_config+0xd) [0x6f03b9d]
/snap/blender/47/blender() [0x184275c]
/snap/blender/47/blender(nodelink_batch_end+0x28) [0x1843d98]
/snap/blender/47/blender(node_draw_nodetree+0x11d) [0x184781d]
/snap/blender/47/blender() [0x1847967]
/snap/blender/47/blender(drawnodespace+0x449) [0x1847dc9]
/snap/blender/47/blender(ED_region_do_draw+0x811) [0x1487631]
/snap/blender/47/blender(wm_draw_update+0x4da) [0x10deb5a]
/snap/blender/47/blender(WM_main+0x30) [0x10dcab0]
/snap/blender/47/blender(main+0x317) [0xd5ec67]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5) [0x7f6f851d2f45]
/snap/blender/47/blender() [0xe1fa83]
Python backtrace


text:
Q: Server memory usage reporting incorrect? I have a Windows 2016 Server (128GB Ram), running SQL Server 2016, and I'm seeing some unusual figures on the memory usage reporting.
I'm used to seeing SQL Server using a lot of memory (we have this one limited to 96GB) but I'm seeing this being reported strangely in Task Manager.  I am seeing 75% memory usage but only 755.5MB against SQL Server.  While there are other services running in the background, the total does not come anywhere near 75% of 128GB.

The 75% is the being reflected in Performance manager as I'd expect, with 96% being committed to SQL.

Internally in sql server, I am getting similar figures from internal reporting.
SELECT  (physical_memory_in_use_kb / 1024)          Phy_Memory_usedby_Sqlserver_MB
,       (locked_page_allocations_kb / 1024)         Locked_pages_used_Sqlserver_MB
,       (virtual_address_space_committed_kb / 1024) Total_Memory_UsedBySQLServer_MB
,       process_physical_memory_low
,       process_virtual_memory_low
  FROM  sys.dm_os_process_memory;

I've been asked to investigate why the task manager is showing such a low usage when we would expect it to be so much higher.  If there is a general misunderstanding on my part here, then please let me know.  If there are any further tests I can perform to help track this down then I'm happy to do so.
Many thanks in advance.

A: Taskmanager only shows processes that allocate memory via VirtualAlloc. When Lock Pages is set in SQL Server, AllocateUserPhysicalPages is used for allocating and this does not show up in TaskManager. So you cannot rely on TaskManager for SQL memory usage.


text:
Q: Split part of string after character, always same amount I am looking to get part of a string after an = sign that will always be the same amount of characters, after the =.
Ex.
str = [<User id=000000000000000000 name='test' discriminator='0001'] -

I want to be able to get the 000000000000000000 and nothing else. The total length of the string may change, but the numbers I am looking to collect are always going to be 18 numbers, after the id=.

A: You could use re.findall here:
inp = "str = [<User id=000000000000000000 name='test' discriminator='0001']"
id = re.findall(r'\bid=(\d+)\b', inp)[0]
print(id)  # 000000000000000000


text:
Q: Handling custom variables on HTML POST I got a Servlet that can handle a Post form and save all the defined variables to MYSQL.
I'm now attempting to write another Servlet that will read all the parameters and their values with req.getParameterMap() and then send them to the database, in case a parameter that was not specified gets logged as well.
The code I have for the first servlet is bellow:
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
import java.sql.*;

public class QueryServlet extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException, ServletException
    {
        String transId = req.getParameter("transId") == null ? "" : req.getParameter("transId");
        String instId = req.getParameter("instId") == null ? "" : req.getParameter("instId");
        String cartId = req.getParameter("cartId") == null ? "" : req.getParameter("cartId");
        String desc = req.getParameter("desc") == null ? "" : req.getParameter("desc");
        String cost = req.getParameter("cost") == null ? "" : req.getParameter("cost");
        String amount = req.getParameter("amount") == null ? "" : req.getParameter("amount");
        String currency = req.getParameter("currency") == null ? "" : req.getParameter("currency");
        String name = req.getParameter("name") == null ? "" : req.getParameter("name");
        String transStatus = req.getParameter("transStatus") == null ? "" : req.getParameter("transStatus");
        String transTime = req.getParameter("transTime") == null ? "" : req.getParameter("transTime");
        String cardType = req.getParameter("cardType") == null ? "" : req.getParameter("cardType");
        Connection conn = null;
        PrintWriter out = res.getWriter();
        try {
            conn = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/orders", "root", "root");

            String sqlStr = "insert into orderdetails "
                + "values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            try (PreparedStatement stmt = conn.prepareStatement(sqlStr)) {
                stmt.setString(1, transId);
                stmt.setString(2, instId);
                stmt.setString(3, cartId);
                stmt.setString(4, desc);
                stmt.setString(5, cost);
                stmt.setString(6, amount);
                stmt.setString(7, currency);
                stmt.setString(8, name);
                stmt.setString(9, transStatus);
                stmt.setString(10, transTime);
                stmt.setString(11, cardType);
                int updateCount = stmt.executeUpdate();
                for (Enumeration<String> en = req.getParameterNames(); en.hasMoreElements();) {
                    String paramName = en.nextElement();
                    String paramValue = req.getParameter(paramName);
                }
            }
    } catch (SQLException ex) {
        ex.printStackTrace();
        }
    }
}

For the second Servlet, I managed to get it to be able to read all the parameters and their values and display them on the webpage but I have no clue on how I can then get them to the database, either by creating the columns for the parameters or having them created already and just creating row values.
Could you provide me some guidance or examples to follow?
Bellow is the code for the second Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class QueryServlet extends HttpServlet
{
    protected void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
    {
        PrintWriter pw=res.getWriter();
        res.setContentType("text/html");

        Map m=req.getParameterMap();
        Set s = m.entrySet();
        Iterator it = s.iterator();

            while(it.hasNext()){

                Map.Entry<String,String[]> entry = (Map.Entry<String,String[]>)it.next();

                String key             = entry.getKey();
                String[] value         = entry.getValue();

                pw.println("Key is "+key+"
");

                    if(value.length>1){
                        for (int i = 0; i < value.length; i++) {
                            pw.println("
" + value[i].toString() + "

");
                        }
                    }else
                            pw.println("Value is "+value[0].toString()+"
");

                    pw.println("-------------------
");
            }

        pw.close();
    }
}

Any help will be greatly appreciated.
Cheers

A: Well first you need to start specifying columns when doing inserts, unless you want your code to break later when you add a column to the table.  The way you're doing it you always have to include all the columns and in the defined order.
If you specify the columns, then you can use only the ones you want, and in any order you want.
 insert into tablename (col1, col2) values('col1val', 'col2val');
 insert into tablename (col2, col1, col5) values('col2val', 'col1val', 'col5val');

From there you should be able to figure out how to modify the second servlet to insert using the Key and Value variables, and creating the guts to go inside the column list and value list parts of the SQL statement.


text:
Q: Using C library (spglib) from C++ I'm simply trying to use functions from a C-libary (the Space Group library spglib) inside my C++ code. The library is already compiled and installed in an Anaconda environment.
A minimal example looks like this:
extern "C"
{
#include "spglib.h"
}

#include <iostream>

static void test_spg_get_symmetry(void);

int main(void)
{
    test_spg_get_symmetry();

    return 0;
}

static void test_spg_get_symmetry(void)
{
    double lattice[3][3] = {{4, 0, 0}, {0, 4, 0}, {0, 0, 3}};
    double position[][3] =
        {
            {0, 0, 0},
            {0.5, 0.5, 0.25},
            {0.3, 0.3, 0},
            {0.7, 0.7, 0},
            {0.2, 0.8, 0.25},
            {0.8, 0.2, 0.25},
            {0, 0, 0.5},
            {0.5, 0.5, 0.75},
            {0.3, 0.3, 0.5},
            {0.7, 0.7, 0.5},
            {0.2, 0.8, 0.75},
            {0.8, 0.2, 0.75}};
    int types[] = {1, 1, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2};
    int num_atom = 12;
    int max_size = 50;
    int i, j, size;
    int rotation[max_size][3][3];
    double translation[max_size][3];

    double origin_shift[3] = {0.1, 0.1, 0};
    for (i = 0; i < num_atom; i++)
    {
        for (j = 0; j < 3; j++)
        {
            position[i][j] += origin_shift[j];
        }
    }

    printf("*** Example of spg_get_symmetry (Rutile two unit cells) ***:\n");
    size = spg_get_symmetry(rotation,
                            translation,
                            max_size,
                            lattice,
                            position,
                            types,
                            num_atom,
                            1e-5);
    for (i = 0; i < size; i++)
    {
        printf("--- %d ---\n", i + 1);
        for (j = 0; j < 3; j++)
            printf("%2d %2d %2d\n", rotation[i][j][0], rotation[i][j][1], rotation[i][j][2]);
        printf("%f %f %f\n",
               translation[i][0], translation[i][1], translation[i][2]);
    }
}

I'm compiling with a command similar to this:
g++ -g symm.cpp -o main.exe -I/miniconda3/env/include -Lminiconda3/env/aims-env/lib/libsymspg.a
But I get a linking error every time:
undefined reference to 'spg_get_symmetry'.
What am I missing? Any help is appreciated.


text:
Q: Simple javaScript bug in game - Image not moving vertically This game starts after user clicks on first image - which then disappears and the game image (div) appears.
I have all the functionality working including score, timer of 30 seconds... But one simple thing is missing which I cannot figure out.
Image is supposed to move randomly in any direction but only moves horizontally. I have implemented move method similarly for both horizontal direction by changing style: left property dynamically, but the vertical change is unresponsive when I try to change style: top.
Please help. Thanks in advance.
<BASE HREF="http://my.campuscruiser.com/cruiser/waldenu/tushar.gerg/game.html"/>

<title>Image click Game!</title>

Score: <input type= "text" id="score" size="3" value="0"></form>   Game ends in 30 seconds -- HURRY

Game Ended - 30 Seconds up

Score: <input type= "text" id="Finalscore" size="3"></form>

A: You have defined top as a global variable which is conflicting with the default window.top variable. Try renaming it to something else or better yet, don't make it a global variable to begin with. (Also, if you do a search and replace, don't change the im.style.top instance at Line 82.)


text:
Q: Extract lines from multiple files based on condition in one line I have a number of directories containing text files with a pattern like this:
class FeatureFE():
    meta_data = MetaData(
        name='COOL_FEATURE',
        sub_type='EXTRA_COOL_FEATURES',
        required_data=[accounts, logs],
        has_graph=True,
        x_axis_label='Time',
        y_axis_label='Foo',
        graph_caption='Description of my feature',
        priority='low',
    )

The task I have been given is to go through each .py file and, if has_graph=True, extract the name, required_data and graph_caption - the end goal being a CSV structured like this:
name, required_data, graph_caption
'COOL_FEATURE', [accounts, logs],'Description of my feature',

This definitely seems doable with awk/sed/grep, but I'm struggling to get there. So far I've managed this:
grep -E -B 4 -A 5 "has_graph=True" feature_17.py | tr -s ' ' | grep '^ name\|^ required_data\|^ graph_caption' | sed 's/.*=//'

Which returns
'COOL_FEATURE',
[accounts, logs],
'Description of my feature',

for one file, but nothing when run on *.py.
Help much appreciated!

A: Whenever you have name=value pairs in your data I find it best to first create an array of those mappings and then simply access the values by their names. For example, with GNU awk for the 3rd arg to match() and ENDFILE:
$ cat tst.awk
BEGIN {
    OFS = ","
    numNames = split("name required_data graph_caption",names)
}

match($0,/^\s*(\w+)\s*=\s*(.*\S)\s*,\s*$/,a) {
    name  = a[1]
    value = a[2]
    name2value[name] = value
}

ENDFILE {
    if ( name2value["has_graph"] == "True" ) {
        if ( !doneHdr++ ) {
            for (nameNr=1; nameNr<=numNames; nameNr++) {
                name = names[nameNr]
                printf "%s%s", name, (nameNr<numNames ? OFS : ORS)
            }
        }
        for (nameNr=1; nameNr<=numNames; nameNr++) {
            name  = names[nameNr]
            value = name2value[name]
            gsub(/"/,"\"\"",value)
            printf "\"%s\"%s", value, (nameNr<numNames ? OFS : ORS)
        }
    }
    delete name2value
}

$ awk -f tst.awk file
name,required_data,graph_caption
"'COOL_FEATURE'","[accounts, logs]","'Description of my feature'"

I added double quotes before printing to make sure the output is a valid CSV even when your values contain , (as [accounts, logs] does) and/or double quotes.
To use the above with find I'd do this:
find . -name '*.py' -exec awk -f tst.awk {} +

but remove this part of the script first:
        if ( !doneHdr++ ) {
            for (nameNr=1; nameNr<=numNames; nameNr++) {
                name = names[nameNr]
                printf "%s%s", name, (nameNr<numNames ? OFS : ORS)
            }
        }

so you don't get a header line printed once for every batch of files passed to awk from find and just add the header line manually later or print it before running the script. There's other ways to deal with that but that's the simplest.

A: Could you please try following(considering that your python files will have only 1 occurrence of this class). Tested and written in GNU awk.
awk '
BEGIN{
  FS="="
  s1="\047"
  OFS=","
  print "name, required_data, graph_caption"
}
/has_graph=True/{
  found=1
}
found && /name/{
  sub(/,/,"",$2)
  name=$2
  next
}
found && /required_data/{
  sub(/,/,"",$2)
  data=$2
}
found && /graph_caption/{
  sub(/,/,"",$2)
  print s1 name s1,s1 data s1,s1 $2 s1
  nextfile
}
'  *.py

A: Perl solution:
perl -0777 -nE 'for my $key (qw( name required_data graph_caption )) {
                  ($h{$key}) = /\b$key=(.*),/;
                }
                say join ",", @h{qw{ name required_data graph_caption }};
               ' -- *.py

*

*-n reads the input record by record, executing the code for each one

*-0777 reads the whole file instead of reading it line by line

*the %h hash is populated with values captured from a regex match, \b stands for a "word boundary"


text:
Q: Unable to compile ESP-IDF example project I'm trying to compile my first ESP32 example project.
I set up Visual Studio Code with all the latest tools. (Python, toolschain, etc).
I'm not sure what exactly I need as I'm new in this environment, so maybe I missed something.
I followed the user guide on how to create and compile the first project, I used the Blink project from the example folder.
Here is what I get.
> Executing task: cmake -G Ninja .. <

-- Project is not inside a git repository, or git repository has no commits; will not use 'git describe' to determine PROJECT_VER.
-- Building ESP-IDF components for target esp32s2
-- Checking Python dependencies...
Python requirements from C:\Users\dmitryke\esp\esp-idf\requirements.txt are satisfied.
-- Project sdkconfig file C:/ESP32_projects/blink/sdkconfig
Loading defaults file C:/ESP32_projects/blink/sdkconfig.defaults...
-- Components:
-- Component paths:
-- Configuring done
-- Generating done
-- Build files have been written to C:/ESP32_projects/blink/build

The terminal will be reused by tasks, press any key to close it.

> Executing task: cmake --build . <

[1/1] Linking C executable blink.elf
FAILED: blink.elf
cmd.exe /C "cd . && C:\Users\dmitryke\.espressif\tools\xtensa-esp32s2-elf\esp-2020r3-8.4.0\xtensa-esp32s2-elf\bin\xtensa-esp32s2-elf-gcc.exe -mlongcalls   CMakeFiles/blink.elf.dir/project_elf_src.c.obj  -o blink.elf  -Wl,--cref -Wl,--Map=C:/ESP32_projects/blink/build/blink.map  -fno-rtti  -fno-lto && cd ."
c:/users/dmitryke/.espressif/tools/xtensa-esp32s2-elf/esp-2020r3-8.4.0/xtensa-esp32s2-elf/bin/../lib/gcc/xtensa-esp32s2-elf/8.4.0/../../../../xtensa-esp32s2-elf/bin/ld.exe: c:/users/dmitryke/.espressif/tools/xtensa-esp32s2-elf/esp-2020r3-8.4.0/xtensa-esp32s2-elf/bin/../lib/gcc/xtensa-esp32s2-elf/8.4.0/../../../../xtensa-esp32s2-elf/lib/no-rtti/crt0.o:(.literal+0x0): undefined reference to `main'
collect2.exe: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.
The terminal process "C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command cmake --build ." terminated with exit code: 1.

Terminal will be reused by tasks, press any key to close it.

I removed everything from the blink.c to avoid code errors.
blink.c
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "sdkconfig.h"

/* Can use project configuration menu (idf.py menuconfig) to choose the GPIO to blink,
   or you can edit the following line and set a number here.
*/
#define BLINK_GPIO 0x01

void app_main(void)
{
    while(1) {    }
}

Another issue, there is an option to run  idf.py menuconfig.
Sometimes it works and sometimes it says:
C:\ESP32_projects\blink>idf.py menuconfig
'idf.py' is not recognized as an internal or external command,
operable program or batch file.

Any help will be appreciated!

A: All ESP IDF tasks (cmake, idf.py, etc) must be run inside a prepared environment. I would start by losing the VSC (because it's just another potential failure point) and using the basic ESP IDF command prompt. Try running idf.py menuconfig, idf.py build and idf.py -p COMx flash for configuring, building and flashing your test project.
Once you've verified that the ESP IDF environment and your project works, go back to VSC and see what's wrong there.
As a working example, this is how I compile the same sample project on my machine (Linux, ESP IDF v4.2.1) from scratch:
$ cp -r ~/esp-idf/examples/get-started/blink/ .
$ cd blink
$ idf.py build
Running cmake in directory /home/tarmo/tmp/espidftest/blink/build
Executing "cmake -G Ninja -DPYTHON_DEPS_CHECKED=1 -DESP_PLATFORM=1 -DCCACHE_ENABLE=0 /home/tarmo/tmp/espidftest/blink"...
-- Found Git: /usr/bin/git (found version "2.30.2")
-- IDF_TARGET not set, using default target: esp32
-- The C compiler identification is GNU 8.4.0
-- The CXX compiler identification is GNU 8.4.0

[SNIP]

esptool.py v3.0
Generated /home/tarmo/tmp/espidftest/blink/build/bootloader/bootloader.bin
[934/934] Generating binary image from built executable
esptool.py v3.0
Generated /home/tarmo/tmp/espidftest/blink/build/blink.bin

Project build complete. To flash, run this command:
/home/tarmo/espressif/python_env/idf4.2_py3.9_env/bin/python ../esp-idf/components/esptool_py/esptool/esptool.py -p (PORT) -b 921600 --before default_reset
 --after hard_reset --chip esp32  write_flash --flash_mode dio --flash_size detect --flash_freq 40m 0x1000 build/bootloader/bootloader.bin 0x8000 build/partition_table/partition-table.bin 0x10000 build/blink.bin
or run 'idf.py -p (PORT) flash'
$ ls -lha
drwxr-xr-x 8 tarmo tarmo 4,0K juuni  4 12:26 build
-rw-r--r-- 1 tarmo tarmo  234 juuni  4 12:25 CMakeLists.txt
-rw-r--r-- 1 tarmo tarmo 1,5K juuni  4 12:25 example_test.py
drwxr-xr-x 3 tarmo tarmo 4,0K juuni  4 12:26 main
-rw-r--r-- 1 tarmo tarmo  177 juuni  4 12:25 Makefile
-rw-r--r-- 1 tarmo tarmo  157 juuni  4 12:25 README.md
-rw-r--r-- 1 tarmo tarmo  33K juuni  4 12:25 sdkconfig
-rw-r--r-- 1 tarmo tarmo    3 juuni  4 12:25 sdkconfig.defaults

A: The command window is less concerning, i got it working.
My main problem is main not being linked.

A: I had the same problem with building the ESP-project in VS Code, but found a solution: The project needs to be created in a folder with a different name than the example name.
I tried the blink project and it works when creating it in c:\esp-idf\ rather than in c:\esp-idf\blink. The latter will make a folder named blink within the blink folder.

A: You can add this code to your main(), checking your esp-idf environment first:
    gpio_reset_pin(BLINK_GPIO);
    gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT);
    while(1) {
        printf("Turning off the LED\n");
        gpio_set_level(BLINK_GPIO, 0);
        vTaskDelay(1000 / portTICK_PERIOD_MS);
        printf("Turning on the LED\n");
        gpio_set_level(BLINK_GPIO, 1);
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }

Don't forget to close the previous terminal and open it again.


text:
Q: iMac 2011 - two external monitors I have an iMac from 2011 and there is already one external monitor connected via minidisplay port to dvi adapter. Today I wanted to connect another one, as the iMac features 2 minidisplay/thunderbolt ports. I bought a second adapter and hoped it would work just as easy – plug in and done. But the screen of that monitor stayed black, nothing happened at all. Do I need another adapter? Some additional software?

A: I believe you would like to take a look at this Endgadget link that explains (even with a video) what you need.
If you have two Thunderbolt ports (only the 27inch iMac), then those can support two external displays (confirmed by Apple, you can google that).
(this has been also asked on SuperUser)


text:
Q: Is the ECONNREFUSED problem a known issue with (i)WebDriver? On my current project we're using iWebDriver to run acceptance tests on our CI server.
Occasionally, we see the error:
Connection refused - connect(2) (Errno::ECONNREFUSED)

Thus far, we have found no pattern to this failure; whenever we encounter it, we simply restart the build and it generally runs successfully. I'd say this happens roughly 10% of the time.
Before everybody jumps on me for ignoring a real problem: we capture screenshots whenever there is a test failure. Whenever this particular error occurs, there doesn't appear to be an actual problem based on the captured screenshot. It is not the same as a simple timeout error (where, e.g., an element isn't found in time); in that case we see a different message: execution expired (Timeout::Error).
We're all kind of under the assumption that this is due to some erratic bug in WebDriver itself. Which tempts me to implement a script that simply detects the above error message and restarts the build if it's detected but otherwise yields real failures. (Actually, I've already done that; I simply haven't configured our build server to use it, yet.)
Have others seen this intermittent error? Is it a known issue? Does it actually indicate a real problem that we should investigate on our end (in which case, where do we start)?


text:
Q: How to port ScrollView written in kotlin to flutter Scrolling view with scaling and panning in Kotlin.
I would like to port this to flutter, but GestureLisner is not working and I don't know how to solve it.
The XML Layout itself is displayed, but the GestureLisner for scaling and panning is not detected.
Can anyone help me with a solution?
Below is the code created in Kotlin.
We are aiming to port this.
class MainActivity : AppCompatActivity() {
private lateinit var mScaleGestureDetector: ScaleGestureDetector
private lateinit var mPanGestureDetector: GestureDetector

private var mScaleFactor = 1.0f
private var mTranslationX = 0f
private var mTranslationY = 0f
private var mImageWidth = 0f
private var mImageHeight = 0f
private var mDefaultImageWidth = 0f
private var mDefaultImageHeight = 0f
private var mViewPortWidth = 0f
private var mViewPortHeight = 0f

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContentView(R.layout.activity_main)

    mImageView.setImageDrawable(getDrawable(R.drawable.hongkong))

    mScaleGestureDetector = ScaleGestureDetector(this, ScaleListener())
    mPanGestureDetector = GestureDetector(this, PanListener())

    val viewTreeObserver = mImageView.viewTreeObserver
    if (viewTreeObserver.isAlive) {
        viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                mImageView.viewTreeObserver.removeOnGlobalLayoutListener(this)

                val imageAspectRatio = mImageView.drawable.intrinsicHeight.toFloat() / mImageView.drawable.intrinsicWidth.toFloat()
                val viewAspectRatio = mImageView.height.toFloat() / mImageView.width.toFloat()

                mImageWidth =  scrollView.height.toFloat()
                mImageHeight =  scrollView.height.toFloat()

                mDefaultImageWidth = mImageWidth
                mDefaultImageHeight = mImageHeight

                mViewPortWidth = mImageView.width.toFloat()
                mViewPortHeight = mImageView.height.toFloat()
            }
        })
    }
}

override fun dispatchTouchEvent(event: MotionEvent): Boolean {
    mScaleGestureDetector!!.onTouchEvent(event)
    mPanGestureDetector!!.onTouchEvent(event)

    return mPanGestureDetector!!.onTouchEvent(event)
}

private inner class PanListener : GestureDetector.SimpleOnGestureListener() {
    override fun onScroll(
        e1: MotionEvent, e2: MotionEvent,
        distanceX: Float, distanceY: Float
    ): Boolean {
        val translationX = mTranslationX - distanceX
        val translationY = mTranslationY - distanceY

        adjustTranslation(translationX, translationY)

        return true
    }
}

private inner class ScaleListener : ScaleGestureDetector.SimpleOnScaleGestureListener() {
    override fun onScale(detector: ScaleGestureDetector): Boolean {
        mScaleFactor *= mScaleGestureDetector.scaleFactor
        mScaleFactor = Math.max(1.0f, Math.min(mScaleFactor, 5.0f))
        mImageView.scaleX = mScaleFactor
        mImageView.scaleY = mScaleFactor
        mImageWidth = mDefaultImageWidth * mScaleFactor
        mImageHeight = mDefaultImageHeight * mScaleFactor

        adjustTranslation(mTranslationX, mTranslationY)

        return true
    }
}

private fun adjustTranslation(translationX: Float, translationY: Float) {
    val translationXMargin = Math.abs((mImageWidth - mViewPortWidth) / 2)
    val translationYMargin = Math.abs((mImageHeight - mViewPortHeight) / 2)

    if (translationX < 0) {
        mTranslationX = Math.max(translationX, -translationXMargin)
    } else {
        mTranslationX = Math.min(translationX, translationXMargin)
    }

    if (mTranslationY < 0) {
        mTranslationY = Math.max(translationY, -translationYMargin)
    } else {
        mTranslationY = Math.min(translationY, translationYMargin)
    }

    scrollview.translationX = mTranslationX
    scrollview.translationY = mTranslationY
}
}

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:id="@+id/linerLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/image1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:contentDescription="@string/no_image"
                android:src="@drawable/comic_2" />

            <ImageView
                android:id="@+id/image2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:contentDescription="@string/no_image"
                android:src="@drawable/thumb_02" />

            <ImageView
                android:id="@+id/image3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:contentDescription="@string/no_image"
                android:src="@drawable/thumb_03" />

            <ImageView
                android:id="@+id/image4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:contentDescription="@string/no_image"
                android:src="@drawable/thumb_04" />

            <ImageView
                android:id="@+id/image5"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:contentDescription="@string/no_image"
                android:src="@drawable/thumb_05" />

            <ImageView
                android:id="@+id/image6"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:contentDescription="@string/no_image"
                android:src="@drawable/thumb_06" />

        </LinearLayout>

    </ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

 import 'package:flutter/foundation.dart';
 import 'package:flutter/gestures.dart';
 import 'package:flutter/material.dart';
 import 'package:flutter/rendering.dart';
 import 'package:flutter/services.dart';

 void main() {
   runApp(const MyApp());
 }

 class MyApp extends StatelessWidget {
   const MyApp({Key? key}) : super(key: key);

   // This widget is the root of your application.
   @override
   Widget build(BuildContext context) {
     return MaterialApp(
       title: 'Flutter Demo',
       theme: ThemeData(
         primarySwatch: Colors.blue,
       ),
       home: const MyHomePage(title: 'Flutter Demo Home Page'),
     );
   }
 }

 class MyHomePage extends StatefulWidget {
   const MyHomePage({Key? key, required this.title}) : super(key: key);

   final String title;

   @override
   State<MyHomePage> createState() => _MyHomePageState();
 }

 class _MyHomePageState extends State<MyHomePage> {

   @override
   Widget build(BuildContext context) {

     const String viewType = '<plugins-scroll_widget>';
     const Map<String, dynamic> creationParams = <String, dynamic>{};

     return PlatformViewLink(
         viewType: viewType,
         surfaceFactory:
             (context, controller) {
           return AndroidViewSurface(
             controller: controller as AndroidViewController,
             gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{},
             hitTestBehavior: PlatformViewHitTestBehavior.translucent,
           );
         },
         onCreatePlatformView: (params) {
           return PlatformViewsService.initSurfaceAndroidView(
             id: params.id,
             viewType: viewType,
             layoutDirection: TextDirection.ltr,
             creationParams: creationParams,
             creationParamsCodec: const StandardMessageCodec(),
             onFocus: () {
               params.onFocusChanged(true);
             },
           )
             ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated)
             ..create();
         },
       );
   }
 }


text:
Q: Grep for a variable in a file I want to grep the following patterns in the file /root/scripts/list.txt:
'^"123"^'
'^"456"^'
'^"789"^'

So I write code like below in my shell script
myvar=-F -e '^"123"^' -e '^"456"^' -e '^"789"^'
grep $myvar /root/scripts/list.txt

(Pattern will change every time, so I created a string with myvar)
It is giving a null output, but when I run the command below I'm getting the required output:
grep -F -e '^"123"^' -e '^"456"^' -e '^"789"^' /root/scripts/list.txt

Can some one please help me?
Thanks in advance.


text:
Q: couldn't understand app review process on google play Does google review app everytime when we upload new android app bundle because I uploaded new .aab file in production and status is written "in review".

A: Yes it does review the app every time except for the internal test track.


text:
Q: Perform arithmetic on a singly linked list which represent a large number I have a linked list which represents the large number 2253239487.
class ListNode:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

def __repr__(self):
    return '{0}'.format(self.val)

The ListNode instance is populated as below:
h1 = ListNode(2)
n2 = ListNode(2)
n3 = ListNode(5)
n4 = ListNode(3)
n5 = ListNode(2)
n6 = ListNode(3)
n7 = ListNode(9)
n8 = ListNode(4)
n9 = ListNode(8)
n10 = ListNode(7)

h1.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
n5.next = n6
n6.next = n7
n7.next = n8
n8.next = n9
n9.next = n10

Now, I want to divide the number by 3 and return the answer as a whole number.
I have written below code but it is giving wrong result:
sum = 0
head = h1
while head.next:
     sum += head.val
     head = head.next
return sum // 3

There is an assumption that the "sum" integer is too big for the integer object. What is the best way to directly calculate avg without storing sum in memory?

A: If you can't represent the linked list as an integer, then you need to do long division on the values in the list. You can do this by iterating divide by 3 over the nodes to generate new nodes, and then joining the nodes before finally outputting the result:
divisor = 3
nodes = []
head = h1
r = 0
while head:
    v = r * 10 + head.val
    q = v // divisor
    r = v % divisor
    if q != 0 or head != h1:
        nodes.append(ListNode(q))
    head = head.next

for i, n in enumerate(nodes[:-1]):
    n.next = nodes[i+1]

head = nodes[0]
while head:
    print(head.val, end='')
    head = head.next

print()

Output:
751079829

Note that if the divisor could be larger than the input number (for testing purposes) then this would give a string of 0s as the result. You can work around this by changing the if test to only add a leading 0 if we are at the last node in the list:
divisor = 3
nodes = []
head = h1
r = 0
while head:
    v = r * 10 + head.val
    q = v // divisor
    r = v % divisor
    if q != 0 or len(nodes) > 0 or head.next is None:
        nodes.append(ListNode(q))
    head = head.next

for i, n in enumerate(nodes[:-1]):
    n.next = nodes[i+1]

head = nodes[0]
while head:
    print(head.val, end='')
    head = head.next

print()

Note also that if you generate your list in reverse order you can save all the assignments to .next:
n10 = ListNode(7)
n9 = ListNode(8, n10)
n8 = ListNode(4, n9)
n7 = ListNode(9, n8)
n6 = ListNode(3, n7)
n5 = ListNode(2, n6)
n4 = ListNode(3, n5)
n3 = ListNode(5, n4)
n2 = ListNode(2, n3)
h1 = ListNode(2, n2)


text:
Q: Issue on the material card holder I cant seem to figure out why is everything not constrained inside the holder because in other insatances even though it is almost an identical code it displays everything perfectly inside the material card holder with the name age hobby picture displayed according to how I coded it but for this it just displayed a white screen and in the design I could see that nothing is constrained to the material card holder and I cant seem to figure out why is that happening.
Here is the code:
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    app:cardCornerRadius="4dp"
    app:cardElevation="4dp"
    tools:visibility="invisible">
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ImageView
            android:id="@+id/item_image"
            "layout stuffs"
            android:scaleType="centerCrop"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="parent" />
        <TextView
            android:id="@+id/dog_name"
            "layout stuffs"
            android:textAppearance="@style/TextAppearance.MaterialComponents.Headline6"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/item_image" />
        <TextView
            android:id="@+id/dog_age"
            "layout stuffs"
            android:textAppearance="@style/TextAppearance.MaterialComponents.Body1"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/dog_name" />
        <TextView
            android:id="@+id/dog_hobbies"
            "layout stuffs"
            android:textAppearance="@style/TextAppearance.MaterialComponents.Body1"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/dog_age" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>```

Here is the design view:
[design view of the code](https://i.stack.imgur.com/0nu0j.png)

I was expecting all of the item to be constrained inside the view so that it can be displayed. Everything should be constrained under the Material card holder and displayed accordingly. I cannot seem to find the issue, would be glad to have someone to guide me on the issue I am facing


text:
Q: Prove or disprove: $\exists x \forall y \,\,\varphi \models \forall y \exists x \,\ \varphi$
Prove or disprove: $\exists x \forall y \,\,\varphi \models \forall y
\exists x \,\ \varphi$
where $\varphi$ is a first-order-logic formula

About notation: I call LHS as $A$ and RHS as $B$. Then $A \models B$ means that $B$ is true in every structure in wich $A$ is true. Now question is if this is the case here, with proof.
Let's say we have $\varphi : = R(x,y)$ where $R$ stands for relation.
Then LHS says that

For some $x$, all $y$ are such that $R(x,y)$

RHS says that

For any $y$, there is a $x$ such that $R(x,y)$

Now if we expand those two sentences, we have for LHS:

There exists a $x \in \mathbb{N}$, such that for any number $y$, we have that $x
>y$. This is wrong because there can't be number that is greater than
  all numbers.

For RHS we have:

For any $y \in \mathbb{N}$, there exists a number $x$ such that $x >
y$. This is correct because for any number there is always a bigger
  number.

For this reason we have no model here and this means the statement is false.
I like to know if this is correct pls because I need it for exam and I would do it like that in exam if they ask similar question?

A: All you have done so far is to show one particular structure in which $A$ is false and $B$ is true. This tells you nothing about $A\vDash B$, which is about structures where $A$ is true. It does not care what might happen to $B$ in structures that don't satisfy $A$.

A: You are given $\exists x\forall y\;\varphi(x,y)$. So let $x_0$ be such that $\forall y\;\varphi(x_0,y)$. In particular,  for arbitrary $y$, we have $\varphi(x_0,y)$.
Now let $y$ be arbitrary. As just seen, we have $\varphi(x_0,y)$, hence $\exists x\;\varphi(x,y)$. As $y$ was arbitrary, $\forall y\exists x\;\varphi(x,y)$, as was to be shown.

A: 'Informal semantical proof': If A is true then there is some $x$ such that for all $y$ such that $R(x,y)$. OK, so let's call this x 'Bob'. So, 'Bob' stands in relation $R$ to everything (including itself). But then it is true that for everything, there is something that stands in relation $R$ to it (namely 'Bob'!). So, for all $y$ there is some $x$ such that $R(x,y)$. So, B is true.
And here is a formal proof in Fitch:


text:
Q: Keeping Xcode from stripping out unused symbols from a static library I've built a static library that I'm my iOS binary is linking in.  Code stripping is off, etc. for the static library, and I can see the symbols in the archive (via nm).
So, I link that library into my application as a framework.  But, I'm not actually calling that function directly.  As a result, I can see the symbols that I'm calling directly in my binary, but not the ones that aren't called.  But, since I actually want these symbols to be there at runtime, I'm compiling with -all_load.
But, this seems to place an unnecessary burden on the users of the library.  Is there something I can add in the static library that enforces this, rather than relying on the user of the library?

A: Depending on what you are trying to accomplish, you can precisely control which symbols are dead-stripped and which are always loaded, even if the user of the library doesn't actually use them.
The easiest way is to create a library initialization function that references the exact symbols you don't want dead-stripped.  This is precise, and saves you the burden of wrestling with the linker command-line options, which may insulate you from (unlikely) tool behavior changes down the road.
Frameworks have automatic initializers (quite handy) that can be called automatically when the framework is loaded at runtime, right after any static variables are initialized.
__attribute__((constructor))
static void MyModuleInitializer()
{
    static BOOL initialized = NO;
    if (!initialized) {

        // References to symbols that should be kept around.

        initialized = YES;
    }
}

Just for grins, automatic finalizers are also supported using the __attribute__((destructor)) decorator.


text:
Q: C++ regex match, not matching So I have the following text in a std::string:
2: enp1s0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc fq_codel state DOWN mode DEFAULT group default qlen 1000\    link/ether 68:f7:28:4e:7b:ac brd ff:ff:ff:ff:ff:ff

and I am trying to extract the 'enp1s0' and '68:f7:28:4e:7b:ac' using the following regex:
\d{1}:\s+(\w+).*link\/ether\s{1}([a-z0-9:]+)

which works in an online regex tester, but this C++ code does not detect a match:
std::regex interface_address("^\\d{1}:\\s+(\\w+).*link\\/ether\\s{1}([a-z0-9:]+)");
std::smatch pieces;
if (std::regex_match(line, pieces, interface_address)) {
    std::string name = "";
    std::string address = "";
    for (size_t i = 0; i < pieces.size(); ++i) {
        auto submatch = pieces[i];
        if (i == 0) {
            name = submatch.str();
        } else if (i == 1) {
            address = submatch.str();
        }
    }
    std::cout << name << address << std::endl;
}

where am i going wrong?

A: The regex_match fails when the string doesnt match EXACTLY the pattern. Note that the brd ff:ff:ff:ff:ff:ff part of the string isnt being matched. All you need to do, then, is to append a .* to the pattern:
^\\d{1}:\\s+(\\w+).*?link\\/ether\\s{1}([a-z0-9:]+).*

Also, for that example, the loop isnt necessary. You can use:
if (std::regex_match(line, pieces, interface_address)) {
    std::string name = pieces[1];
    std::string address = pieces[2];
    std::cout << name << address << std::endl;
}


text:
Q: when i try send sms in sim800l with at+cmgs i have got error hi it is my code to send "hello world" to my phone number with ardiuno and sim800l but i get Error and when i use "gsm.println("at+cmee=1");" i will get  cms error 305
what is your suggestion to send normal sms with ardiuno and sim800l?
    void sends()
  {
  Serial.println("try send sms");
  gsm.println("AT+CSCS=\"GSM\"");
  delay(500);
  gsm.println("at+cmee=0");
 if(gsm.available())
  {
    txt1 = gsm.readString();
    Serial.println(txt1);
  }
  gsm.println("at+cmgf=1");
 delay(500);

 if(gsm.available())
  {
    txt1 = gsm.readString();
    Serial.println(txt1);
  }

delay(500);
  gsm.print("at+cmgs=\"+98914xxxxxxx\"");
  delay(50);
gsm.println("HELLO WORLD");
delay(50);
gsm.println((char)26);

 // gsm.write(26);
delay(500);
  if(gsm.available())
  {
    txt1 = gsm.readString();
    Serial.println(txt1);
  }
}

how can i send sms in ardiuno?
this link suggested by a friend
+CMS ERROR: 305 when sending SMS
but it is vb and i used  gsm.println("AT+CSCS="GSM"");

A: Change
gsm.print("at+cmgs=\"+98914xxxxxxx\"");

to
gsm.println("at+cmgs=\"+98914xxxxxxx\"");

The AT command need to be terminated by a \r\n before you inputing your sms message.


text:
Q: Вылетает ошибка при умножении двух матриц Пытался написать программу, умножающую две матрицы. Но вылетает ошибка, после чего программа завершается. Скрин и код прилагаются. Заранее благодарю!
main.cpp

#include <iostream>
#include "classes.h"

using namespace std;

int main()
{
    {
        Matrix obj1, obj2;
        cout << "Matrix 1: " << obj1 << "\nMatrix 2: " << obj2 << endl;
        Matrix result(obj1 * obj2);
        cout << "Resulting matrix: " << result << "\nYay!\n`";
        obj2 = result;
        cout << "After obj2 = result: " << obj2 << "That's it. Bye!\n";
    }
    return 0;
}

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

methods.cpp

#include <iostream>
#include "classes.h"

Matrix::Matrix()
{
    std::cout << "\nEnter the size of the matrix.\nEnter rows: ";
    std::cin >> rows;
    std::cout << "Enter columns: ";
    std::cin >> cols;
    matrix = new double* [rows];
    for (int i = 0; i < rows; i++)
    {
        matrix[i] = new double[cols];
    }
    for (int i = 0; i < rows; i++)
    {
        std::cout << "\nRow #" << i + 1 << ":\n";
        for (int j = 0; j < cols; j++)
        {
            std::cout << "  column #" << j + 1 << ":  ";
            std::cin >> matrix[rows][cols];
        }
    }
}

Matrix::Matrix(int _rows, int _cols)
{
    rows = _rows;
    cols = _cols;
    matrix = new double* [rows];
    for (int i = 0; i < rows; i++)
    {
        matrix[i] = new double[cols];
        for (int j = 0; j < cols; j++)
        {
            matrix[i][j] = 0;
        }
    }
}

Matrix::Matrix(const Matrix& obj)
{
    rows = obj.rows;
    cols = obj.cols;
    matrix = new double* [rows];
    for (int i = 0; i < rows; i++)
    {
        matrix[i] = new double[cols];
    }
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            matrix[rows][cols] = obj.matrix[rows][cols];
        }
    }
}

Matrix::~Matrix()
{
    std::cout << "\nMatrix deleted.\n";
    for (int i = 0; i < rows; i++)
    {
        delete[] matrix[i];
    }
    delete[] matrix;
    matrix = nullptr;
}

Matrix Matrix::operator=(const Matrix& obj)
{
    if (this == &obj)
        return *this;
    this->~Matrix();
    rows = obj.rows;
    cols = obj.cols;
    matrix = new double* [rows];
    for (int i = 0; i < rows; i++)
    {
        matrix[i] = new double[cols];
    }
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            matrix[rows][cols] = obj.matrix[rows][cols];
        }
    }
    return *this;
}

Matrix operator*(const Matrix& obj1, const Matrix& obj2)
{
    Matrix temp(obj1.rows, obj2.cols);
    if (obj1.cols != obj2.rows)
    {
        std:: cout << "\nThe matrix multiplication is impossible due to a rows and cols dismatch. \nPlease, enter another matrix sizes.\n\n";
        return obj1;
    }
    for (int i = 0; i < obj1.rows; i++)
    {
        for (int j = 0; j < obj2.cols; j++)
        {
            for (int k = 0; k < obj1.cols; k++)
            {
                temp.matrix[i][j] += obj1.matrix[i][k] * obj2.matrix[k][j];
            }
        }
    }
    return temp;
}

std::ostream& operator<<(std::ostream& os, const Matrix& obj)
{
    std::cout << "\n\n";
    for (int i = 0; i < obj.rows; i++)
    {
        std::cout << "   | ";
        for (int j = 0; j < obj.cols; j++)
        {
            std::cout << obj.matrix[i][j] << "  ";
        }
        std::cout << "\b|  \n";
    }
    return os;
}

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

classes.h

#ifndef CLASSES_H
#define CLASSES_H
#include <iostream>

class Matrix
{
private:
    double** matrix;
    int rows, cols;
public:
    Matrix();
    Matrix(int _rows, int _cols);
    Matrix(const Matrix& obj);
    ~Matrix();
    Matrix operator=(const Matrix& obj);
    friend Matrix operator*(const Matrix& obj1, const Matrix& obj2);
    friend std::ostream& operator<<(std::ostream& os, const Matrix& obj);
};

#endif CLASSES_H

A: Должно быть matrix[i][j], а не matrix[rows][cols].


text:
Q: Total magnetic moment in an atom I have a doubt regarding the calculation of total angular momentum of electron in an atom. Which is the right way to do it?
Method 1:
Total magnetic moment
$$
\begin{align}
\vec{\mu_J} &= \vec{\mu_L}+\vec{\mu_S}
            \\&= g_L \mu_B\vec{L}+g_s \mu_B\vec{S}.
\end{align}
$$
Since $g_L = -1$ and $g_S=-2$,
$$\begin{align}\vec{\mu_J}& = -\mu_B\vec{L}-2\mu_B\vec{S}
            \\&= -\mu_B(\vec{L}+2\vec{S}),\end{align}$$
where
$$|\mu_J|=\mu_B|\vec{L}+2\vec{S}|$$
and
$$|\mu_J|=\mu_B\sqrt{|\vec{L}|^2+4|\vec{S}|^2+4\vec{L}.\vec{S}}.$$
Method 2:
Here we calculate Landé $g$ factor as
$$g_J=1+\frac{j(j+1)+s(s+1)-l(l+1)}{2j(j+1)},$$
and then substitute in the equation:
$$|\mu_J| = g \frac{e\hbar}{2m}\sqrt{j(j+1)}.$$
I wanted to know what is wrong with method 1.

A: The problem is that you do two different things with the two methods. Method 1 gives you the (uniteresting) length of the combined mangetic moment vector while Method 2 gived you its expectation value in the quantization direction which is $\vec{J}=\vec{L}+\vec{S}$. $\vec{\mu}_J$ does obviously not point in the same direction as $\vec{J}$, because of the different g-factors $g_L$ and $g_S$.
If you want to use Method 1 to reproduce the $g_J$ from Method 2 you have to do the following:
$$\vec{\mu}_J\cdot\vec{J}=-\mu_B(\vec{L}+2\vec{S})(\vec{L}+\vec{S}).$$
Compute this using $\vec{L}\cdot\vec{S}=\frac{1}{2}(\vec{J}^2-\vec{L}^2-\vec{S}^2)$ and you will reproduce $g_J$.


text:
Q: Exe file failed to execute I'm building a simple Prediction GUI using Python and tkinter. It works fine in the Jupyter notebook and when I converted the file to .py using nbconvert. As I want to pass around the tool to people who don't have python, I have converted it to exe using pyinstaller --onefile Prediction.py.
The exe is build without error, but when I run the exe in the cmd I got FileNotFoundError: [Errno 2] File b'SRV_Platforms_Yield.csv' does not exist: b'SRV_Platforms_Yield.csv'[5404] Failed to execute script Prediction which means that it cannnot find my file for training. How can I make it work?
This is the code for my prediction tool:
import pandas as pd
import numpy as np

df = pd.read_csv('SRV_Platforms_Yield.csv')
df.rename(columns={'REPORT FAMILY':'REPORT_FAMILY', 'FPY+':'FPY'},inplace=True)
df['FPY'] = df['FPY'].apply(lambda x: np.nan if x in ['-'] else x[:-1]).astype(float)/100
df = df[['REPORT_FAMILY', 'FPY_TESTED', 'FPY']]
df['REPORT_FAMILY'] = df['REPORT_FAMILY'].astype(str)

from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
df["REPORT_FAMILY"] = le.fit_transform(df["REPORT_FAMILY"])
print("Class mapping: ")
for i, item in enumerate(le.classes_):
    print(item, "-->", i)

x = df.iloc[:,:-1]
y = df.iloc[:,-1]

from sklearn.ensemble import RandomForestRegressor
rf = RandomForestRegressor(n_estimators= 1000, random_state=42)
rf.fit(x, y)

#tkinter GUI
import tkinter as tk
#creating the window
window = tk.Tk()
window.title("FPY+ Prediction")

canvas1 = tk.Canvas(window, width = 550, height = 250)
canvas1.pack()

t = tk.Text(window)
canvas1.create_window(270, 250)
for i, item in enumerate(le.classes_):
    t.insert(tk.INSERT, f"{item}-->{i}\n")
t.pack()

# New_Interest_Rate label and input box
label1 = tk.Label(window, text='Type REPORT FAMILY: ')
canvas1.create_window(50, 100, window=label1)

entry1 = tk.Entry (window) # create 1st entry box
canvas1.create_window(270, 100, window=entry1)

# New_Unemployment_Rate label and input box
label2 = tk.Label(window, text='Type FPY_TESTED: ')
canvas1.create_window(60, 130, window=label2)

entry2 = tk.Entry (window) # create 2nd entry box
canvas1.create_window(270, 120, window=entry2)

def values():
    global New_REPORT_FAMILY #our 1st input variable
    New_REPORT_FAMILY = entry1.get()

    global New_FPY_TESTED #our 2nd input variable
    New_FPY_TESTED = float(entry2.get())

    Prediction_result  = ('Predicted FPY: ', rf.predict([[New_REPORT_FAMILY ,New_FPY_TESTED]]))
    label_Prediction = tk.Label(window, text= Prediction_result, bg='yellow')
    canvas1.create_window(260, 180, window=label_Prediction)

button1 = tk.Button (window, text='Predict FPY',command=values, bg='grey') # button to call the 'values' command above
canvas1.create_window(270, 150, window=button1)

window.mainloop()

A: you should put your file 'SRV_Platforms_Yield.csv' and .exe file in the same folder


text:
Q: Добавление записи в таблицу через Entity добавляет запись в связанную таблицу Есть класс
public class DbItem
{
    public int Id { get; set; }
    public Products Product { get; set; }
}

где класс Products - это таблица в БД
При добавлении новой DbItem в БД , происходит попытка добавления Products в соответствующую таблицу в БД. Но добавления не просходит и выскакивает ошибка, что элемент с таким ключом уже существует.
Мне нужно добавить новый элемент только в таблицу DbItem
Сам Products Product беру из БД как AsNoTracking()
Как обновлять и добавлять элемента только в таблицу DbItem ?
Class Products
[Table("Products")]
public class Products
{
    [Key]
    public int Id { get; set; }

    [Display(Name = "Name")]
    [Required(ErrorMessage = "Введите название")]
    public string ProductName { get; set; }

    [BindProperty]
    [Display(Name = "Category")]
    [Required(ErrorMessage = "Не выбрана категория")]
    public int Category { get; set; }

    [NotMapped]
    public string CategoryName { get; set; }
}

Update
var product = _context.Product.AsNoTracking().Where(x=>x.ProductId == Id).FirstOrDefault();

var dbitem = new Dbitem{Id = 1, Product = product};
_context.Dbitem.Add(dbitem);
_context.SaveChanges();

A: Судя по вашему описанию, текущий код выглядит примерно так:
var product = context.Products.AsNoTracking().First();

var dbItem = new DbItem { Product = product };

context.DbItems.Add(dbItem);

context.SaveChanges();

Да, в этом случае возникнет исключение, т. к. сущность product не отслеживается контекстом.
Чтобы добавление прошло успешно, нужно либо убрать AsNoTracking(), либо присоединить сущность к контексту, тогда она станет отслеживаться.
context.Attach(product);

context.SaveChanges();


text:
Q: Why am I getting "double free or corruption" with the following code? I am writing a simple program to make sure I fully understand how pointers in C work as I go through Harvard's CS50. Here is the code:
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int *a = malloc(sizeof(int));
    *a = 5;
    printf("the address of pointer a is: %p\n", &a);
    printf("the address that a is pointing to is: %p\n", a);
    printf("the contents of a are: %i\n", *a);

    printf("please enter a new value for a: \n");
    scanf("%i", a);
    printf("the address of pointer a is: %p\n", &a);
    printf("the address that a is pointing to is: %p\n", a);
    printf("the contents of a are: %i\n", *a);

    int *b = malloc(sizeof(int));
    *b = 7;
    printf("the address of pointer b is: %p\n", &b);
    printf("the address that b is pointing to is: %p\n", b);
    printf("the contents of b are: %i\n", *b);

    a = b;
    printf("setting a = b\n");
    printf("the address of pointer a is: %p\n", &a);
    printf("the address that a is pointing to is: %p\n", a);
    printf("the contents of a are: %i\n", *a);

    free(a);
    free(b);
}

It compiles w/o issues, but when executed, I get the following error: "* Error in `./address': double free or corruption (fasttop): 0x00000000018b7030 *
Aborted"
This problem goes away if I get rid of either the free(a) or free(b) statements, however valgrind reveals a memory leak:
"==9626== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==9626==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9626==    by 0x4206AD: main (address.c:6)"
I've looked through the other questions here and other websites that mention double free corruption, but still can't figure out quite what the issue is... I have a feeling that the answer is simple, and the issue probably lies in the statement "a = b", however I don't really get why I wouldn't be able to have one pointer point to a memory location that another one is pointing to, and then free the memory taken by both pointers...

A: You're doing this:
 a = b; // a now points to the same thing as b does

...

free(a);
free(b);

... which is semantically equivalent to
free(b);
free(b);

That's the double free - b gets free'd twice - and that is disallowed in C.

For your memory leaking problem:
When you're setting a = b you're losing the original value of a. a was a pointer to the memory that you allocated with int *a = malloc(sizeof(int)); that is now lost. You need to save that address and pass it to free() before exit, if you want valgrind to stop complaining about leaks.
For each address that malloc() returns (except zero... ^_^), you should call free() with that very same address as argument.

A: Let's reduce your code to the bare minimum:
#include <stdlib.h>

int main(void)
{
    int *a = malloc(sizeof(int));
    int *b = malloc(sizeof(int));

    a = b; // after the assignment the pointer value previously held by a is gone.
           // both pointers point to the same memory. The memory previously pointed
           // to by a can no longer be free()d since its address is gone.

    free(a); // free the memory pointed to by b (a is a copy of b) once
    free(b); // free the memory pointed to by b twice --> boom.
}

A: When you do this:
 a = b;

You are effectively making a and b point to the same address (a.k.a. be the same pointer). So this is what causes the error:
free(a); // Frees the location where b points to
free(b);