text:
Q: Как изменить фон QLabel? Как изменить фон QLabel? У меня есть много лейблов, поэтому нужно каждому менять индивидуально.
Нужно поменять фон не всему класу QLabel, а индивидуально 1. Как получить класс определенного лейбла в каскадной таблице?
import PyQt5
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget, QMainWindow, QAction, qApp
from PyQt5.QtGui import QIcon

HEIGHT = 750
WIDTH = 1300
class Menu(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.menubar = parent.menuBar()
        self.file = self.menubar.addMenu('&Опции')

        self.exitAction = QAction(QIcon('cross-exit.ico'), '&Exit', self)
        self.exitAction.setShortcut('Ctrl+Q')
        self.exitAction.setStatusTip('Exit application')
        self.exitAction.triggered.connect(parent.close)

        self.file.addAction(self.exitAction)

    def addMenu(self, actionName, text, command, icon, shortcut=None, statusTip=None) :
        self.actionName = QAction(QIcon(icon), text, self)
        if shortcut:
            self.actionName.setShortcut(shortcut)
        if statusTip:
            self.actionName.setStatusTip(statusTip)
        self.actionName.triggered.connect(command)

        self.file.insertAction(self.exitAction, self.actionName)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.q = QDesktopWidget().availableGeometry()
        self.r_w, self.r_h = self.q.width(), self.q.height()
        self.setGeometry(self.r_w/2-WIDTH/2, self.r_h/2-HEIGHT/2, WIDTH, HEIGHT)
        self.w = self.size().width()
        self.h = self.size().height()
        print(self.w, self.h)
        self.setFixedSize(1300, 750)
        self.setWindowTitle('Lings')
        self.setWindowIcon(QIcon('Lings.ico'))
        self.label = QtWidgets.QLabel("sdsd", self)
        self.labelAnswer = QtWidgets.QLabel("", self)
        self.l_w, self.l_h = 500, 100
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.labelAnswer.resize(self.l_w, self.l_h)
        self.labelAnswer.move(self.w/2-self.l_w/2, 250)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.resize(self.l_w, self.l_h)
        self.label.move(self.w/2-self.l_w/2, 100)
        self.label.setFont(QtGui.QFont('Verdana', 24))
        self.labelAnswer.setFont(QtGui.QFont('Verdana', 24))
        self.label.setStyleSheet(".QLabel{\n"        //Нужно поменять фон не всему класу QLabel, а индивидуально 1. Как получить класс определенного лейбла в каскадной таблице?
        "background-color: #E0FFFF\n"
        "\n"
        "}")
        self.label.setStyleSheet(".QLabel{\n"
        "background-color: #E0FFFF\n"
        "\n"
        "}")
        self.menu = Menu(self)
        self.menu.addMenu('action', 'New', lambda: SecondWindow(self), 'test.ico', shortcut="Ctrl+D", statusTip="Creating")

        self.show()

class SecondWindow(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent, QtCore.Qt.Window)
        self.initUI()

    def initUI(self):

        self.q = QDesktopWidget().availableGeometry()
        self.r_w, self.r_h = self.q.width(), self.q.height()
        self.setGeometry(self.r_w/2-WIDTH/2, self.r_h/2-HEIGHT/2, WIDTH, HEIGHT)
        self.setFixedSize(1300, 800)
        self.setWindowTitle('Lings2')
        self.setWindowIcon(QIcon('Lings.ico'))
        self.mainLayout = QtWidgets.QVBoxLayout()

        self.buttons = []
        for i in range(5):
            but = QtWidgets.QPushButton('button {}'.format(i), self)
            self.mainLayout.addWidget(but)
            self.buttons.append(but)
        self.setLayout(self.mainLayout)

        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = MainWindow()

    sys.exit(app.exec_())```

A: В коде индивидуально вот так:
self.label1.setStyleSheet("background-color: #E0FFFF")
self.label2.setStyleSheet("background-color: #FF0000")
self.label3.setStyleSheet("background-color: #00FFFF")

В qss так:
QLabel#label1 {
    background-color: #E0FFFF;
}

QLabel#label2 {
    background-color: #FF0000;
}

Загрузить внешний qss-файл можно так (допустим, он называется style.qss и
лежит рядом с запускаемым py-файлом):
app = QApplication(sys.argv)
styleFile="style.qss"
with open(styleFile,"r") as sf:
    app.setStyleSheet(sf.read())


text:
Q: Sharepoint online powershell script to get all field properties Is there a way in SharePoint Online to get Field Properties? For example, I have a lookup column and for this I want its Field Type, Required, Get information from:
Allow Multiple Values: Checked or not, Description. I know we can get it like this:
$context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$context.Credentials = $creds
$web = $context.Web
$list=$web.Lists.GetByTitle($listName);
$fieldColl=$list.Fields;
$context.Load($fieldColl);
$context.ExecuteQuery();
foreach($field in $fieldColl)
{
    Write-Host $field.Title
    Write-Host $field.Description
}

But I want the other properties as well.

A: You could get field properties like this:
$columns = Get-PnPField -List "PnPList"
foreach($column in $columns){
    Write-Host "Column Title  :" $column.Title
    Write-Host "Description   :" $column.Description
    Write-Host "Group Name    :" $column.Group
    Write-Host "Internal Name :" $column.InternalName
    Write-Host "Static Name   :" $column.StaticName
    Write-Host "Scope         :" $column.Scope
    Write-Host "Type          :" $column.TypeDisplayName
    Write-Host "Schema XML    :" $column.SchemaXml
    Write-Host "Is Required?  :" $column.Required
    Write-Host "Is read only? :" $column.ReadOnlyField
    Write-Host "Unique?       :" $column.EnforceUniqueValues
    Write-Host "-------------------------------------------"
}

And for detailed definition, you could check the SchemaXml, it will have all property definition.
EDIT : Script source

A: You can do this easily with PnP PowerShell using the Get-PnPField commandlet:
So something like this:
Connect-PnPOnline https://yourtenant.sharepoint.com/sites/yoursite
Get-PnPField -List "Your List Name"
Disconnect-PnPOnline

You can also get this information via REST by visiting:
https://yoursite.sharepiont.com/sites/yoursites/_api/web/lists/getbytitle('Your List Name')/fields

A: Finally I ended up using site provisioning to transfer over my columns and content types over to the Content Type Hub.
Login through PnP PowerShell
Get-PnPProvisioningTemplate -out "youroutputfile.xml" –Handlers "Fields,ContentTypes"

Find the file ouput.  Defauld be
C:\Windows\System32
Connect to the Hub
    Connect-PnPOnline https://yoursite.sharepoint.com/sites/contentTypeHub
Apply the provisioned file
   Apply-PnPProvisioningTemplate C:\Temp\youroutputfile.xml
That's it!

redpajama_set_name: RedPajamaStackExchange


text:
Q: If2 used in PDE solution in simultaneous dynamic mode I am currently working on a model consists of a system of partial differential equations (PDE). The differentials that vary in space have been discretized, while differentials in time have been solved numerically by Orthogonal Collocation on Finite Elements method.
I have a problem. When using condition if2, the initial condition is zero, regardless of what was informed.
It is necessary to initialize the model with IMODE=4 and then with IMODE = 5, both with SOLVER = 3.
This is a simplified example of the model:
import numpy as np

from gekko import GEKKO
m = GEKKO(remote=False)

zf = 0.17
tf = 1

n = 3
nt = 2
m.time = np.linspace(0,tf,nt)

dz = zf/n

#########################

tg_ini = [580.8821, 326.10596036, 318.07166567]
tg = [m.Var(tg_ini[i]) for i in range(n)]

cpv2_ini = [2.0038420499, 1.872134158, 1.8696804845]
cpv2 = [m.Param(cpv2_ini[i]) for i in range(n)]

tp = [m.Var(310.15) for i in range(n)]

#########################

def func_cpv11(t):
    cp11 = ( 31.32234 + ((-20.23531)*(t/1000)) + (57.86644*((t/1000)**2)) + ((-36.50624)*((t/1000)**3)) + ((-0.007374)/((t/1000)**2)) )/31.998
    return cp11

def func_cpv21(t):
    cp21 = ( 28.98641 + (1.853978*(t/1000)) + ((-9.647459)*((t/1000)**2)) + ((16.63537)*((t/1000)**3)) + (0.000117/((t/1000)**2)) )/28.0134
    return cp21

def func_cpv22(t):
    cp22 = ( 19.50583 + (19.88705*(t/1000)) + ((-8.598535)*((t/1000)**2)) + (1.369784*((t/1000)**3)) + (0.527601/((t/1000)**2)) )/28.0134
    return cp22

#########################

cpv1 = [m.Intermediate(func_cpv11(tg[i])) for i in range(n)]

cpv21 = [m.Intermediate(func_cpv21(tg[i])) for i in range(n)]
cpv22 = [m.Intermediate(func_cpv22(tg[i])) for i in range(n)]

for i in range(n):
    cpv2[i] = m.if2(tg[i]-500,cpv21[i],cpv22[i])

cpv = [[cpv1[i], cpv2[i]] for i in range(n)]

y = np.array([0.5, 0.5])

fg_cpv = [m.Intermediate(y @ cpv[i]) for i in range(n)]

#########################

m.Equation(tg[0] == 580.8821)
m.Equation([tg[i] == tg[i-1] + dz*fg_cpv[i-1] for i in range(1,n)])

m.Equation([tp[i].dt() == fg_cpv[i] for i in range(n)])

#########################

m.options.imode = 5
m.options.SOLVER = 3

m.solve()

print('cpv2 = ')
for i in range(n):
    print(cpv2[i].value)

This is the result obtained:
----------------------------------------------------------------
 APMonitor, Version 0.9.2
 APMonitor Optimization Suite
 ----------------------------------------------------------------

 --------- APM Model Size ------------
 Each time step contains
   Objects      :  3
   Constants    :  0
   Variables    :  21
   Intermediates:  12
   Connections  :  6
   Equations    :  27
   Residuals    :  15

 Number of state variables:    27
 Number of total equations: -  21
 Number of slack variables: -  0
 ---------------------------------------
 Degrees of freedom       :    6

 **********************************************
 Dynamic Estimation with Interior Point Solver
 **********************************************

 Info: Exact Hessian

******************************************************************************
This program contains Ipopt, a library for large-scale nonlinear optimization.
 Ipopt is released as open source code under the Eclipse Public License (EPL).
         For more information visit http://projects.coin-or.org/Ipopt
******************************************************************************

This is Ipopt version 3.10.2, running with linear solver mumps.

Number of nonzeros in equality constraint Jacobian...:       52
Number of nonzeros in inequality constraint Jacobian.:        0
Number of nonzeros in Lagrangian Hessian.............:       12

Total number of variables............................:       27
                     variables with only lower bounds:        6
                variables with lower and upper bounds:       12
                     variables with only upper bounds:        0
Total number of equality constraints.................:       21
Total number of inequality constraints...............:        0
        inequality constraints with only lower bounds:        0
   inequality constraints with lower and upper bounds:        0
        inequality constraints with only upper bounds:        0

iter    objective    inf_pr   inf_du lg(mu)  ||d||  lg(rg) alpha_du alpha_pr  ls
   0 6.0000000e+003 2.55e+002 9.90e+001   0.0 0.00e+000    -  0.00e+000 0.00e+000   0
   1 9.2649845e+003 2.55e+002 9.90e+001  11.2 2.64e+011    -  8.34e-012 3.76e-012f  1
   2 3.6289712e+004 2.55e+002 5.95e+004  12.5 3.20e+012    -  9.33e-010 1.41e-012f  1
   3 3.1244934e+006 2.55e+002 3.55e+011  11.8 1.21e+010    -  1.00e+000 4.26e-008f  1
   4 1.2233739e+008 6.90e-002 7.62e+011  11.1 1.99e+004    -  5.67e-001 1.00e+000f  1
   5 1.2233421e+008 2.16e-012 6.44e+009   5.4 5.33e-001    -  9.90e-001 1.00e+000f  1
   6 1.2198510e+008 2.63e-012 6.44e+007   3.4 5.82e+001    -  9.90e-001 1.00e+000f  1
   7 9.4816241e+007 1.14e-012 6.46e+005   1.4 4.53e+003    -  9.90e-001 1.00e+000f  1
   8 3.0450882e+006 1.21e-012 8.97e+003  -0.3 1.53e+004    -  9.86e-001 1.00e+000f  1
   9 1.6038743e+005 3.18e-011 4.47e+002   2.8 5.28e+002    -  9.96e-001 9.03e-001f  1
iter    objective    inf_pr   inf_du lg(mu)  ||d||  lg(rg) alpha_du alpha_pr  ls
  10 3.5917803e+004 2.72e-011 3.42e+002   2.6 3.23e+001    -  1.00e+000 7.43e-001f  1
  11 4.4032685e+003 3.28e-011 2.67e-001   1.5 1.15e+000    -  9.99e-001 1.00e+000f  1
  12 4.9020198e+001 7.06e-013 7.78e-003  -0.5 1.87e-001    -  9.94e-001 9.95e-001f  1
  13 4.8932248e-001 1.14e-013 8.96e-005  -6.3 1.94e-003    -  9.90e-001 9.90e-001f  1
  14 -1.7447063e-003 3.93e-014 9.21e-002  -8.3 1.94e-005    -  9.99e-001 9.96e-001f  1
  15 -2.2492197e-003 1.14e-013 3.63e+003  -5.9 7.80e-008    -  1.00e+000 5.42e-001f  1
  16 -2.4686751e-003 1.14e-013 2.28e+002  -6.7 4.09e-008    -  1.00e+000 9.58e-001f  1
  17 -2.4879150e-003 1.14e-013 2.92e-001  -8.3 2.71e-009    -  1.00e+000 9.99e-001f  1
  18 -2.4882162e-003 1.14e-013 9.09e-013 -10.1 2.70e-011    -  1.00e+000 1.00e+000h  1

Number of Iterations....: 18

                                   (scaled)                 (unscaled)
Objective...............: -2.4882162366554839e-004  -2.4882162366554835e-003
Dual infeasibility......:  9.0949470177292824e-013   9.0949470177292824e-012
Constraint violation....:  3.4861931869050499e-014   1.1368683772161603e-013
Complementarity.........:  7.5538837469831659e-011   7.5538837469831659e-010
Overall NLP error.......:  9.1075642737176940e-012   7.5538837469831659e-010

Number of objective function evaluations             = 19
Number of objective gradient evaluations             = 19
Number of equality constraint evaluations            = 19
Number of inequality constraint evaluations          = 0
Number of equality constraint Jacobian evaluations   = 19
Number of inequality constraint Jacobian evaluations = 0
Number of Lagrangian Hessian evaluations             = 18
Total CPU secs in IPOPT (w/o function evaluations)   =      0.053
Total CPU secs in NLP function evaluations           =      0.020

EXIT: Optimal Solution Found.

 The solution was found.

 The final value of the objective function is  -0.0024882162366554835

 ---------------------------------------------------
 Solver         :  IPOPT (v3.12)
 Solution time  :  0.10469999999999999 sec
 Objective      :  0.
 Successful solution
 ---------------------------------------------------

cpv2 =
[0.0, 1.0705093271]
[0.0, 1.0705216696]
[0.0, 1.0705340141]

It is a simple model and I cannot understand the cause of the problem.

A: This is a common issue when initializing a model. The first point in the horizon is not calculated because there is typically a fixed initial condition. There equations at the first node but Gekko deactivates them, assuming that the initial conditions are fixed. The initial condition can be calculated with m.free_initial(x) for the variable x. Another way to get a non-default value (such as 0) in the initial condition position is to solve again with m.options.TIME_SHIFT=1 (default). One recommendation is to put two solve statements together to get the correct initial condition after the time shift from the second point as it becomes the new initial condition.
m.solve(); m.solve()

print('cpv2 = ')
for i in range(n):
    print(cpv2[i].value)

cpv2 =
[1.07050933, 1.0705093271]
[1.07052167, 1.0705216696]
[1.07053401, 1.0705340141]

Does this resolve the concern?


text:
Q: Oracle named constraint in create table to set date to default date I want to add a named constraint in my CREATE TABLE statement that will cause of my columns to default to the system date.  I know how to define a primary key constraint:
constraint cust_ID_PK PRIMARY KEY (Cust_ID)

How do I define a constraint on Hire_Date that defaults it to the system date?

A: You can set a default for a column.  But that is not a constraint so you cannot name it.
CREATE TABLE customer (
  cust_id   NUMBER,
  hire_date DATE DEFAULT sysdate,
  CONSTRAINT cust_id_pk PRIMARY KEY( cust_id )
)

A default is not a type of constraint so you can't use the syntax for defining a constraint to define a default. A default is not an object type in the database so it cannot have a name. A default is a property of a column-- it can only be declared inline with the column.


text:
Q: RichTextBox Hyperlink I have a WPF richtextbox that contains text and hyperlinks. I want to change the font size for the selected hyperlink when i press a button. The problem that i have is that i am not able to get the selected hyperlink from the richtextbox selection.
Best Regards
Marian
PS. I've uploaded a demo here: http://cid-6d5e36974c8e12a8.office.live.com/self.aspx/RTB%20Hyperlink/RTBDemo.zip
PS2. Adding hyperlink to rtb at caret position:
Run hyper = new Run("SampleLink");
Hyperlink hp = new Hyperlink(hyper);
hp.Click += new RoutedEventHandler(hp_Click);
TextBlock tb = new TextBlock();
tb.FontSize = 10;
tb.Inlines.Add(hp);
using (rtb.DeclareChangeBlock())
{
    TextPointer tp = rtb.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);
    InlineUIContainer inlineUIContainer = new InlineUIContainer(tb, tp);
    rtb.CaretPosition = inlineUIContainer.ElementEnd;
}
rtb.IsDocumentEnabled = true;

PS3. Setting font:
TextRange text = new TextRange(rtb.Selection.Start, rtb.Selection.End);
text.ApplyPropertyValue(TextElement.FontSizeProperty, 14.00);

Solved: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/23fcf1b7-8708-40ca-b3b0-658a96a795eb/#b2f32824-fab6-45cc-8c81-7c26986b12bf

A: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/23fcf1b7-8708-40ca-b3b0-658a96a795eb/#b2f32824-fab6-45cc-8c81-7c26986b12bf


text:
Q: Vue Js - Displaying elements using v-for loop in single line (for pagination) I am using v-for loop to show pagination links -

   <router-link :to="'/top/pages/' + n" @click.native="getPaginatedUser">{{ n }}</router-link>

Each link is getting displayed in new line, like below -
1
2
Is there any way i can display them in single line ? like this -
1
2
Thanks.

A: The reason for each link is displayed in new line is because you are iterating a div element which is a block element. You can use an inline element like span or Vue specific template which won't render any additional markup or you can just iterate the router link
<router-link
  :to="'/top/pages/' + n"
  @click.native="getPaginatedUser"
  :key="n"
  v-for="n in this.totalPages"
>{{ n }}</router-link>

Using template instead of div.
<template v-for="n in this.totalPages">
    <router-link :to="'/top/pages/' + n" @click.native="getPaginatedUser" :key="n">{{ n }}</router-link>
</template>

A: You can change either the component div to span, or change the style of the div to:
display: inline-block;

A: just move the v-for to the router-link component:

   <router-link v-for="n in this.totalPages" :key="n" :to="'/top/pages/' + n" @click.native="getPaginatedUser">{{ n }}</router-link>

The router-link component will render an  tag by default, which you can then style via css to get the layout you want.
Example:

new Vue({
  el: '#root',
  router: new VueRouter()
});
a + a { margin-left: 0.3rem; }

  <router-link v-for="id in 10" :key="id" :to="'/foo/' + id">{{id}}</router-link>

A: Add a class to template/div and style it with:
display: flex;

and v-for the router link instead of the div.
It should put your pagination inline!


text:
Q: Logic problem that i am struggling with $1$-   The universal set for this problem is the set of students attending Miskatonic University. Let
-$M$ denote the set of Math majors.
-$CS$ denote the set of Computer Science majors.
-$T$ denotes the set of students who had a test on Friday.
-$P$ denotes those students who ate pizza last Thursday.
Using only the set theoretical notation we have following assertions
$1$. Computer Science majors had a test on Friday $$CS \subseteq T$$
$2$. No Math majors ate pizza last Thursday-----> $$M^c \subseteq P$$ or $$M \cap P=\varnothing$$ (The book said that the answer is $M \cap P=\varnothing$, idk why?)
$3$. Some Math majors did not eat pizza last Thursday$$C^c \cap P=\varnothing?$$ I am struggling with translating context to symbols.
$4$. Those Computer Science majors who did not have a test on Friday ate pizza on Thursday
$$CS^c \in T \subseteq P?$$
$5$. Math or Computer Science major who ate pizza on Thursday did not have a test on Friday
$$M \cup CS \subseteq P \land T = \varnothing?$$
I need help please. I am trying my best to learn the logic and operations on sets.
I understand that $A \cup B$ reads "$x \in A$ or $x \in B$"; $A \cap B$" means $x \in A$ and $x \in B$" but when it comes to question like this, I have no clue how to write. For instance, $(2)$, how is $M \cap P = \varnothing$? Why can't it be $M^C  \subseteq P$? How does "and" or" "E" used to write symbols?

A: $(1)$ is correct.
$(2)$ is $M\cap P=\varnothing $ Since $M\cap P$ are the Math Majors who ate Pizza last Thursday.
$(3)$ is $M\cap P^c\ne\varnothing $ Since $M\cap P^c$ are the Math Majors who did not eat Pizza last Thursday.
$(4)$ is $(CS\cap T^c)\subseteq P $ Since $CS\cap T^c$ are the Computer Science Majors who did not have test on Friday.
$(5)$ is $((M\cup CS)\cap P)\subseteq T^c $ Since$((M\cup CS)\cap P)$ are Math or Computer Science Majors who ate Pizza last Thursday.


text:
Q: If $ \sin \alpha = \frac 45 $ and $ \cos \beta = \frac{5}{13} $, prove that $ \cos \frac{\alpha-\beta}{2} = \frac{8}{\sqrt {65}} $ I can solve it easily if I assume that $ 0 < \alpha, \beta < \frac{\pi}{2}$
But there is no mention of the quadrants in which $ \alpha $ and $ \beta $ lie in.
Is the question wrong ?

A: HINT:
\begin{align}
\cos(\alpha/2-\beta/2)&=\sqrt{\frac{1+\cos(\alpha-\beta)}{2}}=\sqrt{(1+\cos\alpha\cos\beta+\sin\alpha\sin\beta)/2}\\
\end{align}
$$ \cos\alpha =\frac35, \cos\beta = \frac{5}{13},\, \sin\alpha=\frac45,\, \sin\beta =\frac{12}{13}, $$
plug in to get $ 8/\sqrt{65}$
For other quadrants calculate other three values also which are possible with inverse trig functions.
$$\sqrt{(1\pm\cos\alpha\cos\beta\pm\sin\alpha\sin\beta)/2}$$

A: Hint:
$\sin \alpha>0$ then $0<\alpha<\pi$ and $\cos \beta>0$ then $-\frac{\pi}2<\beta<\frac{\pi}2$ and $-\frac{\pi}2<-\beta<\frac{\pi}2$
Thus $$-\frac{\pi}2<\alpha-\beta<\frac{3\pi}2$$
and
$$-\frac{\pi}4<\frac{\alpha-\beta}2<\frac{3\pi}4$$
1) $\sin^2\alpha+\cos^2\alpha=1$, then $\cos\alpha=\pm\sqrt{1-\sin^2\alpha}$  and $\sin \beta=\pm\sqrt{1-\cos^2\beta}$
2) $\cos (\alpha-\beta)=\cos\alpha\cos\beta+\sin\alpha\sin\beta$
3)$|\cos \frac{\alpha-\beta}2|=\sqrt{\frac{1+\cos(\alpha-\beta)}2}$


text:
Q: How to access files loaded to sourceforge.net using via SFTP using HTTP I loaded files to one of my projects web following their documentation. Now I need to get the URL for those files so I can access them from my application. Sadly, I'm unable to find the URL format for this. Any idea?

A: Say you uploaded your index.html to /home/project-web/foo_project/htdocs/index.html on web.sourceforge.net
You can than access it using http://foo_project.sourceforge.net/index.html
For details, see https://sourceforge.net/p/forge/documentation/Project%20Web%20Services/
Note that the path SFTP documentation mentions, like /home/groups/f/fo/foo_project/ is actually a link to /home/project-web/foo_project/.


text:
Q: Logic Connective involving implication and biconditions(FOL/Tarski' World) I'm trying to solve the following two problems where I'm asked to translate these English sentences into First Order Language (FOL) by using Tarski's World symbols. I'll appreciate it very much if anyone can help me confirm my solutions to the problems.
Question:
1) If $e$ is a tetrahedron, then it's to the right of $b$ if and only if it is also in front of $b$.
2) $e$ is in front of $d$ unless $e$ is a large tetrahedron.
my solution:
1) Tet(e) ⇒ (RightOf(e,b) ⇔ FrontOf(e,b))
I'm not very certain for this problem. Can it be that:
(Tet(e) ⇒ RightOf(e,b)) ⇔ (Tet(e) ⇒ LeftOf(e,b)) the correct solution? Because if the iff symbol is in between RightOf(e,b) and FrontOf(e,b), then it only shows the iff relation between these two and not related Tet(e) at all.
2) ¬(Large(e) ∧ Tet(e)) ⇒ FrontOf(e,d):
For this problem, the "Q unless P" translates to "If ¬P then Q", at first I thought of using ¬(Large(e) ∨ Tet(e)), but on the second thought that if we have "Small Tetrahedron" it will still satisfy the "If ¬P" aka if it's the case that P is large Tetrahedron. So I used conjunction instead.
Thanks

A: Your first solution for 1) is correct.  The second one (Tet(e) ⇒ RightOf(e,b)) ⇔ (Tet(e) ⇒ LeftOf(e,b)) turns out to be equivalent, but it is not a direct translation of the original English sentence. In the original sentence, you have the biconditional as part of the consequent.
Your solution (and reasoning) for 2) is correct


text:
Q: Lifting state up - this.state.friends suddenly undefined I'm trying to understand why I get this error whenever a "add to inner circle button" gets clicked (in Frienddetail.js). I am using props to lift state up from Frienddetail to Friends:
addToInnerCircle [as innerCircle]
C:/Users/charl/Desktop/IRONHACK/Week-9/finalproject/client/src/pages/Friends.js:64
  61 |    }
  62 |
  63 |    addToInnerCircle(idclicked){
> 64 |        console.log("hallo")
     | ^  65 |        let idpicked = this.state.friends
  66 |        // .filter(friend => friend._id === idclicked)
  67 |        console.log("Charles")

let idpicked = this.state.friends => gives undefined but I don't understand why?
It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.

App.js
import React from 'react'
import DefaultLayout from "../layout/Default"
import './Friends.css'
import Axios from 'axios'
import Frienddetail from '../components/Frienddetail'
import InnerCircleDetail from '../components/InnerCircleDetail'
import { getUser } from '../utils/auth'

class Friendsfollowers extends React.Component {
    constructor() {
        super()

        this.state = {
            friends: [],
            searchFriends: [],
            innerCircle: [],
            searchInnerCircle: []
        }

        this.searchFriends=this.searchFriends.bind(this)
    }

    componentDidMount(){
        Axios({
            method: "GET",
            url: `${process.env.REACT_APP_API_BASE}/friends`,
            withCredentials: true
        })
        .then(response =>{
            console.log(response)
            let friendslist = response.data // eslint-disable-next-line
            let friendslistupdate = friendslist.filter(friend => {
                if(friend.username){
                    if(friend.username !== getUser().username){
                        return true
                    }
                }
            })
            this.setState({
                friends: friendslistupdate,
                searchFriends: friendslistupdate
            })
        })
        .catch(error =>{
            console.log("Charles made an error when retrieving all friends: ",error)
        })
    }

    searchFriends(e){
        console.log(getUser)
        let friendsearched = this.state.friends.filter(friend => {
            if(friend.username){
                if(friend.username.toLowerCase().includes(e.target.value.toLowerCase())){
                    return true
                }
            }
        })
        this.setState({
            searchFriends:friendsearched
        })
    }

    addToInnerCircle(idclicked){
        console.log("hallo")
        let idpicked = this.state.friends
        // .filter(friend => friend._id === idclicked)
        console.log("Charles")
        console.log(idpicked)
        console.log("Charles")
    }

    render() {
        return (
            <DefaultLayout>

Our community

                <form className="friends">

                        Search for Users :

                        <input className="friendform" type="text" name="friend" value={this.state.friend} placeholder="Type a username here!" onChange={this.searchFriends}></input>

                </form>

                    {
                        this.state.searchFriends.map(friend =>

                                <Frienddetail
                                    key={friend._id}
                                    id={friend._id}
                                    username={friend.username}
                                    location={friend.location}
                                    innerCircle={this.addToInnerCircle}
                                />

                        )
                    }

Your inner circle

                    {
                        this.state.searchInnerCircle.map(inner =>

                                <InnerCircleDetail
                                    key={inner._id}
                                    id={inner._id}
                                    username={inner.username}
                                    location={inner.location}
                                />

                        )
                    }

            </DefaultLayout>
        )
    }
}

export default Friendsfollowers

Frienddetail.js
import React from 'react'
import './Frienddetail.css'

class Frienddetail extends React.Component {
    constructor() {
        super()

        this.state = {

        }
    }

    render() {
        return (

{this.props.username}

{this.props.location}

                    <button className="followbutton">Follow user!</button>
                    <button className="friendbutton" onClick={(e)=> this.props.innerCircle(this.props.id)}>Add to inner circle!</button>

        )
    }
}

export default Frienddetail

A: To be able to use this inside a callback function you need to bind it or react interprets "this" as a window object and not an instance of a class and window object has no state variable so this.state is undefined. what you have done for your searchFriends function you need to do the same for addToInnerCircle or a better way that I like to use which has no problem of binding is to use arrow function syntax just convert your addToInnerCircle into an arrow function.
Read more on react js docs handling events

A: Try using it like this
import React from "react";

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      id: props.id
    };
  }

  handleClick = () => {
    this.props.innerCircle(this.state.id);
  };

  render() {
    return <button onClick={this.handleClick}>Click</button>;
  }
}

export default Test;

In your Frienddetail component.
Lemmi know if this works


text:
Q: Combine crude events and Hazard Ratio in Meta-analysis I'm running a meta-analysis on several studies; most of them have crude event numbers that I can put in my software, but other ones have hazard ratios with 95% C.I. reported and no crude number reported.
Question 1 is: is there a way to pool in a meta-analysis study that reports only crude events with study that reports only hazard ratios? If so, what software can I use to do that?
Question 2 if the answer for Q1 is "no": is there a way to get from a hazard ratio the crude events number, knowing the number of patients?
Thanks a lot in advance for any reply.

A: Firstly, yes, this can be done. And it is probably best to try to get everything to the hazard ratio scale, because one would guess there's a good reason why time-to-event analyses were done in the first place (e.g. not all patients complete trial, event driven trials where not all patients were followed for the same duration etc.).
If you have a log-hazard ratio with standard error (easy to backcalculate from confidence intervals or p-values, if not given, or approximately from the total number of patients with an event), then everything is great and a standard approach would be to do an inverse variance (or corresponding random effects) meta-analysis of the estimate (log-hazard ratio) and its standard error.
Problems arise, if you do not have that information for all trials. It is the easiest to deal with, if you have a relatively constant hazard rate for events over time, in which case you can approximately assume an exponential time-to-event model. You can get an idea off whether that is appropriate, if some of the trials give you e.g. a Kaplan-Meier plot. Alternatively, you can think about whether it is plausible: e.g. if all patients are relatively stable hypertensive patients with a blood pressure of 160 to 170 before we start following them, then there is probably no reason why their hazard rate for death should differ too much or change much over time. In contrast, if we say start following patients the day after which they just survived a myocardial infarction, then there is probably much more of a risk that they died shortly thereafter (say within 30 days) and then the risk goes down over time.
If you have the number of patients with an event $y_{ij}$ in each treatment group $j=0,1$ of trial $i$ and the follow-up to first event or censoring $t_{ij}$ (i.e. summed up over all the patients), then you have a likelihood for that trial of
$$ (\exp(\text{log-HR}) \lambda_i)^{y_{ij}} \exp(e^{\text{log-HR} \times j} \lambda_i t_{ij}), $$
where $\text{log-HR}$ is the log-hazard ratio and $\lambda_i$ is a nuisance parameter for the control group hazard rate. In contrast, for the trials, for which you have the log-hazard ratio and its standard error, the likelihood is a normal pdf $\phi(\text{log-HR}), \text{SE}^2)$.
If you do not have this information, then this paper on the meta-analysis of aggregate data on medical event occurrence may be relevant and discusses a number of relevant options.
Getting from a hazard ratio and no further information back to the number of patients with an event is more or less impossible.
Finally, you always have the option of contacting the authors for extra information, checking clinical trial registries (and results databases), health authority briefing books, approved drug labels and so on.


text:
Q: Is initramfs expandable when embedded in kernel? If I embed initramfs in the kernel image, (I can do this by setting the config variable for the iniramfs file source location, and initramfs becomes located in  data section I guess), and after I boot and get into shell, (by the way I made the initramfs.cpio.gz using busybox) can I make a file in the file system ? I mean does initramfs get expanded as some files are populated there?

A: initramfs is a compressed CPIO archive, it gets transparently mounted and it's basically read-only for all intents and purposes. You cannot edit/expand it, only recreate it.


text:
Q: Initializing utf8 encoded string c++11 I have a problem initializing utf-8 encoded string. I am using Visual Studio 2013.
#include <string>
#include <iostream>

using namespace std::string_literals; // enables s-suffix for std::string         literals

int main()
{

string S1 = u8"hello"; // std::string

}

Error   1   error C2039: 'string_literals' : is not a member of 'std'                   c:\users\veroonika\documents\visual studio 2013\projects\string literals test u8 string\string literals test u8 string\source.cpp   5   1   string literals test u8 string
Error   2   error C2871: 'string_literals' : a namespace with this name does not exist  c:\users\veroonika\documents\visual studio 2013\projects\string literals test u8 string\string literals test u8 string\source.cpp   5   1   string literals test u8 string

Why does compiler not recognize the namespace?

A: Are you sure you can use std::string_literals with Visual Studio 2013? According to this feature list it isn't available.


text:
Q: Integral $f(t)=\int_0^{\pi/2}\sin(t\tan x)dx$
Evaluate the integral
  $$f(t)=\int_0^{\pi/2}\sin(t\tan x)dx.$$

I came across this integral after having shown that its counterpart can be evaluated exactly:
$$\int_0^{\pi/2}\cos(t\tan x)dt=\frac{\pi}{2}e^{-|t|}.$$
I figured that $f$ would be as easy but it is actually presenting me with some difficulties. I start off by using the substitution $\tan x\mapsto x$:
$$f(t)=\int_0^\infty \frac{\sin tx}{1+x^2}dx,$$
then, taking the Laplace transform:
$$\begin{align}
\mathcal{L}\{f\}(s)&=\int_0^\infty \frac1{1+x^2}\int_0^\infty e^{-st}\sin(xt)dtdx\\
&=\int_0^\infty \frac1{1+x^2}\text{Im}\left[\int_0^\infty e^{-(s-ix)t}dt\right]dx\\
&=\int_0^\infty \frac1{1+x^2}\frac{x}{s^2+x^2}dx\\
&=\frac12\int_0^\infty \frac{dx}{(1+x)(s^2+x)}\\
&=\frac1{2s^2-2}\int_0^\infty \left[\frac{1}{1+x}-\frac{1}{s^2+x}\right]dx\\
&=\frac{\ln s}{s^2-1}.
\end{align}$$
Now, I see that $f(t)=\mathcal{L}^{-1}\left\{\frac{\ln s}{s^2-1}\right\}(t),$ but I do not know how to compute that inverse Laplace transform. Could I have some help?

A: Mathematica gives:
$$\frac{1}{4} \sqrt{\pi } t G_{1,3}^{2,1}\left(\frac{t^2}{4}|
\begin{array}{c}
 0 \\
 0,0,-\frac{1}{2} \\
\end{array}
\right)$$
involving the Meier G function.

A: After Kemono Chen's comment.
Starting with
$$f(t)=\int_0^\infty \frac{\sin (tx)}{1+x^2}\,dx=\int_0^\infty \frac{\sin (tx)}{(x+i)(x-i)}\,dx$$
$$f(t)=\frac i 2 \left(\int_0^\infty \frac{\sin (tx)}{x+i}\,dx -\int_0^\infty \frac{\sin (tx)}{x-i}\,dx\right)$$
Consider now
$$I(a)=\int  \frac{\sin (tx)}{x+a}\,dx=\int\frac{\sin (t (y-a))}{y}\,dy$$
$$I(a)=\cos(at) \int \frac{\sin (ty)}{y}\,dy-\sin(at)\int \frac{\cos (ty)}{y}\,dy$$ Now, make $z=ty$
$$I(a)=\cos(at) \int \frac{\sin (z)}{z}\,dz-\sin(at)\int \frac{\cos (z)}{z}\,dz=\cos (a t)\,\text{Si}(z) -\sin (a t)\,\text{Ci}(z) $$
Back to $x$
$$I(a)=\cos (a t)\, \text{Si}(t(x+a))-\sin (a t)\, \text{Ci}(t(x+a))$$ Assuming $t >0$
$$J(a)=\int_0^\infty  \frac{\sin (tx)}{x+a}\,dx=\text{Ci}(a t) \sin (a t)+\frac{1}{2} (\pi -2 \text{Si}(a t)) \cos (a t)$$
$$J(a)-J(-a)=(\text{Ci}(-a t)+\text{Ci}(a t)) \sin (a t)-2 \text{Si}(a t) \cos (a t)$$
$$f(t)=\frac i 2 \left(J(i)-J(-i)\right)=\text{Shi}(t) \cosh (t)-\text{Chi}(t) \sinh (t)$$ which is Kemono Chen's result.


text:
Q: The instance of entity type cannot be tracked hello community I have a problem when I try to edit a model it tells me that I am trying to duplicate the primary key and I don't know why this happens.

Error System.InvalidOperationException: The instance of entity type
'Cotizacion' cannot be tracked because another instance with the same
key value for {'CotizacionId'} is already being tracked. When
attaching existing entities, ensure that only one entity instance with
a given key value is attached.

this is my controller code:
   [HttpPut]
        public async Task<ActionResult> Put(Cotizacion cotizacion)
        {
            var cotizacionoriginal = context.Cotizaciones.Where(x => x.CotizacionId == cotizacion.CotizacionId).FirstOrDefault();
            cotizacionoriginal = cotizacion;
            context.Update(cotizacion);
            context.SaveChanges();
            return NoContent();
        }

this is my model cotizacion:
 public class Cotizacion
    {
        [Key]
        public Guid CotizacionId { get; set; }
        public Guid InquilinoId { get; set; }
        public int Folio { get; set; }
        public DateTime? FechaCotizacion { get; set; }
        public DateTime? FechaVencimiento { get; set; }
        public DateTime? FechaCreacion { get; set; }
        public DateTime? FechaModificacion { get; set; }
        public bool EsBorrador { get; set; }
        public double Total { get; set; }
        public string Comentario { get; set; }
        public bool Aceptada { get; set; }

        public Guid CarritoId { get; set; }
        public Guid ClienteId { get; set; }
        public Guid? DireccionId { get; set; }
        public Guid? ContactoId { get; set; }

        public virtual Carrito Carrito { get; set; }
        public virtual Cliente Cliente { get; set; }
        public virtual Direccion Direccion { get; set; }
        public virtual Contacto Contacto { get; set; }
    }

this is my model cliente:
public class Cliente
    {
        public Guid ClienteId { get; set; }
        public Guid InquilinoId { get; set; }

        [Required(ErrorMessage = "El campo {0} es requerido")]
        public string Nombre { get; set; }

        [Required(ErrorMessage = "El campo Razón Social es requerido")]
        public string Razon_social { get; set; }

        [Required(ErrorMessage = "El campo {0} es requerido")]
        public string Rfc { get; set; }

        [Required(ErrorMessage = "El campo {0} es requerido")]
        public string Email { get; set; }
        public int Telefono { get; set; }
        public int Celular { get; set; }
        public bool Es_Cliente { get; set; }
        public bool Es_Proveedor { get; set; }

        public virtual List<Contacto> Contacto { get; set; } = new List<Contacto>();
        public virtual List<Direccion> Direccion { get; set; } = new List<Direccion>();
        public virtual List<ClienteTipodeConcepto> ClienteTipodeConcepto { get; set; } = new List<ClienteTipodeConcepto>();
        public virtual List<ClienteConcepto> ClienteConcepto { get; set; } = new List<ClienteConcepto>();
        public virtual Cliente Empresa { get; set; }
    }

this is my model carrito:
public class ArticuloCarrito
    {

        [Key]
        public Guid ArticuloCarritoId { get; set; }
        public Guid ProductoId { get; set; }
        public int Cantidad { get; set; }

        public decimal PrecioPublico { get; set; }
        public decimal Total// { get; set; }
        {
            get
            {
                return PrecioPublico * Cantidad;
            }
        }
        public virtual Carrito Carrito { get; set; }
        public virtual Producto Producto { get; set; }
    }

    public class Carrito
    {
        [Key]
        public Guid CarritoId { get; set; }

        public virtual ICollection<ArticuloCarrito> Articulos { get; set; }
        public decimal Subtotal
        {
            get
            {
                decimal total = 0;
                if (Articulos is null)
                {
                    total = 0;
                }
                else
                {
                    foreach (var item in Articulos)
                    {
                        total += item.Total;
                    }
                }

                return total;
            }
        }
        public decimal IVA
        {
            get
            {
                double sub = Convert.ToDouble(Subtotal);

                return (Convert.ToDecimal(sub * .16));
            }
        }
        public decimal Total
        {
            get
            {
                double sub = Convert.ToDouble(Subtotal);

                return (Convert.ToDecimal(sub * 1.16));
            }
        }
        public DateTime UltimoAcceso { get; set; }
        public int TiempoDeVidaEnSegundos { get; set; } = 1800;
    }

also try an endpoint like this:
 [HttpPut]
        public async Task<ActionResult> Put(Cotizacion cotizacion)
        {
            var cotizacionDB = await context.Cotizaciones.FirstOrDefaultAsync(x => x.CotizacionId == cotizacion.CotizacionId);
            if (cotizacionDB == null) { return NotFound(); }

            cotizacionDB = mapper.Map(cotizacion, cotizacionDB);

            await context.Database.ExecuteSqlInterpolatedAsync($"delete from Cotizaciones WHERE CotizacionId = {cotizacion.CotizacionId};");

            cotizacionDB.Cliente = cotizacion.Cliente;
            cotizacionDB.Carrito = cotizacion.Carrito;

            await context.SaveChangesAsync();
            return NoContent();
        }

but it didn't work
my new try:
 [HttpPut]
        public async Task<ActionResult> Put(Cotizacion cotizacion)
        {
            var cotizacionoriginal = context.Cotizaciones.Where(x => x.CotizacionId == cotizacion.CotizacionId).FirstOrDefault();
            cotizacionoriginal.Carrito= cotizacion.Carrito;
            if (cotizacionoriginal != null)
            {

                context.Entry(cotizacionoriginal).State = EntityState.Detached;
            }

            context.Entry(cotizacion).State = EntityState.Modified;

           await context.SaveChangesAsync();
           return NoContent();
        }

A: The reason that you are running into this issue is due to the code in your controller.  On this line you are tracking a Cotizacion entity
var cotizacionoriginal = context.Cotizaciones.Where(x => x.CotizacionId == cotizacion.CotizacionId).FirstOrDefault();

And on this line you are attempting to track another Cotizacion entity with the same key value.
context.Update(cotizacion);

Essentially you have three ways that you can handle this.
Option #1 Detach local entry and attach updated entry:
var cotizacionoriginal = context.Cotizaciones.Where(x => x.CotizacionId == cotizacion.CotizacionId).FirstOrDefault();

// check if local is not null
if (cotizacionoriginal != null)
{
    // detach
    _context.Entry(cotizacionoriginal).State = EntityState.Detached;
}
// set Modified flag in your entry
_context.Entry(cotizacion).State = EntityState.Modified;

// save
_context.SaveChanges();

Option #2 Update the individual properties you want to change
   [HttpPut]
        public async Task<ActionResult> Put(Cotizacion cotizacion)
        {
            var cotizacionoriginal = context.Cotizaciones.Where(x => x.CotizacionId == cotizacion.CotizacionId).FirstOrDefault();
            cotizacionoriginal.Folio = cotizacion.Folio;
            cotizacionoriginal.Total = cotizacion.Total; //Continue as required
            context.Update(cotizacionoriginal );
            context.SaveChanges();
            return NoContent();
        }

Option #3 Simply update that value if it's guaranteed that it will always exist and will never cause any issues (not recommended)
   [HttpPut]
        public async Task<ActionResult> Put(Cotizacion cotizacion)
        {
            context.Update(cotizacion);
            context.SaveChanges();
            return NoContent();
        }

If you are attempt to update items within the Cotizacion type as well (for example Nombre inside the Cliente) then this won't work.  You can update the reference to the Cliente inside the Cotizacion, but in order to update the subitems you will need to perform those separately.


text:
Q: Django ElasticSearch DSL partial matching using nGram analyzer I'm quite new to the ElasticSearch topic and I'm trying to implement simple e-commerce search in my Django application using ElasticSearch with library django-elasticsearch-dsl Github repo .
The thing I'm trying (extremely simplified) to achieve is that, considering these Django model instances:
Red T-shirts
Blue T-Shirts
Nice T-Shirts

for search term T-Sh I'll obtain all these three results:
Red T-shirts
Blue T-Shirts
Nice T-Shirts

So I have this model in shop/models.py (again very simplified)
class Category(models.Model):
   title = models.CharField(max_length=150, blank=False)
   description = models.CharField(max_length=150, blank=False)
   # In reality here I have more fields
   def __str__(self):
      return self.title

With shop/documents.py
from elasticsearch_dsl import analyzer, tokenizer

autocomplete_analyzer = analyzer('autocomplete_analyzer',
            tokenizer=tokenizer('trigram', 'nGram', min_gram=1, max_gram=20),
            filter=['lowercase']
        )from elasticsearch_dsl import analyzer, tokenizer

@registry.register_document
class CategoryDocument(Document):

    title: fields.TextField(analyzer=autocomplete_analyzer, search_analyzer='standard') # Here I'm trying to use the analyzer specified above

    class Index:
        name = 'categories'
        settings = {
            'number_of_shards': 1,
            'number_of_replicas': 0,
            'max_ngram_diff': 20 # This seems to be important due to the constraint for max_ngram_diff beeing 1
        }

    class Django:
        model = Category
        fields = [
            'title',
            # In reality here I have more fields
        ]

And finally, my shop/views.py
class CategoryElasticSearch(ListView):
    def get(self, request, lang):
        search_term = request.GET.get('search_term', '')
        q = Q(
            "multi_match",
            query=search_term,
            fields=[
                'title',
                # In reality here I have more fields
                ],
            fuzziness='auto',)
        search = search.query(q)
        # ... etc

But result for T-Sh is empty. I get something only when writing something longer such as T-Shir. Now I'd probably obtain all three results.
Thank you very much

A: Omg I made it working.
For anyone dealing with this - analyzers are defined on each "field" in the mapping. In other words, in order to attach analyzer to the title field our shop/documents.py has to look like this:
from elasticsearch_dsl import analyzer, tokenizer

autocomplete_analyzer = analyzer('autocomplete_analyzer',
            tokenizer=tokenizer('trigram', 'nGram', min_gram=1, max_gram=20),
            filter=['lowercase']
        )from elasticsearch_dsl import analyzer, tokenizer

@registry.register_document
class CategoryDocument(Document):

    #title: fields.TextField(analyzer=autocomplete_analyzer, search_analyzer='standard') # Here I'm trying to use the analyzer specified above <-- This was extremely incorrect, due to the colon in definition, I don't know how I missed it but I did...
     title = fields.TextField(required=True, analyzer=autocomplete_analyzer) # This is it....

    class Index:
        name = 'categories'
        settings = {
            'number_of_shards': 1,
            'number_of_replicas': 0,
            'max_ngram_diff': 20 # This seems to be important due to the constraint for max_ngram_diff beeing 1
        }

    class Django:
        model = Category
        fields = [
            # 'title' <-- Notice, I removed this field, it would be redeclaration error
            # In reality here I have more fields
        ]

And it works flawlessly...


text:
Q: Implement Display, Edit and New forms in spfx web part using reactjs I have 3 buttons on spfx web part 'Display','Edit' and 'New'.
When I click on these buttons, respective form should open with text boxes and data from sharepoint (online) list.
  I want to use Reactjs with VS Code.
How can I implement this requirement?

A: You simply add the link to the list forms in the buttons. For example the new form
<PrimaryButton href="/serverelativeURL/Lists/LISTNAME/NewForm.aspx" >New</PrimaryButton>

It should open the form. If you want to redirect after that, add the ?Source parameter:
/serverelativeURL/Lists/LISTNAME/NewForm.aspx?Source=/serverrelativeURL/yourspfxwebpartpage


text:
Q: Weak and $*$-weak convergence of functionals in $C[0,1]$ For a sequence of functionals $F_n \in C[0,1]^*$,
where
$$
F_n(f) = \int_0^1 f(x^n)dx
$$
I want to know if this sequence converges weakly.
My attempt.
I can show that there is a weak-star convergence for this sequence. This sequence weakly-star converges to $F\in C[0,1]^*$, where
$$
F(f) = f(0), \ f\in C[0,1]
$$
But I can not prove or disprove weak convergence. Using the fact that $C[0,1]^*\cong BV_0[0,1]$, where $BV_0[0,1]$ is a space of bounded variation functions $g$ such that $g(0) = 0$ and  $g(x-0) = g(x)$. There is a correspondence between functionals  $F_n\in C[0,1]^*$ and functions $g_n = x^{\frac{1}{n}} \in BV_0[0,1]$. And a function $g(x)$ defined by
$$
g(x) = \begin{cases}
0, & x = 0\\
1 & x\in (0, 1]
\end{cases}
$$
corresponds to $F$.
So we need to investigate the convergence $G(g_n)$ to $G(g)$ for every functional from $BV_0[0,1]^*$. I have tried many functionals but all of them converged but I can not prove this in general case. Here I stuck.

A: Consider the functional $G$ defined on $BV_0[0,1]$ by
$$
  G(g) = \lim_{x\to 0_+}g(x).
  $$
Then
$
  G(g_n) = 0,
  $
but $G(g) = 1$.


text:
Q: Visual intuition for $\frac{1}{b - a} \int_{a}^{b} u(t) \ \text{d}t \in \overline{\text{co}}(u([a,b]))$
Let $u: [a,b] \to X$ to be a continuous function and $X$ a Banach space.
  Then
  $$
\frac{1}{b - a} \int_{a}^{b} u(t) \ \text{d}t \in \overline{\text{co}}(u([a,b]))
$$
  holds, where $\overline{\text{co}}(M) = \overline{\text{co}(M)}^{\| \cdot \|_{X}}$ is the closed convex hull for some set $M \subset X$ and
  $$
\text{co}(M)
:= \left\{ \sum_{i = 1}^{N} \lambda_i x_i: N \in \mathbb{N}, \lambda_i \in [0,1], \sum_{i = 1}^{N} \lambda_i = 1, x_i \in M \ \forall i \in \{1, \ldots, N\} \right\}.
$$

How can we visualise this result geometrically?

A: The integral on left-hand side (divided by $b-a$), which I denote by $\bar u$ in the visualization, can be interpreted as an average over the trajectory of $u$. I have tried to visualize it for two different trajectories in $\mathbb R^2$. In some sense, it is a weighted average over the points of the trajectory, since "segments" where the velocity is high get a lower weight in the average process. I tried to visualize this fact by the intermediate points, in particular in the second example, where the velocity is high in the beginning and low in the end, thereby shifting $\bar u$ to the right.
The true average would be the mean of the images of infinitely many equidistant "intermediate points" in $[a,b]$ (or, alternatively, one may think of the segments between those points).
As mentioned before, $\bar u$ being a (weighted) average over the trajectory guarantees that it lies in the convex hull of the trajectory


text:
Q: SyntaxError : Invalid syntax jedi There is a problem showing in my vs-code editor SyntaxError: Invalid syntax jedi I don't know why this problem showing it's bothering me so much and there are some weird symbols on my editor ←[0m ←[m you can see this image can anyone tell how to remove both of this from vs-code editor these will be really helpful.

A: Ok I figured it out I don't know somehow my vs-code packages are disabled all I do just enabled them and the problem was gone.

A: VSCode shows invalid syntax jedi even when you miss () for parameters on your defined function.

A: I had a simple code that contains an if condition and it was getting to me Syntax Error: invalid syntax and the I got the parentheses exist there was wrong and the error happened just for the () in my if condition. :)


text:
Q: Relation between angle subtended by object and number of pixels I am making a camera-based application for Android. My problem, is to find the real angle subtended by an object in an image, on the camera, when I have :
1.The length of that object in the image, in pixels,
2.The vertical angle-of-view of the camera,
3.The length of the image,in pixels.
Being new to image processing, I have this (probably basic) doubt. Is there a linear relationship between the angle that an object subtends on the camera, and the number of pixels in the image of the object taken by the camera? Angle subtended: Join the topmost point of the object to camera, then join bottom most point of object to camera. The angle formed at the camera, is the angle subtended. For example: Consider an image that is vertically, 200 pixels in height. The vertical angle of view of the camera, is suppose 20 degrees. So, I can say, that this 20 degrees covers 200 pixels of the image. Now, there is a portion of the image (an object) which is 10 pixels in height. I want to find the angle subtended by this object on the camera, in physical world. Would I be right in telling that, since 200 pixels are covered by 20 degrees, 10 pixels would be covered by 1 degree? That is, this object subtends an angle of 1 degree on the camera?.

As shown in this diagram, I know the values of L (of image), P (of object in image), x (Vertical angle of view of camera), and I want to find y , the angle subtended by object on camera. My assumption is (y/P)=(x/L), that is directly proportional. Would this assumption be correct?

A: Draw horizontal line. It's length D is distance to object.
D * tg(X/2) = L/2
and
D * tg(Y/2) = P/2
so
Y = 2 * Arctg(tg(X/2) * P / L)
(When angles are small, they are (rough) direct proportional)
Addition: case of non-centered object.

P0, P1 - pixel coordinates of object ends relative to center point D
distance Dx = |OD| = L * ctg (X/2)
coordinate D=(Dx,0)
Y = Angle(OP1, OP0) = ArcCos((OP1 x OP0)/(|OP1| * |OP0|)) , where x means scalar product
Y = ArcCos((Dx*Dx+P1*P0)/Sqrt((Dx*Dx+P1*P1)(DxDx+P0*P0)))
Example:
L=L1-L0=768 pixels
X = 42 degrees
Dx = 1000 (rough)
P1 position = 100 pixels
P0 position = -50 pixels
Y = ArcCos((1000*1000-100*50)/(Sqrt((1000*1000 +100*100)*(1000*1000+50*50)))) = 7 degrees (rough)


text:
Q: A simple App Intent to open Settings Accounts Smeone created for me app to open specific menu on android (Settings > Accounts (The menu where the accounts stored in device are shown (Google,whatsapp,telegram,...)
It works on Samsung S8+ but on Huawei Y5 2019 it doesnt work (It's very important for me to work on Huawei)
package com.androidaccounts.app

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        launchAccountScreen()
    }

    fun launchAccountScreen() {
        Intent(android.provider.Settings.ACTION_SYNC_SETTINGS).apply {
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(this)
            finish()
        }
    }
}

Where is the problem? I need to run app on Huawei too
Thank you


text:
Q: WPF Changes not reflecting, Only on cleaning solution changes are reflected Each time i am making any change to the code or xaml, the changes are not getting reflecting . Each time i had to clean and rebuild and run, then the changes are affected. Not sure of this wierd behavior. Just for changing height of a text box as well.
Any solution or setting for this?

A: Make sure that any and all projects in the solution are is sync with each other in "Configuration Manager"
Build/Configuration Manager ...
They should all be targeting the same platform.


text:
Q: Error pulling slider data from custom theme options I am trying to grab the slider data from my custom theme options panel by using the code below. This is returning the following error
Warning: Invalid argument supplied for foreach() in /home/muratgok/public_html/wp-content/themes/default/page - clients.php on line 16
I am guessing that my syntax is not entirely correct but I am struggling to see where. Thank you
        <?php echo $slides = $smof_data['example_slider']; //get the slides array

        foreach ($slides as $slide) {
            echo $slide['title'];
            echo $slide['url'];
            echo $slide['link'];
            echo $slide['description'];
        }

        ?>

Theme options code below
$of_options[] = array(  "name"      => "Slider Options",
                        "desc"      => "Unlimited slider with drag and drop sortings.",
                        "id"        => "example_slider",
                        "std"       => "",
                        "type"      => "slider"
                );

A: Try with and be sure that is an array $smof_data['example_slider']:
    <?php $slides = $smof_data['example_slider']; //get the slides array

    foreach ($slides as $slide) {
        echo $slide['title'];
        echo $slide['url'];
        echo $slide['link'];
        echo $slide['description'];
    }

    ?>


text:
Q: Cannot fully install nvidia drivers for GTX 960M on Ubuntu 20.04 I have a Lenovo Y700 laptop with GTX 960M.
On 18.04 Nvidia drivers worked just fine. I upgraded to 20.04 and installation broke. It seems like installation is somewhat successful but I can't connect to the driver.
I tried removing and reinstalling both through the UI (additional drivers tool) and through CLI, but no success.
$ nvidia-smi
NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running.

$ sudo ubuntu-drivers devices
== /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0 ==
modalias : pci:v000010DEd0000139Bsv000017AAsd00003802bc03sc02i00
vendor   : NVIDIA Corporation
model    : GM107M [GeForce GTX 960M]
driver   : nvidia-driver-440 - distro non-free recommended
driver   : nvidia-driver-435 - distro non-free
driver   : nvidia-driver-390 - distro non-free
driver   : xserver-xorg-video-nouveau - distro free builtin

$ lspci -k | grep -iEA4 "VGA|3D|Display"

00:02.0 VGA compatible controller: Intel Corporation HD Graphics 530 (rev 06)
    Subsystem: Lenovo HD Graphics 530
    Kernel driver in use: i915
    Kernel modules: i915
00:14.0 USB controller: Intel Corporation 100 Series/C230 Series Chipset Family USB 3.0 xHCI Controller (rev 31)
--
01:00.0 3D controller: NVIDIA Corporation GM107M [GeForce GTX 960M] (rev a2)
    Subsystem: Lenovo GM107M [GeForce GTX 960M]
    Kernel modules: nvidiafb, nouveau
07:00.0 SD Host controller: O2 Micro, Inc. SD/MMC Card Reader Controller (rev 01)
    Subsystem: Lenovo SD/MMC Card Reader Controller

$ sudo apt-get install nvidia-driver-440
Reading package lists... Done
Building dependency tree
Reading state information... Done
nvidia-driver-440 is already the newest version (440.100-0ubuntu0.20.04.1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

A: Try sudo apt autoremove --purge nvidia-driver-440 and then sudo apt install nvidia-driver-440. This should solve the problem if it is related to only drivers. Keep me updated about the results.
Better you run sudo apt autoremove --purge nvidia-driver-440 && sudo apt install nvidia-driver-440, as you might lose the display while driver re-installation.


text:
Q: How to add a click handler to a WPF Button in C++/CLR? In C#, I can do (*):
        Button b = new Button();
        b.Click += ButtonOnClick;
    :
    void ButtonOnClick(object sender, RoutedEventArgs e)
    {
        // do something
    }

But in C++/CLI I can't do:
    Button ^ b = gcnew Button();
    b->Click += ButtonOnClick;
:
void ButtonOnClick(Object ^ sender, RoutedEventArgs ^ e)
{
    // do something
}

I get a compiler error complaing about the += ButtonOnClick:
2>.\blub.cpp(108) : error C3867: 'MyListBoxItem::ButtonOnClick': function call missing argument list; use '&MyListBoxItem::ButtonOnClick' to create a pointer to member
(The tip the compiler gives me doesn't work because it isn't a static method.)
What is the equivalent of (*) in C++/CLI ?
Thx
   Marc

A: try

 b->Click += MAKE_DELEGATE( System::EventHandler, ButtonOnClick );

b->Click += gcnew System::EventHandler(this, &ButtonOnClick);


text:
Q: how to autoclick with xpath I'm trying to autoclick with full xpath but nothing happens where is the problem.
thanks a lot
here is the code:
browser.get("https://www.gazzetta.gr/")
browser.find_element(By.XPATH,"/html/body/header/div/div[2]/nav/ul[2]/li[6]").click()

A: There are cookies button and a pop, you need to click on that beforehand, in order to interact with ΠΡΟΓΡΑΜΜΑ TV link
You can try below code :
browser.maximize_window()
browser.implicitly_wait(30)
browser.get("https://www.gazzetta.gr/")
wait = WebDriverWait(browser, 10)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[aria-label='ΠΕΡΙΣΣΟΤΕΡΕΣ ΕΠΙΛΟΓΕΣ']"))).click()
wait.until(EC.element_to_be_clickable((By.XPATH, "(//button[@aria-label='ΑΠΟΘΗΚΕΥΣΗ ΚΑΙ ΕΞΟΔΟΣ'])[2]"))).click()
wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "ΠΡΟΓΡΑΜΜΑ TV"))).click()

Imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


text:
Q: Migration from gulp v3 to v4 I've tried to migrate from gulp v3 to v4, but when I write 'gulp build' I get such error

D:\Projects\Exo\exo\src\COG.SRM\node_modules\undertaker\lib\set-task.js:10
  assert(typeof fn === 'function', 'Task function must be specified');
  ^ AssertionError [ERR_ASSERTION] [ERR_ASSERTION]: Task function must
  be specified
      at Gulp.set [as _setTask] (D:\Projects\Exo\exo\src\COG.SRM\node_modules\undertaker\lib\set-task.js:10:3)
      at Gulp.task (D:\Projects\Exo\exo\src\COG.SRM\node_modules\undertaker\lib\task.js:13:8)
      at Object. (D:\Projects\Exo\exo\src\COG.SRM\gulpfile.js:341:6)
      at Module._compile (internal/modules/cjs/loader.js:936:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
      at Module.load (internal/modules/cjs/loader.js:790:32)
      at Function.Module._load (internal/modules/cjs/loader.js:703:12)
      at Module.require (internal/modules/cjs/loader.js:830:19)
      at require (internal/modules/cjs/helpers.js:68:18)
      at execute (C:\Users\SS\AppData\Roaming\npm\node_modules\gulp\node_modules\gulp-cli\lib\versioned\^4.0.0\index.js:36:18)

According to my researches, I should change my gulpfile.js file.
Could someone help me please how to change such commands according to the new version of gulp:
gulp.task('clean-css', function (cb) {
    return rimraf(paths.css, cb);
});

gulp.task('clean', ['clean-css', 'clean-fonts', 'clean-js']);

gulp.task('build-css', ['lint-css'], function () {});


text:
Q: mySQL UPDATE query wont work CODE:
$query="UPDATE americana SET 7='99' WHERE Bdate='2011-04-15'";
mysql_query($query);

NOTICE:7 and Bdate are column names.

ERROR: Database query faild: You have
  an error in your SQL syntax; check the
  manual that corresponds to your MySQL
  server version for the right syntax to
  use near '7='99' WHERE
  Bdate='2011-04-15'' at line 1.

Any idea on how to solve this problem?

A: enclose 7 in backticks `
$query="UPDATE americana SET `7`='99' WHERE Bdate='2011-04-15'";

A: try
$query="UPDATE americana SET `7`='99' WHERE Bdate='2011-04-15'";
mysql_query($query);

A: If 99 is an int you don't want quotes on that, mysql will see that as a string, refuse your insert and a kitten will die soemwhere.
$query="UPDATE americana SET `7`= 99 WHERE Bdate='2011-04-15'";
mysql_query($query);


text:
Q: Merge multiple geo-referenced *,jpg files into a GeoTIFF in QGIS I have a set of georeferenced *.jpg files from a UAV flight and want to merge them into a GeoTIFF Mosaic. Is it possible in QGIS ?

A: No, this is not possible in QGIS.  The georeferenced images will contain x, y, and z values embedded in the EXIF tags of the images.  While there are several options for adding those images to QGIS you would viewing the location of the camera at capture time.  Additionally, the image would be oriented with the top edge of the camera pointing north (although there are plugins to display the image rotated based on the azimuth value in the EXIF).
You are looking for structure from motion (SfM) photogrammetry software. SfM software will exploit the EXIF data, determine image adjacency, and stitch images together to produce a single orthorectified image.   A free and opensource option would be Open Drone Map (or WebODM) depending on your OS.  WebODM is installed via Docker so there is a bit of a technical challenge to get things up and running.  I believe there is an Ubuntu repository for ODM.
Some commercial SfM softwares are Agisoft Photoscan, Drone Deploy, and Pix4D.  These three options offer a free trial version that will get you 30 days to accomplish your task.


text:
Q: AngularJS - Purpose of Writing $scope Before function($scope) I started learning AngularJS by seeing few examples in Google, but no where explained about this one. So far i went through few examples where they have written the controllers like
myApp.controller('MainCtrl', function ($scope) {

   $scope.text = 'Hello, Angular fanatic.';

});

But in few other blogs they are including '$scope' before function($scope)
myApp.controller('MainCtrl', ['$scope', function ($scope) {

   $scope.text = 'Hello, Angular fanatic.';

}]);

Is there any difference ? not only $scope, adding other dependencies too in the similar way.

A: Read the section on A note on minification.
https://docs.angularjs.org/tutorial/step_05
In short, both ways of declaring dependencies are the same. The array notation is used so that minifier won't minify the dependencies and angular would know exactly what to fetch.
If you don't minify your code, you can use either way for dependency injection.

A: There is indeed. Writing ['$someInjectable', function ($someInjectable) is what we call 'minification proofing'. Some post-compiler will come along and minify your javascript, garbling your variables into cryptic a, b, c, ... etc. Internally, AngularJS inspects function ($scope) to determine that this function needs to receive a handle to $scope. If you minify the code, variables names are lost, but literals remain constant. The array-chain syntax is a way to make sure that angular can determine that function (a, b) is actually function ($scope, $element).


text:
Q: Create Azure linux VHD to use in Pipeline I would like to prepare an ubuntu image with preinstalled dependencies (python, go, etc.) so that the pipelines do not waste times installing them each time. I expected to find some kind of Dockerfile-like interface, but I have not been able to find an easy way to accomplish this.
What I understood is that I need to create a new virtual machine scale set with this image and then use it for the agent pool. But how do I create the vhd image?

A: You can use one of the below tools to build images on Azure.

*

*packer - more industry-standard across clouds (like Terraform from Hashicorp)

*Azure Image Builder - works only on Azure (from Microsoft)

Both of the above tools can be used to customize base (golden) images available on the Azure marketplace or if you have an existing VM image on-prem, it can be uploaded following documentation here.
If you have multiple subscriptions & you would like to build on one subscription & use them on other subscriptions/other tenants, you would need to use Azure Compute Gallery. This gallery also helps you to version VM images like docker images. In short, it's like a docker registry for VM images.
If you would like to use existing marketplace images (base Ubuntu in your case), you don't need to convert them into VHD. Packer/Azure Image Builder would basically provision a VM out of the base image, install packages (customization of your choice), creates a snapshot of the VM & creates an image out of that.
With packer, you would be writing a JSON builder like the below. Source code is taken from here.
{
  "builders": [{
    "type": "azure-arm",

    "client_id": "f5b6a5cf-fbdf-4a9f-b3b8-3c2cd00225a4",
    "client_secret": "0e760437-bf34-4aad-9f8d-870be799c55d",
    "tenant_id": "72f988bf-86f1-41af-91ab-2d7cd011db47",
    "subscription_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx",

    "managed_image_resource_group_name": "myResourceGroup",
    "managed_image_name": "myPackerImage",

    "os_type": "Linux",
    "image_publisher": "Canonical",
    "image_offer": "UbuntuServer",
    "image_sku": "16.04-LTS",

    "azure_tags": {
        "env": "dev",
        "task": "Image deployment with packer on Azure is fun!"
    },

    "location": "East US",
    "vm_size": "Standard_DS2_v2"
  }],
  "provisioners": [{
    "execute_command": "chmod +x {{ .Path }}; {{ .Vars }} sudo -E sh '{{ .Path }}'",
    "inline": [
      "apt-get update",
      "apt-get upgrade -y",
      "apt-get -y install nginx",
      "/usr/sbin/waagent -force -deprovision+user && export HISTSIZE=0 && sync"
    ],
    "inline_shebang": "/bin/sh -x",
    "type": "shell"
  }]
}

A suggestion from my side:: /usr/sbin/waagent -force -deprovision+user command ran at the end is extremely important when building images on the Azure as it cleans up the cloud-init/waagent user packer provisioned, ssh keys & other things to have a clean start for a customized image.


text:
Q: File not uploading and moving to folder $image = $_FILES['picture']['name'];
$id=$_SESSION['id'];
//This function separates the extension from the rest of the file name and returns it
 function findexts ($filename)
 {
 $filename = strtolower($filename) ;
 $exts = split("[/\\.]", $filename) ;
 $n = count($exts)-1;
 $exts = $exts[$n];
 return $exts;
 }

 $ext = findexts ($_FILES['picture']['name']) ;
 //This assigns the subdirectory you want to save into... make sure it exists!
 $target = "mainimage/";
 //This combines the directory, the random file name, and the extension
 $target = $target . $id.".".$ext;
 if(move_uploaded_file($_FILES['picture']['tmp_name'], $target))
 {
 echo ("This is your new profile picture!");
 }
 else
 {
 echo "Sorry, there was a problem uploading your file.";
 }

for some reason the "else" keeps showing up (there was a problem uploading the file). I put comments in everything that I am trying to do. please help! thanks!

A: To close the question as per OP's request.
The issue is that you need to increase the maximum size for uploads. PHP's default is usually 2M and you are most probably trying to upload a file larger than what the maximum setting is set to.
This can be achieved in two ways.
By editing your php.ini file with the following settings:
; Maximum allowed size for uploaded files.
upload_max_filesize = 40M

; Must be greater than or equal to upload_max_filesize
post_max_size = 40M

or via an .htaccess file placed in the root of your server:
php_value upload_max_filesize 20M
php_value post_max_size 30M


text:
Q: TypeScript and React issue Well, recently I've started using the React.js library, and now I'm trying to use it with Firebase Hosting, with the TypeScript language. But, every time I try to write some code using tsx it just doesn't work, for example:
import * as React from "react"; //red underline under "react"
import "./App.css";

import logo from "./logo.svg";

class App extends React.Component {
  render() {
    return
Hello
; //red underline under
 and

  }
}

export default App;

that way I just can't write any jsx code here, because it always appears the issue:
test.tsx(1,1): error TS7026: JSX element implicitly has type 'any' because no interface 'JSX.IntrinsicElements' exists

Can somebody please help me with this?

A: How did you create your react application? If you used create-react-app you'll need to use react-scripts-ts as your --scripts-version flag. This should install the @types packages along side React's dependencies, eliminating your problem.
Also, it should get you started with an App.tsx file as the one provided in your snippet is not a valid typescript react component (i.e. the your render() method is not public).
Happy hacking!

A: I solved this issue by reloading VSCode.
ctrl+shift+P > Developer: Reload Window


text:
Q: Replace the images with their alt attribute PHP This is the HTML code:

     Hello all

I want a PHP code to search content if it images and replaces the images with their alt attribute.
I want the output to be:

     Hello all

I try to make this by using Regex and this is my code but it's not working:
preg_replace('/]+>/g', '$1', $comment_content)

Any guide really appreciate.
Thank you.

A: <?php
$html = '

     Hello all

';
$dom = new DOMDocument();
$dom->loadHTML('<meta charset="utf-8">' . $html . '');
while ($dom->getElementsByTagName('img')->length) {
    $oldnode = $dom->getElementsByTagName('img')[0];
    $newnode = $dom->createTextNode($oldnode->getAttribute('alt'));
    $oldnode->parentNode->replaceChild($newnode, $oldnode);
}

header('Content-Type: text/html; charset= UTF-8');
echo $dom->saveHTML($dom->getElementsByTagName('div')[0]);


text:
Q: Is there a way to translate column names in datagrid filters? , I have been looking for a way of adding localization to the column field names in filters in Datagrid and I couldn't find the way, can you give me a hand with this, cheers.
Filters modal


text:
Q: Details about ApplicationUnderTest.Launch() method's fileName and alternateFileName arguments I'm having a hard time trying to figure out some details about the arguments of the ApplicationUnderTest.Launch(String, String) method. From the MSDN page, they are described like this:
fileName
    Type: System.String
    The file name of the application to start.

alternateFileName
    Type: System.String
    The alternate file name that has environment variables.

My questions are:

*

*What is the purpose of alternateFileName? Is it only used when fileName is not found or not valid? Does the Launch() method always try the fileName first?

*Does fileName support environment variables in it? Does alternateFileName always require at least one environment variable in it?

A: Based on my own experience (and a little help from a decompiler), here's what I've discovered.

What is the purpose of alternateFileName?

alternateFileName allows you to use a path with environment variables that are expanded at run time. There is also some special handling to convert environment variables only found on a 64-bit environment to those found on a 32-bit environment, if necessary (for example, converting %programfiles(x86)% to %programfiles%).

Is it only used when fileName is not found or not valid? Does the Launch() method always try the fileName first?

If you use one of the Launch() overloads that include the alternateFileName parameter, it is always checked first. If there is a matching file at the expanded path, then that path is used and fileName is never checked. If there is no matching file at the expanded alternateFileName path, only then will it use fileName.
Note: I just discovered a bug present in Visual Studio 2013 Update 4 where alternateFileName is in fact incorrectly handled on a 32-bit system. In that case, alternateFileName was always getting prepended with the value C:\Windows\System32 so it would end up with a value like C:\Windows\System32C:\Program Files\foo\bar.exe. Since this is an invalid value, the system was only relying on fileName.

Does fileName support environment variables in it?

No, any environment variables in fileName are not expanded.

Does alternateFileName always require at least one environment variable in it?

No, environment variables are not required -- although I can't think of how it would be useful to supply a value for alternateFileName without them.

A: Here's what I do:
private static ApplicationUnderTest _application;

public static ApplicationUnderTest LaunchApplicationUnderTest(string applicationPath,
         bool closeOnPlaybackCleanup)
      {
         Process[] processes = Process.GetProcessesByName("MyApp");

         if (processes.Length > 0)
         {
            _application = ApplicationUnderTest.FromProcess(processes[0]);
         }
         else
         {
            _application = ApplicationUnderTest.Launch(applicationPath);
            _application.CloseOnPlaybackCleanup = closeOnPlaybackCleanup;
         }

         return _application;
      }


text:
Q: Построение конвейера обработки данных на BlockingCollection, где первая стадия ожидает данные от IObservable разбираюсь с BlockingCollection и построение конвейера обработки данных на его основе.
В официальном руководстве, приводятся пример первой стадии конвейера, в которой данные читаются из источника реализующего IEnumerable.
Я хотел разобраться, как сделать первую стадию конвейера, ожидающую получение данных от IObservable.
Для упрощения приведу только 2 стадии конвейера чтение и запись.
Сами методы обработки внутри стадии конвейера будут написаны заранее (до рефакторинга с применением BlockingCollection) и скорее всего будут асинхронные.
У меня вопрос по реализации метода ReadStringsFromObservableSourse - верно ли я его реализовал, т.е. обработка ошибок и отмена выполнения.
_ts.GetSourseStringObservable() - выдает IObservable<string>

В моем случае я вручную реализовал поступление данных через GetSourseStringObservable() используя класс SensorPolling, который периодически опрашивает какой-то ресурс.
Но, в реальном случае, скорее всего будут нативные реализации IObservable, например, ожидание данных с очередей обмена или каких то внешних ресурсов.
Вот меня интересуют все подводные камни которые могут быть в ожидании данных в конвейере.
public class Pipline
{
    private readonly TextSource _ts;
    public Pipline(TextSource ts)
    {
        _ts = ts;
    }

    public async Task DoPipeline(CancellationToken token)
    {
        int seed = 5;
        int BufferSize = 50;
        var buffer1 = new BlockingCollection<string>(BufferSize);

        using var cts = CancellationTokenSource.CreateLinkedTokenSource(token);
        var f = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.None);
        var stage1 = f.StartNew(() => ReadStringsFromObservableSourse(buffer1, seed, cts).GetAwaiter().GetResult());
        var stage2 = f.StartNew(() => WriteSentences(buffer1, cts).GetAwaiter().GetResult());

        await Task.WhenAll(stage1, stage2);
    }

    private async Task ReadStringsFromObservableSourse(BlockingCollection<string> output, int seed, CancellationTokenSource cts)
    {
        var observableTask= new TaskCompletionSource<object>();
        try
        {
            var ct = cts.Token;
            using var observerLifeTime = _ts.GetSourseStringObservable().Take(seed).Subscribe(
                i =>
                {
                    if (ct.IsCancellationRequested)
                    {
                        observableTask.SetCanceled();
                        return;
                    }
                    output.Add(i, ct);
                },
                e=>
                {
                    observableTask.SetException(e);
                },
                () =>
                {
                    observableTask.SetResult(default);
                }
            );
            await observableTask.Task.WaitAsync(ct);
        }
        catch (Exception e)
        {
            cts.Cancel();      //нотификация отмены остальным стадиям конвеера.
            if (!(e is OperationCanceledException))
                throw;
        }
        finally
        {
            output.CompleteAdding();
        }
    }

    private async Task WriteSentences(BlockingCollection<string> input, CancellationTokenSource cts)
    {
        try
        {
            var token = cts.Token;
            foreach (var phrase in input.GetConsumingEnumerable())
            {
                if (token.IsCancellationRequested) break;
                await Task.Delay(100);
                var result = phrase + "  Stage_Write";
                Console.WriteLine(result + "   " + DateTime.Now.ToString("T")); //Запись полученного результата
            }

        }
        catch (Exception e)
        {
            // If an exception occurs, notify all other pipeline stages.
            cts.Cancel();
            if (!(e is OperationCanceledException))
                throw;
        }
    }
}

public class TextSource
{
    public IObservable<string> GetSourseStringObservable()
    {
        var sensorFunc = new Func<CancellationToken, Task<string>>((ct) => GetValueFromRemoteSource("Get only new Values", ct));
        var sp= new SensorPolling<string>(sensorFunc);
        var xs=sp.Polling();
        return xs;
    }

    private int i = 0;
    private async Task<string> GetValueFromRemoteSource (string filter, CancellationToken ct)
    {
        //filter not Use
        i++;
        await Task.Delay(500, ct);
        return i.ToString();
    }
}

public class SensorPolling<T>
{
    private readonly Func<CancellationToken, Task<T>> _tryTakeDataAsync;

    public SensorPolling(Func<CancellationToken, Task<T>> tryTakeDataAsync)
    {
        _tryTakeDataAsync = tryTakeDataAsync;
    }

    public IObservable<T> Polling()
    {
        return Observable.Create<T>(
            (obs, ct) =>
            {
                return Task.Run(async () =>
                {
                    while (!ct.IsCancellationRequested)
                    {
                        try
                        {
                            var data = await _tryTakeDataAsync(ct);
                            obs.OnNext(data);
                        }
                        catch (OperationCanceledException)
                        {
                            obs.OnCompleted();
                        }
                        catch (Exception e)
                        {
                            obs.OnError(e);
                        }
                    }
                    Console.WriteLine("Loop terminated");
                }, ct);
            });
    }
}

P.S. Реализация ReadStrings как в примере с офф. сайта получение данных через IEnumerable  (_ts.GetNextString(seed)).
    private async Task ReadStrings(BlockingCollection<string> output, int seed, CancellationTokenSource cts)
    {
        try
        {
            var ct = cts.Token;
            foreach (var phrase in _ts.GetNextString(seed))
            {
                if (ct.IsCancellationRequested) break;
                await Task.Delay(100);
                var result = phrase + " Stage_Read"; //Работа стадии 1
                Console.WriteLine(result  + "   " + DateTime.Now.ToString("T"));
                output.Add(result, ct);
                throw new Exception("gfhgdfgfd");
            }
        }
        catch (Exception e)
        {
            // If an exception occurs, notify all other pipeline stages.
            cts.Cancel();
            if (!(e is OperationCanceledException))
                throw;
        }
        finally
        {
            output.CompleteAdding();
        }
    }


text:
Q: Checking for freetype2 error when installing php5.6 on arch linux I'm trying to install PHP version 5.6.37 from AUR using makepkg -i command, but when it reaches the moment to check for the "freetype2" it displays the error:

checking for freetype2... configure: error: freetype-config not found.

I already have 7.2 installed, but I need the 5.6 for an older project, and as in Ubuntu, I intend to have both installed.
makepkg -i
==> Making package: php56 5.6.37-1 (Wed 12 Sep 2018 12:27:39 PM +08)
==> Checking runtime dependencies...
==> Checking buildtime dependencies...
==> Retrieving sources...
  -> Found php-5.6.37.tar.xz
  -> Found php-5.6.37.tar.xz.asc
  -> Found php.ini.patch
  -> Found apache.conf
  -> Found php-fpm.conf.in.patch
  -> Found logrotate.d.php-fpm
  -> Found php-fpm.service
  -> Found php-fpm.tmpfiles
  -> Found use-enchant2.patch
  -> Found php-freetype-2.9.1.patch
==> Validating source files with sha512sums...

[...]

checking whether to enable truetype string function in GD... yes
checking whether to enable JIS-mapped Japanese font support in GD... no
If configure fails try --with-vpx-dir=<DIR>
checking for jpeg_read_header in -ljpeg... yes
checking for png_write_image in -lpng... yes
checking for XpmFreeXpmImage in -lXpm... yes
checking for pkg-config... (cached) no
checking for freetype2... configure: error: freetype-config not found.
==> ERROR: A failure occurred in build().
    Aborting...

Installing freetype2 with Pacman didn't solve it.

A: ln -s /usr/bin/pkg-config /usr/bin/freetype-config
and in PKGBUILD
--with-freetype-dir=no \


text:
Q: Run Git as Apache on remote server I'm trying to set up a workflow where my code base is version-controlled under Git, and then deployed to a live server over SSH.
I wrote a simple shell script that I run from my machine that opens an SSH connection and then executes git pull on the remote server. However, because this is being ran under root (don't ask) all files and folders that are then created/updated by Git are given the user/group of root too, instead of apache.
How do re-assign apache as the user/group of these files/folders? Do I need to alter my workflow, or could I just run chown and chgrp after I've pulled from Git? Ideally, I'd like to just fix where I'd rather treat the problem though rather than treating the symptoms.

A: You'ld better use another user than root. Anyway, use su -c or sudo to run git pull with the correct username


text:
Q: Low Flash AS3 Performance I'm working on a game coded in AS3 using the Alternativa3D 7.8 engine and it just doesn't have the FPS I was hoping to achieve with it and I'm trying to fully understand why. I get it that having 3D objects in a scene can be very taxing on performance but I'm using only a very limited number of 3d objects and each of those has a relatively small polygon count.
I'm wondering if there is something else like a memory leak causing this on top of the actual rendering of the scene.
I'd like to figure out a way to view how the performance is being distributed in my code to see if there are certain areas that are causing this. I usually only get about 10-15 FPS on my computer and I'd like to get that to around a constant 20-24 or higher if possible.

A: I don't think that this question should be downvoted necessarily, though it is a bit broad. OP is asking about general performance tips for AS3 applications.
It's true that we can't give him specific pointers without seeing his code, but we could still provide him with more general tips/tricks. Here's some analysis, pretty general:
I don't think your performance problems necessarily have anything to do with your 3D, though they might. The instant the game world comes on screen even the mouse movement is tremendously slowed, whereas the instant I pause it the framerate improves - which suggests to me that you are doing a lot of iteration and calculation on every frame.
I'd start with this: do you have any computationally intensive loops going on inside of your main game loop? For instance, I see that you're working with sea level as it effects landmass - are you doing something like calculating all of your water properties on every frame?
Having a lot of "3D" objects isn't necessarily a problem, because a 3D object is just a set of points. They're more intensive to position than 2d objects because you're including an additional dimension, but not so much more intensive that a few 3d objects would cause this kind of performance. I don't think that they are your problem (though I could be wrong).
Rather, it's what kind of calculations you're performing. Look for loops, figure out what you can comment out and instantly see better performance, and then once you've isolated it see what you can do about caching the outputs of those computations so that you don't have to recalc them on every frame.
Cheers,
mb


text:
Q: ¿Como lanzar actividad en blanco al presionar boton SearchView? estoy siguiendo este tutorial para crear un SearchView en android studio con php y mysql todo funciona bien el unico problema es que los resultados de la busqueda se muestran en un Recyclerview que esta en el layout principal de la app o sea el activity_main donde yo ya tengo otras cosas para mi app, quisiera saber como podria mostrar los resultados en un layout en blanco al momento de hacer la busqueda sin tener que salir de la actividad principal, espero su consejo gracias.

A: Ocupas dividir la pantalla amigo
Aquí aplicarías definir "pesos" con la propiedad layout_weight en tu vista, suponiendo el siguiente ejemplo, en el cual necesitamos que nuestra vista de abajo siempre ocupe un 50% de la pantalla y este posicionado en la parte inferior, pero también necesitamos agregar otras 2 vistas, las cuales una ocupe el 30% de la pantalla y la segunda el 20%.

Si tomamos en cuenta el total de la pantalla como el 1 , asignamos un valor de .50 para que siempre ocupe el 50% de la pantalla nuestra vista :
   <WebView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".50"
        android:id="@+id/webView"
        android:layout_alignParentBottom="true" />

y asi con las demás vistas, una ocupara el 30% (asignamos .30) y la otra el 20% (asignamos .20):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".30"
        android:text="Vista 1" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".20"
        android:text="Vista 2" />

    <WebView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".50"
        android:id="@+id/webView"
        android:layout_alignParentBottom="true" />

</LinearLayout>

Podemos asegurar que las vistas tendran el porcentaje especificado en la pantalla y tu decides donde obtener el resultado.
Espero mi palomita amigo :D

A: En el layout principal creas 2 layouts y en el que quede en la parte inferior agregas el recyclerView:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

<RelativeLayout
    android:id="@+id/layout_01"
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <TextView
        android:id="@+id/textView1"
        android:text="Layout Superior"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="116dp"
        android:layout_marginStart="116dp"
        android:layout_marginTop="17dp" />
</RelativeLayout>

<RelativeLayout
    android:id="@+id/layout_02"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:layout_below="@+id/layout_01">

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginLeft="142dp"
    android:layout_marginStart="142dp"
    android:layout_marginTop="24dp"
    android:text="Resultados" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/textView2"
    android:scrollbars="vertical"/>
</RelativeLayout>

En este caso el tamaño (android:layout_height="200dp") es de 200 dp, pero puede ser el que quieras o si quieres que ocupen mitad de pantalla agrega android:layout_weight=".5"


text:
Q: How to get values from a form and send it to Java class using javascript? First i have declare that i am new to javascript. I have created a form that gets Id, Name, Age & Dept. I want it to send to java class and i have to show back the data along with the other data in the data Base using DWR.
For this i already done coding for showing the table, below that i have my form.
After the form "Save" button calls the below function save(). Here, my form and function.
The Form:
Id:<input type="text" id="id"/>

Name:<input type="text" id="name"/>

Age:<input type="text" id="age"/>

Dept:<input type="text" id="dept"/>

<input id="Save" type="button" value="Save" onclick="save()"/>

The function:
function save(){
employee = new Object();
employee.id = dwr.util.getValue(iD);
employee.name = dwr.util.getValue(namE);
employee.age = dwr.util.getValue(agE);
employee.dept = dwr.util.getValue(depT);

dwr.engine.beginBatch();
Employee.aouEmployee(employee);  //   **Java method call to store data in DB**
fetch();//An another function which loads all the data in the table.
dwr.engine.endBatch();
}

But, i cant get proper output for the above function. I am also cant able to find the mistakes(due to no error msgs)
Any suggestions will be more appreciative
Thanks
UPDATES ARE HIGHLIGHTED BY BOLD

A: *

*Install Firefox, if you haven't already

*Install Firebug

*Use Firebug to debug JS, as well as its Net panel to debug AJAX calls; use console.log(string) to get feedback

*Profit.

By the way, for my curiosity: what's up with capitalising the last letter in a variable?


text:
Q: Wrong proof of $TM$ is diffeomorphic to $M\times \mathbb{R^m}$ I want to see what's wrong in here:
Let $M$ be a smooth manifold with dimension $m$. I will show $TM$ is diffeomorphic to $M\times \mathbb{R^m}$.
proof) Define $F:TM\rightarrow M\times \mathbb{R^m}$ by $F(p,v)=(p,v^1,...,v^m)$ where $v=v^i\frac{\partial}{\partial x^i}\in T_pM$.
Let $(U,\phi)$ be a chart containing $p$. Then, $(\pi^{-1}(U),\widetilde{\phi})$ is a chart containing $(p,v)$ where $\pi:TM\rightarrow M$ given by $\pi(p,v)=p$ and $\widetilde{\phi}(p,v)=(\phi(p),v^1,...,v^m)$. And $(U\times \mathbb{R^m},\phi \times Id)$ is a chart containing $F(p,v)$.
Using above, $(\phi\times Id)\circ F\circ \widetilde{\phi}^{-1}:\widetilde{\phi} (\pi^{-1}(U))\rightarrow \phi(U)\times \mathbb{R^m}$ is an identity map (Note that $\widetilde{\phi} (\pi^{-1}(U))$ is $\phi(U)\times \mathbb{R^m}$ by calculation.). Thus $F$ is smooth.
$F^{-1}:M\times \mathbb{R^m}\rightarrow TM$ is given by $F^{-1}(p,v^1,...,v^m)=(p,v)$ where $v=v^i\frac{\partial}{\partial x^i}\in T_pM$. With above charts, we have $\widetilde{\phi}\circ F^{-1}\circ (\phi\times Id)^{-1}:\phi(U)\times \mathbb{R^m}\rightarrow \widetilde{\phi}(\pi^{-1}(U))$ is also identity map. Thus $F^{-1}$ is smooth. $\blacksquare$
But I know $TM$ may not diffeomorphic to $M\times \mathbb{R^m}$. What's wrong in my proof?

A: First of all, the $F$ you have defined is not actually a map on the tangent bundle of the manifold.The point is,when you are explicitly using coordinates to define a map,what you need to check is whether such a thing is independent of the chart chosen.The reason is that, the map you are actually defining takes a point on the manifold and gives you an output, but the same point on the manifold may have different coordinate representations.That is the reason why you cannot just use a chart and work your way with respect to it, it simply might not give you a map on the manifold at all.In your case, for example, if I use a different local chart at that point, then a point on $TM$ would end up having two different coordinate representations, what will $F$ be then?
Edit :- I thought I need to mention this.Another very common mistake with using charts to define maps is, a 'proof' that all smooth $n$-manifolds are orientable.Indeed, one just takes the 'everywhere positive $n$-form' given by $\omega = dx^1\wedge dx^2\wedge ..\wedge dx^n$.Spot the error.
:-)