text:
Q: Constrain WPF element width inside its container I am placing a templated Button with some content in inside it (both Image and TextBlocks) in some other control's Grid:
<SomeControl>
   <Grid>
       <SpecialButton/>
   </Grid>
</SomeControl>

<Style TargetType="{x:Type local:SpecialButton}">>
    ...
    <Setter Property="Template">
        <Setter.Value>
        ...
            <TextBlock/>
            <TextBlock/>
        </Setter.Value>
</Style>

The "SomeControl" control's width is dynamic - that is - it can be dynamically changed according to the screen width, it's container width, etc. Hence I use another method to calculate the "SpecialButton"'s width.
As long as the TextBlock within the button is not wider then the button itself The "SpecialButton" is being perfectly matching its size to it's "SomeControl" container.
However, if the TextBlock's text is longer then the width of the "SpecialButton", the "SpecialButton" right border disappears and the button looks really bad. That being said, the "SpecialButton"'s width is still constained to its containers' width although drawing is not being well calculated.
I am trying to find a way to constain the TextBlock's (or even better the complete Grid's width) without defining an absoulte width, so the "SpecialButton" will still get drawn well and ignore it's children's overflow. Something like CSS's {overflow:hidden} would have been great...
 Note:
 I can't allow wrapping since the "SpecialButton" height is also constained (and manually calculated).

A: Width (and height) in WPF elements is pretty straightforward once you get used to it.  Your grid, by default is set to Auto width, which means it will request 100% of the width of the parent.
Instead of setting a maximum size, I generally put items that I want dynamically sized and positioned in a grid and set grid row and column sizes.  So if I want something to take up 1/3 of the available horizontal space, I can have a grid with two columns, one with width set to "1*" and the other set to "2*" (2/3 being twice the size of 1/3), and put my item in column 1 set to take up all available width.
In your case, the text needs to be truncated as it is doing its best to render all of the text, and is extending the button past the bounds of it's container to do it.  There are two options for the built in trimming capability.  TextTrimming="CharacterEllipsis" and TextTrimming="WordEllipsis"  Just put that in your textblocks.  I would put the textblocks in a container of some kind to keep them separate.  If the first has content that is long enough, it may push the other completely off the side.
Element Sizing
<Window
    x:Class="MainWindow"
    x:Name="Window"
    Title="MainWindow"
    Width="640" Height="480">
    <Grid x:Name="LayoutRoot" DataContext="{Binding}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="2*"/>
        </Grid.ColumnDefinitions>
        <local:SomeControl Margin="8,8,8,0"/>
    </Grid>
</Window>

Text Trimming
<ControlTemplate x:Key="ButtonBaseControlTemplate1" TargetType="{x:Type ButtonBase}">
    <Microsoft_Windows_Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" Fill="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" RenderDefaulted="{TemplateBinding Button.IsDefaulted}" SnapsToDevicePixels="True" ThemeColor="Metallic">
        <TextBlock Text="{TemplateBinding Content}" TextTrimming="WordEllipsis" HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Microsoft_Windows_Themes:ButtonChrome>
    <ControlTemplate.Triggers>
        <Trigger Property="IsKeyboardFocused" Value="True">
            <Setter Property="RenderDefaulted" TargetName="Chrome" Value="True"/>
        </Trigger>
        <Trigger Property="ToggleButton.IsChecked" Value="True">
            <Setter Property="RenderPressed" TargetName="Chrome" Value="True"/>
        </Trigger>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

Additionally, you might want to set the tooltip of your textboxes to the value of the text also.  If the text is truncated and a user want to see what it is, they can mouse over the button and find out.


text:
Q: Creating a Panel from a 3D Ndarray I am trying to build a panel from a 3 dimensional Nd array by using optional axis labels in python 3 on colab. and i get an error message of object takes no parameters on line 7 (minor_axis).
import pandas as pd
import numpy as np
P1 = pd.Panel(np.random.randn(2,5,4),
              items=['Item1','Item2'],
              major_axis=pd.date_range('10/05/2018', periods=5),
              minor_axis=['A','B','C','D'])
P1

Type Error: Object() takes no parameters

Can somebody please explain it to me what I am doing wrong here???

redpajama_set_name: RedPajamaStackExchange


text:
Q: DataGridViewComboBoxCell in an unbound DataGridView WinForm control I am new to the DataGridView WinForm control and just do not like data Binding. I Used to use Spread OCX back 100 years ago and found it friendly. Now I am running into a problem try to do something simple:
I have a grid with two columns:
1) Name
2) Status
I want to loop through my collection of "ChinaVisas" and display the applicant's name and the status of his application. I want to make the status column a drop drop that can allow the user to change the value by selecting a different item in the drop down list.
Here's what I am doing. I have a feeling that this isn't the data binding way that most people would code it, but here ya go:
Private Sub PopulateGridVisa()

    grdVisa.Rows.Add(_Order.ChinaVisas.Count)

    For r As Integer = 0 To _Order.ChinaVisas.Count - 1

        Dim CurrentChinaVisa As ChinaVisa = _Order.ChinaVisas(r)

        For c As Integer = 0 To grdVisa.Columns.Count - 1

            Select Case c

                Case 0
                    Dim CurrentCell As DataGridViewCell = grdVisa.Rows(r).Cells(c)
                    CurrentCell.Value = CurrentChinaVisa.SortName

                Case 1

                    Dim CurrentCell As DataGridViewComboBoxCell = CType(grdVisa.Rows(r).Cells(c), DataGridViewComboBoxCell)

                    For Each StatusCode As StatusCode In _frmMain.ApplicationStartup.StatusCodes
                        If StatusCode.StatusCodeId >= StatusCodeEnum.WaitingToReceive Then
                            CurrentCell.Items.Add(StatusCode)
                        End If
                        If StatusCode.StatusCodeId = CurrentChinaVisa.StatusCodeId Then
                            CurrentCell.Value = StatusCode
                        End If
                    Next

            End Select

        Next

    Next

End Sub

That seems to work, but when the user selects a new status value from the drop down, the following error is returned:
---------------------------
DataGridView Default Error Dialog
---------------------------
The following exception occurred in the DataGridView:

System.ArgumentException: DataGridViewComboBoxCell value is not valid.

To replace this default dialog please handle the DataError event.
---------------------------
OK
---------------------------

Why?

A: enter code hereDon't add the StatusCode object to the Items collection as shown here:
 CurrentCell.Items.Add(StatusCode)

Add a String and see if it works
CurrentCell.Items.Add(StatusCode.ToString)


text:
Q: Пересоздание массива. Foreach Что-то туплю на ровном месте..
Есть многомерный массив:
var_export($arrays):

array (
    'items' =>
    array (
      0 =>
      array (
        'id' => 5182729,
        'custom_fields' =>
        array (
          0 =>
          array (
            'id' => 175255,
            'values' =>
            array (
              0 =>
              array (
                'value' => '+7 (912) 345-67-89',
              ),
            ),
          ),
      ),
    ),
  ),
)

Мне необходимо пересобрать в массив попроще, вида:
array(500){
    array(2){
        ['id'] => int(5182729)
        ['phone'] => string(18) "+7 (912) 345-67-89"
    }
}

Делаю циклы:
(понимаю, что можно без такого кол-ва foreach, мне так быстрее найти было нужное)
$arrays(); //старый массив
$new_array = array(); //новый массив
foreach ($arrays as $array) {
   foreach ($array as $item) {
       foreach ($item as $i){
           $lead_id = $value['id'];
           $user_phone = $value['custom_fields'][0]['values'][0]['value'];
           $new_array['user']['phone']=preg_replace("/[^0-9]/", "", $user_phone);
           $new_array['user']['lead_id']= $lead_id;
       }
   }
}

На что результат получается с проходом только 1 раз:
array(1) {
  ["user"]=>
  array(2) {
    ["phone"]=>
    string(11) "79123456789"
    ["lead_id"]=>
    int(5182729)
  }
}

Как сделать нормальное заполнение нового массива?

A: я немного подправил ваш код
$new_array = array(); //новый массив
foreach ($arrays as $array) {
   foreach ($array as $item) {
       $lead_id = $item['id'];
       $user_phone = $item['custom_fields'][0]['values'][0]['value'];
       $user_phone = preg_replace("/[^0-9]/", "", $user_phone);
       $new_array[] = ['id' => $lead_id, 'phone'=> user_phone];
   }
}
print_r($new_array);

вот, что получается
Array
(
    [0] => Array
        (
            [id] => 5182729
            [phone] => 79123456789
        )
)

Но я не уверен, что таким образом вы не потеряете какие-то данные

A: $arr = [];
foreach($array['items'] as $key => $value){
    $arr[$key]['user']['id'] = $value['id'];
    $arr[$key]['user']['phone'] = $value['custom_fields'][0]['values'][0]['value'];
}


text:
Q: SAXParser problem with parsing data <message priority="info">PARAMETRI:</message>
<message priority="info">vrednost: 2.0</message>
<message priority="info">rank: 0.75</message>
−
<message priority="info">
objekt: irc.kis.model.pomozniRazredi.CasovniInterval.CasovniInterval(Date, Date)
</message>
<message priority="info">iid_tipa: 3</message>
<message priority="info">iid_metrike: 14</message>
<message priority="info">iid_izracuna: 140</message>
<message priority="info">done in 205776 ms</message>
<message priority="info">---------</message>
<message priority="info">Indeksi kakovosti</message>
<message priority="info">QI01: 3.9249</message>
<message priority="info">QI02: 4.0335</message>
<message priority="info">QI03: 4.0966</message>
<message priority="info">QI04: 4.3823</message>
<message priority="info">---------</message>
<message priority="info">QI05: 3.9401</message>
<message priority="info">QI06: 4.2479</message>
<message priority="info">QI07: 4.4984</message>
<message priority="info">QI08: 4.3534</message>
<message priority="info">QI09: 3.8455</message>
<message priority="info">QI10: 4.0195</message>
<message priority="info">QI11: 4.6222</message>

this is my xml log. Can i with java SAXParser get out just
Indeksi kakovosti
QI01: 3.9249
QI02: 4.0335
QI03: 4.0966
QI04: 4.3823

anything between ----
If yes how?

A: Yes, you can do that (assuming your xml is well-formed). You would have to create a ContentHandler, with a counter instance variable to tell how many of the --------- delimiters you've found so far.
Do not use characters() to do this, because characters() can be called multiple times. Instead buffer the text read using characters(), use endElement() to read the final text and test and increment the counters.
So the ContentHandler would look like:
DefaultHandler hander = new DefaultHander() {
    private String marker = "---------";
    private int markerCount = 0;

    private java.io.CharArrayWriter buffer = new java.io.CharArrayWriter();

    public void characters(char ch[], int start, int length) {
        buffer.append(ch, start, length);
    }

    public void endElement( String namespaceURI, String localName, String qName ) {
        String elementText = buffer.toString();
        if (elementText.startsWith(marker) {
            markerCount += 1;
        }
        else if (markerCount == 1) {
            System.out.println(elementText);
        }
        buffer.reset();
    }
};

A: It must be something like this.
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();

    DefaultHandler handler = new DefaultHandler() {
        boolean indexes;

        public void characters(char ch[], int start, int length)
                throws SAXException {
            String value = new String(ch, start, length);
            boolean changeState = value.startsWith("---");//change this, as you need
            if (!changeState && indexes){
                System.out.println(new String(ch, start, length));
            }
            if(changeState) indexes = !indexes;
        }

    };
    parser.parse(PATH_TO_FILE, handler);

But your document has to be well formed (with root element and without unknown characters like in fourth row).


text:
Q: What happens when you deliver a baby offline? Do I need to be online for it to deliver? If not, does it name itself automatically?
Does anything else happen such as growing up if I am not online?

A: You do have to be online to deliver a baby.
If a baby is about to be born when you're offline, i.e. three hours have passed, it will wait until you open the game again to come out :) You will be able to name him/her at this moment. A baby will never name him/herself automatically.
Considering that growing up essentially just adds the possibility to make a dweller work, what difference does it make if it happens offline?
To explain a bit more, nothing really happens "offline". The game does not continue to run when you do not play (even if push notifications on mobile can make you think so). This is what the game does:

*

*When you close the game, save the state of your dwellers and the current date

*When you're offline, nothing

*When you open the game, compare the current date with the saved date and update the state of your dwellers accordingly

A: You need to be online to deliver the baby.
It takes three hours for a pregnant woman to be ready to give birth. It doesn't matter if you're online or not, that's the minimum time it takes. Once the three hours have taken place, and you've logged back in if you've been away, you get an animation and a baby icon appears above the woman to show she's ready to give birth.
That's how she stays until you click the icon. She could remain pregnant forever if you don't deliver the baby. Once you do that, the child appears and you give it a name.
The child now needs another three hours to grow up. Again, you can be online or offline, it doesn't matter. But there's no icon clicking to do when going from child to adult - so if you deliver a child, then log out for more than three hours, then log back in again, you'll find the child has grown into an unassigned adult dweller.
So, to answer the three questions in your post in order: Yes, No and Yes.


text:
Q: Implications on structure of $B$ when $rank(A-B) = s$ for a fixed $A$ Consider the case where $A \in \mathbb{R}^{n \times K}$ where $n > K$ and $\text{rank}(A) = K$. Suppose we know
$$ \text{rank}(A - B) = s$$ for some $s < K$. What does this say about the relationship between the column space of $B$ and $A$?

A: It says you get $B$ from $A$ (or vice versa) by adding a matrix of rank $s$.  What else do you want it to say?
EDIT: The column space of $A$ has dimension $K = \text{rank}(A)$.  The column space of $B$ could be anything from $K - s$ to $K$.

A: It has failed because:
$\dim (A+(-B)) \ge \dim A$


text:
Q: Pattern matcher para formatear números de teléfono españoles Tengo una lista para números de teléfono móvil validados que debo mostrar de una misma manera:
El formato deseado es: +34 666 111 222

String telefonos =
            "666444555,
             666-444-555,
             666 44 45 55,
             666-44-45-55,
             +34666555444,
             0034666555444";

Pattern pattern = Pattern.compile(""); // aqui es donde me clavo.
Matcher matcher = pattern.matcher(telefonos);

while (matcher.find())
    System.out.println(matcher.group());

Salida esperada:
+34 666 444 555
+34 666 444 555
+34 666 444 555
+34 666 444 555
+34 666 555 444
+34 666 555 444

A: Prueba la siguiente expresión regular:
^(0034|\+34)?(\d\d\d)-? ?(\d\d)-? ?(\d)-? ?(\d)-? ?(\d\d)$

Si planeas utilizar esta expresión de manera frecuente, es recomendable utilizar una constante para evitar recompilar la expresión cada vez, es decir:
private static final Pattern REGEX_PATTERN =
        Pattern.compile("^(0034|\\+34)?(\\d\\d\\d)-? ?(\\d\\d)-? ?(\\d)-? ?(\\d)-? ?(\\d\\d)$", Pattern.MULTILINE);

public static void main(String[] args) {
    String input = "666444555\n666-444-555\n666 44 45 55\n666-44-45-55\n+34666555444\n0034666555444";

    System.out.println(
        REGEX_PATTERN.matcher(input).replaceAll("+34 $2 $3$4 $5$6")
    );
}

Salida:
+34 666 444 555
+34 666 444 555
+34 666 444 555
+34 666 444 555
+34 666 555 444
+34 666 555 444

A: Lo mismo que en la otra pregunta, te recomiendo usar libphonenumber (la librería de Google para validar números telefónicos). Tiene muchas ventajas comparado con hacer tu propia implementación, por ejemplo que no tienes que mantenerlo tú y que te da el número en formato internacional, no importando cómo lo ingrese el usuario.
Un ejemplo de cómo se usa es:
String number = "666444555"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
  PhoneNumber number = phoneUtil.parse(number, "ES");
} catch (NumberParseException e) {
  System.err.println("NumberParseException was thrown: " + e.toString());
}

Ahora hay una serie de métodos pero el más importante sería:
boolean isValid = phoneUtil.isValidNumber(number); // retorna true

Acá siempre vas a poder tener el formato internacional que deseas:
System.out.println(phoneUtil.format(number, PhoneNumberFormat.INTERNATIONAL));

Por supuesto, recomiendo siempre que hagas la pregunta de si es válido o no el número antes de preguntar por su formato internacional.
Para ver un demo puedes ir acá.


text:
Q: Using chemfig for copolymers i.e. polymers and 2 sets of parentheses I'd like to use chemfig for copolymers. I have followed the demo for creating parentheses for polymers, but I've been having trouble figuring out how to get the two middle brackets to line up without increasing the bond length between the O and the C. These 3 attempts show what I've been trying. Each is close, but just not quite right. I would like the O-C spacing of the middle one with the alignment and bracket spacing of the top one and would greatly appreciate suggestions, Thanks!
\documentclass[12pt,twoside,openright]{report}
\usepackage{chemfig}

%For polymer braces - copied from documentation
\newcommand\setpolymerdelim[2]{\def\delimleft{#1}\def\delimright{#2}}\def\makebraces[#1,#2]#3#4#5{%
\edef\delimhalfdim{\the\dimexpr(#1+#2)/2}%
\edef\delimvshift{\the\dimexpr(#1-#2)/2}%
\chemmove{%
    \node[at=(#4),yshift=(\delimvshift)]
    {$\left\delimleft\vrule height\delimhalfdim depth\delimhalfdim width0pt\right.$};%
    \node[at=(#5),yshift=(\delimvshift)]
    {$\left.\vrule height\delimhalfdim depth\delimhalfdim width0pt\right\delimright_{\rlap{$\scriptstyle#3$}}$};}} \setpolymerdelim()

\begin{document}
\chemfig{[:30]-[@{left,.5}]C(=[:90]O)-[:-30]C(-[:90]H)(-[:-90]H)-[:30]C(-[:90]CH_3)-[:-30]O-[@{right,0.5}][@{left2,.5}]-C(=[:90]O)-[:-30]C(-[:90]H)(-[:-90]H)-[:30]C(-[:90]CH_2-CH_3)-[:-30]O-[@{right2,0.5}:30]}
\makebraces[25pt,25pt]{\!\!\!m}{left}{right}
\makebraces[25pt,25pt]{\!\!\!n}{left2}{right2}

\chemfig{[:30]-[@{left,.5}]C(=[:90]O)-[:-30]C(-[:90]H)(-[:-90]H)-[:30]C(-[:90]CH_3)-[:-30]O[@{right,0.4}]-[@{left2,.6}]C(=[:90]O)-[:-30]C(-[:90]H)(-[:-90]H)-[:30]C(-[:90]CH_2-CH3)-[:-30]O-[@{right2,0.5}:30]}
\makebraces[25pt,25pt]{\!\!\!m}{left}{right}
\makebraces[25pt,25pt]{\!\!\!n}{left2}{right2}

\chemfig{[:30]-[@{left,.5}]C(=[:90]O)-[:-30]C(-[:90]H)(-[:-90]H)-[:30]C(-[:90]CH_3)-[:-30]O-[@{right,0.5}]-[@{left2,.5}]C(=[:90]O)-[:-30]C(-[:90]H)(-[:-90]H)-[:30]C(-[:90]CH_2-CH_3)-[:-30]O-[@{right2,0.5}:30]}
\makebraces[25pt,25pt]{\!\!\!m}{left}{right}
\makebraces[25pt,25pt]{\!\!\!n}{left2}{right2}

\end{document}

A: Looks like PHBV! Assuming I'm right, you are missing hydrogens on your third carbons in both HB and HV. Also, the bond angles for the hydrogens on the second carbons aren't right. I took the liberty of adjusting accordingly and cleaning things up a bit.
As for your question, you can modify the \chemmove macro call in the preamble to draw both the right and left parentheses in the same node. Then, another call at the end will manually move the right parenthesis of the second monomer into position.
\documentclass[12pt,twoside,openright]{report}
\usepackage{chemfig}

%For polymer braces - copied from documentation
\newcommand\setpolymerdelim[2]{\def\delimleft{#1}\def\delimright{#2}}\def\makebraces[#1,#2]#3#4#5{%
\edef\delimhalfdim{\the\dimexpr(#1+#2)/2}%
\edef\delimvshift{\the\dimexpr(#1-#2)/2}%
\chemmove{%
    \node[at=(#4),yshift=(\delimvshift)]
    {$\left\delimleft\vrule height\delimhalfdim depth\delimhalfdim width0pt\right.$};%
    \node[at=(#5),yshift=(\delimvshift)]
    {$\left.\vrule height\delimhalfdim depth\delimhalfdim width0pt\right\delimright_{\rlap{$\scriptstyle#3$}}\left\delimleft\vrule height\delimhalfdim depth\delimhalfdim width0pt\right.$};}}
\setpolymerdelim()

\newcommand{\alignC}{C}

\begin{document}

\chemfig{[:30]-[@{left,.5}]C(=[:90]O)-[:-30]CH_{2}-#(6pt,)[:30,,1]CH(-[:90,1]CH_{3})-#(6pt,)[:-30,,1]O-[@{right,0.5}]C(=[:90]O)-[:-30]CH_{2}-#(6pt,)[:30,,1]CH(-[:90,,1,2]H_{2}C-CH_{3})-#(6pt,)[:-30,,1]O-[@{right2,0.5}:30]}
\makebraces[25pt,25pt]{\!\!\!m}{left}{right}
\chemmove{\node[at=(right2),yshift=(\delimvshift)]{$\left.\vrule height\delimhalfdim depth\delimhalfdim width0pt\right\delimright_{\rlap{$\scriptstyle{\!\!\!n}$}}$};}

\end{document}

Edit: Skeletal alternative:
\documentclass[12pt,twoside,openright]{report}
\usepackage{chemfig}

%For polymer braces - copied from documentation
\newcommand\setpolymerdelim[2]{\def\delimleft{#1}\def\delimright{#2}}\def\makebraces[#1,#2]#3#4#5{%
\edef\delimhalfdim{\the\dimexpr(#1+#2)/2}%
\edef\delimvshift{\the\dimexpr(#1-#2)/2}%
\chemmove{%
    \node[at=(#4),yshift=(\delimvshift)]
    {$\left\delimleft\vrule height\delimhalfdim depth\delimhalfdim width0pt\right.$};%
    \node[at=(#5),yshift=(\delimvshift)]
    {$\left.\vrule height\delimhalfdim depth\delimhalfdim width0pt\right\delimright_{\rlap{$\scriptstyle#3$}}\left\delimleft\vrule height\delimhalfdim depth\delimhalfdim width0pt\right.$};}}
\setpolymerdelim()

\newcommand{\alignC}{C}

\begin{document}
    \chemfig{[:30]-[@{left,0.5}]{}(=[:90]O)-[:-30]{}-[:30]{}(-[:90]CH_{3})-[:-30,,1]O-[@{right,0.5}]{}(=[:90]O)-[:-30]{}-[:30]{}(-[:90]{}-CH_{3})-[:-30]O-[@{right2,0.5}:30]}
\makebraces[25pt,25pt]{\!\!\!m}{left}{right}
\chemmove{\node[at=(right2),yshift=(\delimvshift)]{$\left.\vrule height\delimhalfdim depth\delimhalfdim width0pt\right\delimright_{\rlap{$\scriptstyle{\!\!\!n}$}}$};}
\end{document}


text:
Q: I'm getting an attribute error and I do not understand why. Python Here is the error message:
line 68, in isValid
    for symbol in (self.AllValidSymbols):
AttributeError: 'ExpressionEvaluation' object has no attribute 'AllValidSymbols'

I don't understand because in my code (below) I intilized it to have AllValidSymbols set to a list. I'm aware there are more problems with the code I'm just not understanding this error.
    class ExpressionEvaluation():
      stack = stack()
      def __int__(self):
      self.allinfixExpressions = []
      self.infixObj = InfixToPostfix()
      self.operatorList = ['+', '-', '*', '/', '%', '^', '@']
      self.AllValidSymbols = ['(', ')', '{', '}', '[', ']', '+', '-', '*',

      '/', '%','^', '@', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

def getExpressionsFromFile(self, filename):
    self.allinfixExpressions = []
    if (os.path.isfile(filename)):
        infile = open(filename, 'r')
        expr = infile.readline()
        while (expr != ""):#file is not empty
            expr = expr.strip()
            expr = expr.replace(" ", "")#remove spaces
            expr = expr.replace("//", "@")#remove spaces
            expr = expr.replace("**", "^")#remove spaces
            self.allinfixExpressions.append(expr)
            expr = infile.readline()#get next expression
        infile.close()
        return True
    else:
        return False
def doesNotMatch(self, left, right):
    answer = False
    if(left == '(' and right != ')'):
        answer = True
    elif (left == '[' and right != ']'):
        answer = True
    elif (left == '{' and right != '}'):
        answer = True

def isBalanced(self, expr):
    balanced = True
    index = 0
    expr = expr.strip()
    expr = expr.replace(" ", "")
    while(index < len(expr) and balanced):
        symbol = expr[index]
        if(symbol in '([{'):
            self.stack.push(symbol)
        elif (symbol in ')]}'):
            if(self.stack.is_empty()):
                balanced = False
            else:
                item = self.stack.pop()
                if (self.doesNotMatch(item, symbol)):
                    balanced = False
        index += 1
    if(balanced and self.stack.is_empty()):
        return True
    return False

def removeSymbol(self, symbol, exprList):
    n = exprList.count(symbol)
    for i in range(n):
        exprList.remove(elem)
def isValid(self,expr):
    exprList = list(expr)
    for symbol in (self.AllValidSymbols):
        self.removeSymbol(symbol, exprList)
    exprList = list(infixList)
    for elem in tempList:
        if(elem.isdigit()):
            self.removeElement(elem, PostfixList)
    if(postfixList == []):
        return True
    else:
        return False
def evaluateExpressions(self):
   # print(self.allinfixExpressions)
   if (self.allinfixExpressions == []): #empty list
       print("the input list is empty! there is nothing to evaluate.")
   else:
       for expr in self.allinfixExpressions:
           balanced = self.isBalanced(expr)
           valid = self.isValid(expr)
           if (balanced and valid):#good to go
               postfixlist = self.InfixToPostfix(expr)
               postfixExpr = self.getPostfix(postfixlist)
               result = self.evaluatePostfix(postfixlist)
               self.printresult(expr, postfixList)
           else:
               print("not balanced or valid.")

    def main():
     system = ExpressionEvaluation()
     goodFile = system.getExpressionsFromFile('infixexpressions5.txt')
     if(goodFile):
       system.evaluateExpressions()
   main()

A: It's because your initialisation is never run, you have a typo in the __init__ method name.


text:
Q: How do I set context in the response json payload? I have setup a nodeJS server to return responses to a dialogflow webhook. I want to be able to send back a context in the JSON response so that dialogflow logic can move to the next desired Intent in the conversation flow.
In the response payload, I tried inserting "outputContexts" array in order to set the context. However this is not working in this form. The response Json is pasted below. The variable contextName holds the desired value of context to be sent back.
var simpleResponse = {
  "payload": {
    "google": {
      "expectUserResponse": true,
      "outputContexts": [
        {
          "name": "projects/my-agent-v2/agent/sessions/" + sessionId + "/contexts/" + contextName,
          "lifespanCount": 1,
          "parameters": {
            "param": "param value"
          }
        }
      ],
      "richResponse": {
        "items": [
          {
            "simpleResponse": {
              "textToSpeech": "Simple response",
              "displayText": "Simple response"
            }
}]}}}};

The control should move to intent = awaiting_more_details. The above returned context is the "input context" to this intent.
I hope this gives an understanding about what I want to achieve.

A: Your response has the wrong format, the outputContexts array must be in the top level object, next to payload. See Dialogflow's Discovery document for the authoritative specification: https://www.googleapis.com/discovery/v1/apis/dialogflow/v2beta1/rest


text:
Q: (MacOS) Django can't find the MySQL driver ... but, why? Here's the traceback:
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/Users/mike/.virtualenvs/djangoprod/lib/python3.10/site-packages/MySQLdb/__init__.py", line 18, in <module>
    from . import _mysql
ImportError: dlopen(/Users/mike/.virtualenvs/djangoprod/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so, 0x0002): Library not loaded: '@rpath/libmysqlclient.21.dylib'
  Referenced from: '/Users/mike/.virtualenvs/djangoprod/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so'
  Reason: tried: '/usr/lib/libmysqlclient.21.dylib' (no such file)

And here's the problem:
$ locate libmysqlclient
[...]
/usr/local/mysql-8.0.31-macos12-x86_64/lib/libmysqlclient.21.dylib

So, the library is there, but Django isn't finding it.  So, before I "bang my head uselessly against this thing," especially given that it used to work, will someone out there kindly give me a nudge in the right direction? What am I missing here?
I particularly notice that the package is trying the path, /usr/lib... when that is not in fact the proper location here.
In particular: I see in the text a reference to @rpath which I am sure is the root cause of the problem – obviously, the value is wrong. (I notice that it does have the library-name right.)  I'm frankly not familiar with this @rpath thing, nor exactly what sets it.
Thank you kindly in advance ...

A: Sorry to have asked this question so many times ...
It appears that System Integrity Protection (SIP) was the root cause of the problem.  Turning it off caused the library to be found, once it had been added with export DYLD_LIBRARY_PATH ...etc...
Instructions and explanation can be found here: https://developer.apple.com/documentation/security/disabling_and_enabling_system_integrity_protection
According to the Apple Developer website, this causes the value of DYLD_LIBRARY_PATH to be denied to child processes.  And apparently, the Python interface for MySQL must use one somewhere.  (How doing such an odd thing would benefit "system integrity" is quite beyond me, but Apple must have its reasons. ...)
FYI: I also found out from Apple's man dyld page what @RPATH means and where its value comes from.


text:
Q: How to add more nodes to nodes on a NSOutlineView like a directory tree? I would like to get and show the user home directory on a NSOutlineView going deep every time the node is expandable.
So far I can get only the first level and expand it to a second level.
I imagine that it has to be appended to an index or something like that.
I can get level 1 and 2. When i click on the level 2, for example Documents, there is a directory, yourDirectoryName, that has more directories in it. I would like to show the arrow and be able to keep going further on the tree
First pic is my app. Second pic is an example from filezilla

import Cocoa
class Directories {
var name: String
var subDirectories: [String]

init(name: String, subDirectories: [String]) {
    self.name = name
    self.subDirectories = subDirectories
}
}

class ViewController: NSViewController {
var directories = [Directories]()
@IBOutlet weak var outlineView: NSOutlineView!

override func viewDidLoad() {
    super.viewDidLoad()
    getDir(path: "")
    outlineView.dataSource = self
    outlineView.delegate = self
}

func getDir(path: String) {
     let fm = FileManager.default.homeDirectoryForCurrentUser

    do {
        let items = contentsOf(folder: fm)
        for item in items {
            let sub = getSubDir(path: item.lastPathComponent)
            let re = Directories(name: item.lastPathComponent, subDirectories: sub)
            directories.append(re)
        }
    }
}

func contentsOf(folder: URL) -> [URL] {
    let fileManager = FileManager.default
    do {
        let contents = try fileManager.contentsOfDirectory(atPath: folder.path)

        let urls = contents.map { return folder.appendingPathComponent($0) }
        return urls
    } catch {
        return []
    }
}

func getSubDir(path: String) -> [String]{
    var sub = [String]()
    let fm = FileManager.default
    let filePath = NSString(string: path).expandingTildeInPath
    do {
        let items = try fm.contentsOfDirectory(atPath: filePath)
        for item in items {
            sub.append(item)
        }
    } catch {
        // failed to read directory
    }
    return sub
}

override var representedObject: Any? {
    didSet {
        // Update the view, if already loaded.
    }
}
}

extension ViewController: NSOutlineViewDataSource {
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
    if let directories = item as? Directories {
        return directories.subDirectories[index]
    }
    return directories[index]
}

func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
    if let directories = item as? Directories {
        return directories.subDirectories.count > 0
    }
    return false
}

func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
    if let directories = item as? Directories {
        return directories.subDirectories.count
    }
    return directories.count
}
}

extension ViewController: NSOutlineViewDelegate {
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
    var text = ""
    if let directories = item as? Directories {
        text = directories.name
    }
    else {
        text = item as! String
    }

    let tableCell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "cell"), owner: self) as! NSTableCellView
    tableCell.textField!.stringValue = text
    return tableCell
}
}

A: Expanding level 2 to 3 is the same as expanding level 1 to 2. A subdirectory is a directory and has its own subdirectories. The subDirectories property of Directories should be an array of Directories. The directories property of ViewController points to a tree of directories and can be a Directories.
Example:
class ViewController: NSViewController {

    // the rootItem is invisible
    var rootItem = DirectoryItem(url: FileManager.default.homeDirectoryForCurrentUser)

}

extension ViewController: NSOutlineViewDataSource {

    func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
        let directoryItem = item as? DirectoryItem ?? rootItem
        return directoryItem.childItems.count
    }

    func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
        let directoryItem = item as? DirectoryItem ?? rootItem
        return directoryItem.childItems[index]
    }

    func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
        let directoryItem = item as? DirectoryItem ?? rootItem
        return directoryItem.isExpandable
    }

}

extension ViewController: NSOutlineViewDelegate {

    func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
        let directoryItem = item as? DirectoryItem ?? rootItem
        let tableCell = outlineView.makeView(withIdentifier: (tableColumn?.identifier)!, owner: self) as! NSTableCellView
        tableCell.textField!.stringValue = directoryItem.name
        return tableCell
    }

}

class DirectoryItem {

    var name: String
    var url: URL

    lazy var isExpandable: Bool = {
        do {
            return try url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory ?? false
        } catch let error as NSError {
            return false
        }
    }()

    lazy var childItems: [DirectoryItem] = {
        do {
            let urls = try FileManager.default.contentsOfDirectory(at: url,
                    includingPropertiesForKeys: [.isDirectoryKey],
                    options: [.skipsHiddenFiles])
            return urls.map { DirectoryItem(url: $0) }
        } catch let error as NSError {
            return []
        }
    }()

    init(url: URL) {
        self.url = url
        self.name = url.lastPathComponent
    }

}

Disclaimer: I'm used to Objective-C and I'm struggling with Swift.


text:
Q: Eclipse GMF/GEF different Figures I using GEF/GMF and now I tried Eugenia.
I want to create a special model, with special forms.
In an example there are some figures called "ellipse", "rectangle" and "rounded".
These are the only figures I know, I can´t find any list with all the different figures to use.
Do someone knows more figures or a website where I can find a list?
Regards
Dotana

A: OK, I found the solution by myself.
For everyone:
The figures are listed under "org.eclipse.draw2d.geometry".


text:
Q: Best way to add an event to an element without a library or using the onclick attribute? So I want an element i.e: click me to perform a JavaScript function i.e:
functionName();
I want to avoid using the "on" attributes i.e: onclick="".
By cross-browser I mean the A-grade browser compatibility list from YUI

A: var el = document.getElementById("target");
var old = el.onclick;
el.onclick = function() {
  if(old) old();
  functionName();
  // if you want to prevent default action
  // return false;
};

For a more robust solution, see: Dean Edward's addEvent.

A: document.getElementById('target').onclick=function() {
  functionName();
  return false;
}

I assume you meant "without onclick html attribute"

A: Use the getElementById method to find the element, and set it's onclick event:
document.getElementById('target').onclick = functionName;

A: I don't know if this counts as a library, but here are the addEvent() and removeEvent() functions written by John Resig (yes, that John Resig):
function addEvent( obj, type, fn )
{
    if (obj.addEventListener)
    {
        obj.addEventListener( type, fn, false );
    }
    else if (obj.attachEvent)
    {
        obj["e"+type+fn] = fn;
        obj[type+fn] = function() { obj["e"+type+fn]( window.event ); };
        obj.attachEvent( "on"+type, obj[type+fn] );
    }
}

function removeEvent( obj, type, fn )
{
    if (obj.removeEventListener)
    {
        obj.removeEventListener( type, fn, false );
    }
    else if (obj.detachEvent)
    {
        obj.detachEvent( "on"+type, obj[type+fn] );
        obj[type+fn] = null;
        obj["e"+type+fn] = null;
    }
}

Use:
addEvent(document.getElementById('target'), 'click', functionName);
removeEvent(document.getElementById('target'), 'click', functionName);


text:
Q: curious thing happened in linux socket programming I am trying to build a server which can serve for many clients.
The server just do a simple job: get the input string from client and then change each letter to upper case.
But the problem is, when I try to shut down one client, for example, type "Ctrl-C", then my OS will be shut down suddenly.
I use the Ubuntu 10.10 and CentOS to test my program, but always the same problem.
Here's my source code:
/* client.c */
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define MAXLINE 80
#define SERV_PORT 8000

int main (void)
{
    struct  sockaddr_in servaddr, cliaddr;
    char    buf[MAXLINE];
    int sockfd, n;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr);
    servaddr.sin_port = htons(SERV_PORT);

    connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

    while (fgets(buf, MAXLINE, stdin) != NULL) {
        write(sockfd, buf, strlen(buf));
        n = read(sockfd, buf, MAXLINE);
        if(n == 0) printf("Connect closed\n");
        else write(STDOUT_FILENO, buf, n);
    }
    close(sockfd);
    return 0;
}

/* server */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define MAXLINE 80
#define SERV_PORT 8000

void sigchld_func (int signo) {
    wait(NULL);
}

int main (void)
{
    struct  sockaddr_in servaddr, cliaddr;
    char    buf[MAXLINE];
    char    str[INET_ADDRSTRLEN];
    int     listenfd, connfd;
    socklen_t   cliaddr_len;
    int     n, i;
    pid_t   pid;

    signal(SIGCHLD, sigchld_func);

    listenfd = socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(SERV_PORT);

    bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

    listen(listenfd, 20);

    printf("Accepting connections...\n");

    while (1) {
        cliaddr_len = sizeof(cliaddr);
        connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddr_len);
        if ((pid = fork()) < 0) {
            perror("fork error!");
            exit(1);
        } else if (pid > 0) {
            close(connfd);
        } else {
            close(listenfd);
            while (1) {
                n = read(connfd, buf, MAXLINE);
                if (n <= 0) {
                    printf("Connection closed\n");
                    break;
                }
                inet_ntop(AF_INET, &cliaddr.sin_addr, str, sizeof(str));
                printf("Received from %s at port %d\n", str, ntohs(cliaddr.sin_port));
                for (i = 0; i < n; i++)
                    buf[i] = toupper(buf[i]);
                write(connfd, buf, n);
            }
            close(connfd);
        }
    }
    return 0;
}

A: Your server code is causing a fork bomb, and you're not seeing it properly because you're not checking the return value of accept.
The root cause is that in the child that reads/writes to the client, after the connection is closed, you're not either calling exit or returning out of main.
So the child process stays in the toplevel while(1) loop, tries to accept on listenfd (but you closed that one, which is good). accept fails, and you fork regardless. Tight loops of forks will slow down your computer, the scheduler can't deal with them properly (unless you have counter-measures in place).
So exit out of the program after close(connfd), and add more error checking in your code.


text:
Q: Fibonacci Sequence Ruby I have coded the fibonacci sequence on Ruby:
n=40
def fibonacci (n)
    if n == 1
        1
    elsif n == 2
        1
    else
        fibonacci(n-1) + fibonacci(n-2)
    end
end
puts "#{n}'s fibonacci value is #{fibonacci(n)}"

What code do I need to add to allow the user to select which part of the sequence they are looking for eg: n=35? I'm using the MAC terminal to test

A: Ruby can take input from the user in a variety of forms, but the easiest is through ARGV, which encapsualtes the command-line arguments.
First let's clean up the implementation by using Ruby's flexible case statement:
def fibonacci(n)
  case (n)
  when 1,2
    1
  else
      fibonacci(n-1) + fibonacci(n-2)
  end
end

Then feed input from the command-line argument thorugh to the function. Note that command-line input is always strings, so these need to be converted to integers with .to_i:
n = ARGV[0].to_i
puts "#{n}'s fibonacci value is #{fibonacci(n)}"

And then you call it like this:
ruby fib.rb 35
# => 35's fibonacci value is 9227465


text:
Q: ImportError: ERROR: recursion is detected during loading of "cv2" binary extensions. Check OpenCV installation I as making a screen recorder with python and I was using OpenCV with python but its giving this output that I can't find a working answer ANYWHERE and I really need help. I am have only been using python for about a year. Here is the output it gives me:
['C:\\Users\\Diana\\Desktop\\python\\RecScreen', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\pygooglevoice-0.5-py3.10.egg', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\win32', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Diana\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\Pythonwin']
Traceback (most recent call last):
  File "C:\Users\Diana\Desktop\python\RecScreen\RecScreen.py", line 3, in <module>
    import cv2
  File "C:\Users\Diana\AppData\Local\Programs\Python\Python310\lib\cv2\__init__.py", line 180, in <module>
    bootstrap()
  File "C:\Users\Diana\AppData\Local\Programs\Python\Python310\lib\cv2\__init__.py", line 75, in bootstrap
    raise ImportError('ERROR: recursion is detected during loading of "cv2" binary extensions. Check OpenCV installation.')
ImportError: ERROR: recursion is detected during loading of "cv2" binary extensions. Check OpenCV installation.

My code is:
# importing the required packages
import pyautogui
import cv2
import keyboard
import numpy as np

# Specify resolution
resolution = (1920, 1080)

# Specify video codec
codec = cv2.VideoWriter_fourcc(*"XVID")

# Specify name of Output file
filename = "Recording.avi"

# Specify frames rate. We can choose any
# value and experiment with it
fps = 60.0

# Creating a VideoWriter object
out = cv2.VideoWriter(filename, codec, fps, resolution)

cv2.namedWindow("Recording", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Recording", 480, 270)

while True:
    # Take screenshot using PyAutoGUI
    img = pyautogui.screenshot()

    # Convert the screenshot to a numpy array
    frame = np.array(img)

    # Convert it from BGR(Blue, Green, Red) to
    # RGB(Red, Green, Blue)
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    # Write it to the output file
    #out.write(frame)

    # Optional: Display the recording screen
    cv2.imshow('Live', frame)

    # Stop recording when we press 'ctrl+esc'
    if keyboard.is_pressed("Ctrl+esc"):
        break

# Release the Video writer
out.release()

# Destroy all windows
cv2.destroyAllWindows()

I can't figure out how to fix this error. Any help is appreciated.

A: ERROR: recursion is detected during loading of "cv2" binary extensions. Check OpenCV installation
it worked for me
put this in your cmd as you run as admin
pip3 install opencv-python --upgrade --force-reinstall


text:
Q: How to Enable SageMaker Debugger in the SageMaker AutoPilot I'd like to (a) plot SHAP values out of the SageMaker (b) AutoML pipeline. To achieve (a), debugger shall be used according to: https://aws.amazon.com/blogs/machine-learning/ml-explainability-with-amazon-sagemaker-debugger/.
But how to enable the debug model in the AutoPilot without hacking into the background?

A: SageMaker Autopilot doesn't support SageMaker Debugger out of the box currently (as of Dec 2020). You can hack the Hyperparameter Tuning job to pass in a debug parameter.
However, there is a way to use SHAP with Autopilot models. Take a look at this blog post explaining how to use SHAP with SageMaker Autopilot: https://aws.amazon.com/blogs/machine-learning/explaining-amazon-sagemaker-autopilot-models-with-shap/.


text:
Q: How to use different JS output for different pages? Let's say I have two pages which share much code, many libraries etc., but have some differences. For a concrete example, I include jQuery and in each page have different function in "document ready" (aka $(function() { ... })).
With JS that would be easy. I would include jQuery in each page, and have different piece of <script> on each page, or include script-behind-page-A.js in pageA.html, and script-behing-page-B.js in pageB.html.
How shall I achieve the same result with ClojureScript?
I suspect the compilation output is so big that it's best to have one big ball of JavaScript emitted by compiler. In that case, it clearly cannot have two different "document ready" functions.
Is the suggested flow to make the code consist mostly of functions that enable you to do things, few state variables initialized, and initialize each page individually with plain JS as needed?

A: I think the recommended approach would be what is explained in this ClojureScript tutorial by Mimmo Cosenza:

*

*Produce a single, large JS output file (so you optimize/gzip it when this goes live)

*Use different namespaces for the functions, make sure you export at least a single "entry-point function" for each page

*On each HTML file, call the desired "entry point function", like this:
<!-- on the bottom of welcome.html -->
<script src="js/output.js"></script>
<script>myapp.welcome.init();</script>

<!-- on the bottom of login.html -->
<script src="js/output.js"></script>
<script>myapp.login.init();</script>

This is explained on detail on the part 6 of the tutorial.


text:
Q: hiding files with php I can't wrap my head around this, and it is SO frustrating. I have no idea how I'd be solving my problem.
I use sockets to connect with my NodeJS server, and I use PHP for routing people to the correct pages. When I route someone to the admin page I check if he is allowed to continue, if so I'll redirect him, if not I won't. Now here's the issue, people can just go to mywebsite.com/browser/admin.html and read everything that's in the admin panel (just the layout and stuff). I don't want people to be able and visit my admin panel to see what admins can do and can't do.
Can I do this in any way? E.g. only show the admin panel if they have a certain rank; if they don't have that rank they WILL NEVER be able to visit the admin panel. I'd like to hide the html files and other files somehow.
Routing - .htaccess
RewriteEngine on

RewriteRule ^/browser/admin.html$ index.php?page=admin [L,NC,QSA]
RewriteCond %{DOCUMENT_ROOT} !-f
RewriteRule ^(\w+)$ index.php?page=$1 [L,NC,QSA]
RewriteRule ^(\w+)+\/$ index.php?page=$1 [L,NC,QSA]

Routing - index.php
function route(){
    global $db;
    global $user;

    $page = $_GET['page'];

    if(!isset($page)) {
        header('Location: /home');
    }

    if($page === 'home'){
        loadWebpage('index.html', array());
    }else if($page === 'admin'){
        if($user['rank'] !== 'admin'){ /* This works but people can still access the files since they are loaded on the frontend with myexample.com/browser/admin.html */
            echo 'Access denied.';
            return;
        }

        loadWebpage('admin.html', array())
    }
}

route();

I'm sorry if I haven't explained it well, but I hope you understand what I mean; I find it difficult to explain the things I want. I appreciate the help.

A: I believe there are plenty of ways to go about what you're trying to achieve, but I'll just explain one way of "access-protecting" a certain file.
Create a file in your directory, admin.php. Here, just have some basic code like this:
<?php
$accessKey = $_POST['accessKey'];
if ($accessKey == "MyVeryAwesomeAccessKeyThatNobodyKnows") //Change this to whatever you want
{
?>
    This info will only be shown if you're an admin!
<?php
}
else
    echo("Invalid access key.
");
?>

This code basically checks if the correct access key was sent in, and only if it was, will it load your protected file.
And then, wherever you have to access the admin page, you can put a form or something there like this:
<form method="POST" action="admin.php">
    <input name="accessKey" type="password" />
    <input type="submit" value="Load Admin Site" />
</form>

The user has to enter in the administrator access key to be granted permission into the protected information page. This way is a bit hackish, but it gets the job done!


text:
Q: How to change the padding of Radio or RadioListTile in flutter? I am trying to do some ui customization, but I don't figure out how to reduce the padding of a Radio or RadioList in Flutter.
Can we do it ?

A: If you are using Radio, add property
visualDensity: VisualDensity(horizontal: x, vertical: y),

Where -4 <= x <= 4, and -4 <= y <= 4

A: If you are using RadioListTile then set dense to true.
If it's a Radio then materialTapTargetSize: MaterialTapTargetSize.shrinkWrap will reduce the size.
Otherwise, make your own.

A: set these Radio properties:
visualDensity: const VisualDensity(
  horizontal: VisualDensity.minimumDensity,
  vertical: VisualDensity.minimumDensity,
),

and
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,

A: this worked great for me...
RadioListTile(
  title: Transform.translate(
           offset: const Offset(-12, 0),
           child: Text(Text'),
         ),
         value: ...
),

A: Wrap the Radio widget in a SizedBox this allows you to control the padding around the Radio widget.
SizedBox(
    width: 20,
    height: 20,
    child: Radio(
         value: true,
         groupValue: _isSubscription,
         onChanged: (_) {
             setState(() {
                _isSubscription = true;
             });
         },
         // this no longer has any effect on the size
         materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
         ),
    ),


text:
Q: How to change data in the container while iterating in python Given the following example:
container = [ (1, "a") ,
              (40, "b") ,
              (24, "c") ,  #we intend to change this
              (103, "d")
            ]

for k,v in container:
    if k == 24:
        v += " good"

print container

The (24, "c") data pair in container will still remain its original value,
and won't be changed to (24, "c good"). What would be the way to alter it to (24, "c good") as intended during the iteration?
I use python 2.7 , but 3.x examples are also welcome.
Thanks.

A: You can use enumerate() the keep track of the index of the container item you are looking at:
for i, (k,v) in enumerate(container):
    if k == 24:
        container[i] = (k, v+" good")

A: Messed up a bit. Fixed now
container = [ (1, "a") ,
                  (40, "b") ,
                  (24, "c") ,  #we intend to change this
                  (103, "d")
                ]

for k, n in enumerate(container):
    if n[0] == 24:
        container[k] = (n[0], n[1] + " good")

print container


text:
Q: 404 page after changing hyperlinks configuration I do not know why i change the configuration of my permalinks from
POSTNAME :http://c51.444.myftpupload.com/sample-post/ to
PLAIN: http://c51.444.myftpupload.com/?p=123
but now i want to change to the previous config but i got a 404 page not found error.

I have researched thru internet and they suggest to modify the permissions of the htaccess file to 666 which I have done already, some just say to go the permalinks options on WP and then click on save button but this did not solve my issue too.
I'm kinda thinking that the real solution is in the htaccess but I really do not know what would be the exact config to use. Here it is my htaccess:
#BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress

Here is it the staging site where my site is running now: http://c51.444.myftpupload.com/
Thanks in advance for your help
*FYI I got to say that before posting this thread I follow related topics here on stackoverflow but those suggestions I have tried already. I am not sure what exactly to do. Thanks in advance ok


text:
Q: Select this element in anchor in bootstrap using jQuery

Test2.docx

I want to select the button using jQuery. I 've tried a lot of  times, some of the samples are like:
$("#listOfAttachments > li > a > i")
$("#listOfAttachments > li > a > .fa .fa-close blue")

none of them works, some one can help me out?

A: I want to select the button using jQuery: (Remove the i tag from the selector)
$("#listOfAttachments > li > a[role='button']")

Fiddle: http://jsfiddle.net/c5pxaa8p/


text:
Q: How to write this integral in terms of Gamma functions $\int_0^1 dx \ x^{\alpha n}(1-x)^{\beta n} = \frac{\Gamma(\alpha n +1)\Gamma(\beta n +1)}{\Gamma(\alpha n + \beta n + 2)}$ for Re($\alpha$n) > -$1$ and Re($\beta$n) > -$1$.
I want to manipulate the left side in order to arrive at the result on the right but I fail to make it work. Reparametrizations to write an integral in form of a Gamma function are clear to me but how do I end up with three different ones? Thanks in advance for any help!

A: The Beta function is defined
$$
B(x,y)=\int_0^1 t^{x-1} (1-t)^{y-1}dt=\frac{\Gamma (x)\Gamma (y)}{\Gamma (x+y)}
$$
In your case $x=1+\alpha m$ and $y=1+\beta n$ which gives the result you are seeking.


text:
Q: How do I add "No results" item to my autocomplete? If my jQuery autocomplete request returns empty, I want to add "No results" to the drop down list. But how exactly do I do  this?
I have removed stuff to shorten / make the code simpler in this example:
$(element).autocomplete({
    source: function (request, response) {
        $.ajax({
            success: function (data) {
                response(data);
            }
        });
    },
    response: function(e, ui){
        if (ui.content.length === 0) {
         // Could I do something here?
        }
    },
    select: function(e, ui){
        // Do stuff here
        return false;
    }
// This is not triggered if DB returns empty
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
    return jQuery( "

" )
      .data( "ui-autocomplete-item", item )
      .append( ""+ item.name + "" )
      .appendTo( ul );
}

A: In your response object, add the following:
response: function(event, ui) {
    if (!ui.content.length) {
        var noResult = {
             value: "",
             label: "No results found"
         };
         ui.content.push(noResult);
     } else {
        $("#message").empty();
     }
},

JSFiddle


text:
Q: SharePoint 2013 Task Sync with Exchange 2013 CAS Cluster We have a question regarding SharePoint task synch with Exchange (CAS with NLB - CAS cluster).
NLB - Round-Robin DNS.
In MySites task list user can select "Sync to Outlook". We found this article http://technet.microsoft.com/en-us/library/jj649094%28v=exchg.150%29.aspx but it doesn't say on which servers do we have to run this ps1 script if we have a CAS Cluster (2 CAS, 4MBX).
We think that we have to run this script on both CAS servers.
Another question: Which URL will be used for synchronization when user selects to synch tasks? I couldn't find any information on this.
Thank you for all the help.
Ales


text:
Q: Masking a url with a url shortener I need to mask number of URLs with a short URL link that does not reveal location of the web page in the address bar.
Example:
mywebsite.com/content-123
Masked URL:
surl.us/ae12sw
Clarification: I am not looking for redirects like traditional URL shorteners (bit.ly) that would redirect user to long URL. I need the short URL to remain in the address bar masking the actual URL.  But the page would display the content from original website.

A: Not sure if this will help but maybe try adding something like this to the JavaScript of each page
    history.pushState("mywebsite.com/content-123", "Example Site", "surl.us/ae12sw");


text:
Q: Connect to web application protected by GlobalProtect with custom HTTP requests Our company CRM web application does not have an API and therefore is extremely cumbersome to use when having to upload data as this all has to be done manually and through the GUI. To access this application you need to be identified in GlobalProtect. My idea was to use http requests sent directly to the server to try to circumvent the lack of an API.
However, i have been very unsuccesful as copying http request out of the chrome devtools and changing their payloads using Postman resulst in an ECONN_RESET error. I am no networking expert, but i believe this error has to do with the fact that the application is protected by GLobalProtect and there is more communication necessary with the server to make it accept my modified http requests.
Is there anyone with knowledge about networking and GlobalProtect that could point me in the right direction towards setting up a direct communication with the server? Thanks so much!


text:
Q: How to "reuse" randomly generated passwords in Helm and ArgoCD? I'm using ArgoCD to manage my app deployments. My apps are Helm charts and I'm using "randAlphaNum" to generate a random password. Unfortunately a new password is generated each time I'm syncing my app. So I was trying to use something like this:
apiVersion: v1
kind: Secret
metadata:
  name: mypass
type: Opaque
stringData:
{{ if .Release.IsInstall }}
  pw: {{ randAlphaNum 32 | quote }}
{{ end }}

But when I check the "App Diff", I see that ArgoCD also updates the "pw". So I tried using the "lookup" function of Helm instead but I finally figured out that it's not supported by ArgoCD atm (see https://github.com/argoproj/argo-cd/issues/5202). So I wonder if there's any other solution I can use or if there's a list of supported Helm functions in ArgoCD?!

A: Maybe an alternative way of generating passwords can help - try Kubernetes Secret Generator.
I've used this example to generate an auth secret for the chart bitnami/postgresql:
apiVersion: secretgenerator.mittwald.de/v1alpha1
kind: StringSecret
metadata:
  name: postgresql-auth-secret
spec:
  forceRegenerate: false
  fields:
    - fieldName: "password"
      encoding: "base64"
      length: "30"
    - fieldName: "postgres-password"
      encoding: "base64"
      length: "30"

It seems to work well with ArgoCD too.

A: If you are looking to generate a value on the initial install and then never change it again, you should be able to leverage the pre-install hook to make sure that it is only ever used that first time:
apiVersion: v1
kind: Secret
metadata:
  name: mypass
  annotations:
    "helm.sh/hook": "pre-install"
    "helm.sh/hook-delete-policy": "before-hook-creation"
type: Opaque
stringData:
  pw: {{ randAlphaNum 32 | quote }}

One caveat here is that by using a hook the resource will no longer be managed by Helm, so running helm uninstall would leave the secret behind, but the delete policy will make sure you don't get a collision on the next run.


text:
Q: Wired GFCI vs. 40v 5a battery use near spa My wife has recently taken to running a cord out near our pool to watch TV.  She's very careful, but I was thinking of doing what I can to make it safer, since the outlet in question is NOT a GFCI outlet (It's a standard US 110v outlet).
One obvious solution is an inline GFCI.
The other more expensive idea that occurred to me is using a 5ah 40v lithium battery that I can purchase a 300w inverter for.
My guess here is that if the wired TV were to go into the water, a GFCI would be better than nothing, but unsafe...whereas the battery would be practically speaking likely to be completely safe.  Can anyone enlighten me as to which approach would be the safest, and if either or both is actually "safe"?

A:
My guess here is that if the wired TV were to go into the water, a GFCI would be better than nothing, but unsafe...whereas the battery would be practically speaking likely to be completely safe.

120v from an inverter is still 120v.  If that goes into the pool, you could be injured or killed.  Nothing about that is safe.
The whole idea of a GFCI is that if you drop something into a body of water, the voltage is interrupted once a few mA starts to flow, generally fast enough that you won't be injured.


text:
Q: Spring Boot cache doesn't work I trying to configure spring cache, but the method is executed still. I have the below code, and the civilStatus cache is not working. The method getCivilStatus() is executed always. Does Anybody know the reason?
@Configuration
@EnableCaching
public class ApplicationConfig {

@Autowired
private SocioDemographicInfoService socioDemographicInfo;

@Bean
public CacheManager cacheManager() {
    SimpleCacheManager cacheManager = new SimpleCacheManager();
    cacheManager.setCaches(Arrays.asList(
            new ConcurrentMapCache("civilStatus");

    return cacheManager;
}
}

@Service
public class SocioDemographicInfoService {

@Cacheable(value="civilStatus")
public Map<String, String> getCivilStatus(){
    log.info("Retrieving civilStatus");
    Map<String, String> civilStatus = new HashMap<String, String>();
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";
    try {
        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(classLoader.getResource("CatalogoEstadoCivil.csv").getFile());
        br = new BufferedReader(new FileReader(file));
        while ((line = br.readLine()) != null) {
            String[] cod = line.split(cvsSplitBy);
            civilStatus.put(cod[0].trim(), cod[1]);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return civilStatus;
}
}

}

A: I believe you are using spring boot and setting up a server using a class something like this (given below). Add EnableCaching annotation on the same class and define CacheManager as given below, instead of a separate configuration class. That will make sure caching is enabled before your class get initialized.
@Configuration
@EnableAutoConfiguration
@ComponentScan
@EnableCaching
@PropertySource(ignoreResourceNotFound = true, value = {"classpath:application.properties"})
@ImportResource(value = { "classpath*:spring/*.xml" })
public class MyBootServer{

public static void main(String args[]){
    ApplicationContext ctx = SpringApplication.run(MyBootServer.class, args);
}

@Bean(name="cacheManager")
public CacheManager getCacheManager() {
...// Your code
}
}

Nothing wrong in your over all code. I tested your configuration in my spring boot sample code and it works

A: You don't need the AOP and caching complexity your usecase is a lot simpler. Just create a method that loads the file at startup and let your getCivilStatus return that map. A lot simpler.
@Service
public class SocioDemographicInfoService implements ResourceLoaderAware {

    private final Map<String, String> civilStatus = new HashMap<String, String>();

    private ResourceLoader loader;

    @PostConstruct
    public void init() {
        log.info("Retrieving civilStatus");
        Map<String, String> civilStatus = new HashMap<String, String>();
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = ",";
        Resource input = loader.getResource("classpath:CatalogoEstadoCivil.csv"));
        if (input.isReadable() ) {
            File file = input.getFile();
            br = new BufferedReader(new FileReader(file));
            try {
                while ((line = br.readLine()) != null) {
                    String[] cod = line.split(cvsSplitBy);
                    civilStatus.put(cod[0].trim(), cod[1]);
                }
            } catch (IOException e) {
                logger.error("Error reading file", e_;
            } finally {
                if (br != null) {
                    try { br.close() } catch( IOException e) {}
                }
            }
        }
    }

    public Map<String, String> getCivilStatus() {
        return this.civilStatus;
    }

    public void setResourceLoader(ResourceLoader loader) {
        this.loader=loader;
    }

}

Something like this should work. It loads your after the bean is constructed (this code can probably be optimized by using something like commons-io). Note I used Springs ResourceLoader to load the file.


text:
Q: Magento : Show same product as separate in cart I have products with different custom options. When a same product with same custom options is added to cart twice, it appears in the cart as 2 X qty
Please refer the image

I want to display it as separate product. Please refer the below image.

How can I do it. Please help.

A: Try this:
Copy the file app/code/core/Mage/Sales/Model/Quote/Item.php to app/code/local/Mage/Sales/Model/Quote/Item.php
Set the return as false in function representProduct()

A: Magento shows product with different options separately. You need to add an additional option programmatically using observer.
Go through below link to do the same.
https://docs.google.com/presentation/d/1efPznQSVTrT1HAD1xQvCPC-Tgvr8jYok4X7ZEJhm9jE/edit#slide=id.gd03b59c1_026


text:
Q: implementation of object level raw permissions inside microservice architecture I have a bunch of microservices running. I have an api gateway that connect consumers to all these services. Now on some services I need to give permission to certain users ( users are stored in separate Users Service ). For example if I have a blog service I need to give blog 1, blog 2 and blog 3 view permissions only to user 1 and not to user 2 ( the scenario is acl rather than RBAC or ABAC i think, correct me if i am worng ). Now how should i implement the permission system.
For example If store the permission on each entity object inside each microservice as suggested here then each of my service has to know about users also to grant them permissions. this scenario will compel me to synchronize the users data across all microservices ( on users delete update ... ).
Another Solution is to create a separate generic authorization service to manage all services permissions. but this solution will require me to save each microservice schema ( and have to synchronize that schema on change )
Or there is any other solution. please help. how to implement ACL (authorization)

A: One solution would be to introduce userID into the downstream path from the gateway. So the path
GET /blogs/{blogId}

is exposed on the gateway, but this becomes
GET /blogs/{userId}/{blogId}

on the blogs microservice. The gateway handles the user's bearer token and injects the user's ID into the downstrteam call. The blogs microservice would then return the blog for a "valid" path, or a 404 if the path was not valid.
This is illustrated here:

the backend service maintains which users have access to which blogs?

The blog microservice stores and manages blogs. A blog can have an access list associated with it. That list may contain only the user who is the blog owner, or more than one user. The point is that the ACL is not centralised, but distributed with each blog's data containing it.

if a user is deleted

Then you have two choices. If the user is deleted you publish a UserDeleted event, to which the blogs service is subscribed. Then you can manage all the blogs which have the user in their ACL and remove them. Or, you can do nothing. I would personally choose the latter; one of the features of having a microservice architecture is that some data will not be consistent. If you require absolute consistency then you can have a "caretaker" process which removes deleted users out of blog ACLs. Or don't use microservices.


text:
Q: SimpleDB: how store items in an xml file? I need to retrieve all items in the SimpleDB domain from java application. So, I used the select method, but I don't know is there an easy way to store the retrieved values in an xml file?? or I've to create the attributes and elements by myself and set values to them, like this:
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("Items");
        doc.appendChild(rootElement);

    SelectRequest selectRequest = new SelectRequest(selectExpression);

        for (Item item : sdb.select(selectRequest).getItems()) {
            //  <item>-------------------
            itemBeg = doc.createElement("Item");
            rootElement.appendChild(itemBeg);
                //  <Name>-------------------
                Elmname = doc.createAttribute("Name");
                Elmname.setValue(item.getName());
                itemBeg.setAttributeNode(Elmname);
                  //  <Attributes> -----------------
                attrib = doc.createElement("Attributes");
                itemBeg.appendChild(attrib);

             for (Attribute attribute : item.getAttributes()) {
                //  attribute <Name> -----------------
                 attrName = doc.createAttribute("Name");
                attrName.setValue(attribute.getName());
                attrib.setAttributeNode(attrName);
                 //  attribute <Value> -------------------
                    attrValue = doc.createAttribute("Value");
                attrValue.setValue(attribute.getValue());
                attrib.setAttributeNode(attrValue);
            }


text:
Q: Spring data dynamically remove field from PATCH I am trying to protect specific entity/document fields from being updated by unauthorized users. What i have so far:
I created an annotation "UpdateableByAdmin", that i put on the fields that need protection, and listen to the before save event.
Then i check if the user has the needed role, and if not then set the fields to null.
And here is my problem, that setting the field of the object to null just sets those fields in the database to null. Is there a way to just not include these specified fields in the update?
import org.springframework.data.rest.core.annotation.HandleBeforeSave;
import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
import org.springframework.stereotype.Component;

@RepositoryEventHandler(Object.class)
@Component
public class MongoEventHandler {
    private final EntityFieldDefender fieldDefender;

    public MongoEventHandler(EntityFieldDefender fieldDefender) {
        this.fieldDefender = fieldDefender;
    }

    @HandleBeforeSave
    public void handleUserBeforeSave(Object object) {
        System.out.println("in handlebeforesave");
        this.fieldDefender.filterSecuredFields(object);
        System.out.println(object);
    }
}

import java.lang.reflect.Field;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import com...ERole;
import com...AuthToken;
import com...UpdateableByAdmin;

@Component
public class EntityFieldDefender {
    public void filterSecuredFields(Object entity) {
        final AuthToken auth = (AuthToken) SecurityContextHolder.getContext().getAuthentication();
        if (!auth.getRoleNames().contains(ERole.ROLE_ADMIN) && !auth.getRoleNames().contains(ERole.ROLE_SUPERADMIN)) {
            for (final Field field : entity.getClass().getDeclaredFields()) {
                if (field.isAnnotationPresent(UpdateableByAdmin.class)) {
                    try {
                        field.setAccessible(true);
                        field.set(entity, null);
                        field.setAccessible(false);
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }
}

Another solution would be to intercept the request and set the body directly, but that doesn't seem too pretty.
Yet another solution would be to load the old object and replace the value, but if there was a way to avoid a useless db call, then that would be nice.


text:
Q: Google calendar API. Modifications loss when simultaneously patching event I have firebase function that processes webhook.
This function updates calendar event, updating of single event may be simultaneously.
I use Etag and If-Match header for prevent modification loss as described in doc.
But I still loss all changes except the last.
This code does multiple simultaneous updates with same event.
In result summary must be '10' but actually it is '2'.
What is wrong with it?
Code
const calendarId = 'calendarid';
const scopes = [
  "https://www.googleapis.com/auth/calendar",
  "https://www.googleapis.com/auth/calendar.events",
];
const auth = new google.auth.GoogleAuth({ scopes });
const calendar = google.calendar({ version: "v3", auth });

...

const reproduce = async () => {
  const {id: eventId} = await calendar.events.insert({
    auth,
    calendarId,
    resource: {
      summary: '1',
      // some another resource data
    },
  });

  const update = async () => {
    const event = await calendar.events.get({
      auth,
      calendarId,
      eventId,
    });

    console.log("***BEFORE***");
    console.log("summary: " + event.summary);
    console.log("etag: " + event.etag);

    const previousSummary = event.summary;
    const newSummary = parseInt(previousSummary) + 1;

    const res = await calendar.events.patch({
      auth,
      calendarId,
      eventId,
      resource: {summary: newSummary.toString()},
    }, {
      headers: {
        "If-Match": event.data.etag
      }
    });

    console.log("***AFTER***");
    console.log("summary: " + res.data.summary);
    console.log("etag: " + res.data.etag);
  }

  let i = 0;
  // simultaneously updates event
  while (i++ < 10) {
    update();
  }
}

Output
>  ***BEFORE***
>  summary: 1
>  etag: "3235006977030000"
>  ***BEFORE***
>  summary: 1
>  etag: "3235006977030000"
>  ***BEFORE***
>  summary: 1
>  etag: "3235006977030000"
>  ***BEFORE***
>  summary: 1
>  etag: "3235006977030000"
>  ***BEFORE***
>  summary: 1
>  etag: "3235006977030000"
>  ***BEFORE***
>  summary: 1
>  etag: "3235006977030000"
>  ***BEFORE***
>  summary: 1
>  etag: "3235006977030000"
>  ***BEFORE***
>  summary: 1
>  etag: "3235006977030000"
>  ***BEFORE***
>  summary: 1
>  etag: "3235006977030000"
>  ***AFTER***
>  summary: 2
>  etag: "3235006998028000"
>  Event updated successfully
>  ***AFTER***
>  summary: 2
>  etag: "3235007000852000"
>  Event updated successfully
>  ***AFTER***
>  summary: 2
>  etag: "3235007002822000"
>  Event updated successfully
>  ***AFTER***
>  summary: 2
>  etag: "3235007003202000"
>  Event updated successfully
>  ***AFTER***
>  summary: 2
>  etag: "3235007004826000"
>  Event updated successfully
>  ***AFTER***
>  summary: 2
>  etag: "3235007009742000"
>  Event updated successfully
>  ***AFTER***
>  summary: 2
>  etag: "3235007011058000"
>  Event updated successfully
>  ***AFTER***
>  summary: 2
>  etag: "3235007014902000"
>  Event updated successfully
>  ***AFTER***
>  summary: 2
>  etag: "3235007018050000"
>  Event updated successfully

A: I was able to reproduce your issue using Javascript in Apps Script.
The reason why you were able to update your event once (which makes your summary "2") is because of your async/await command in update().
Sample Code:
 const update =  async () => {
    const event =  await Calendar.Events.get(
      calendarId,
      eventId,
    );

    Logger.log("***BEFORE***");
    Logger.log("summary: "+event.summary);
    Logger.log("etag: "+event.etag);
    const previousSummary = event.summary;
    const newSummary = parseInt(previousSummary) + 1;

    const res =  await Calendar.Events.patch(
      {summary: newSummary.toString()},
      calendarId,
      event.id,
      { "If-Match": event.etag }
     );

    Logger.log("***AFTER***");
    Logger.log("summary: "+res.summary);
    Logger.log("etag: "+res.etag);
    //Logger.log(res);
  }

let i = 0;
// simultaneously updates event
while (i++ < 10) {
  update();
}

Output:
12:04:47 AM Notice  Execution started
12:04:51 AM Info    ***BEFORE***
12:04:51 AM Info    summary: 1
12:04:51 AM Info    etag: "3234758978180000"
12:04:51 AM Info    ***BEFORE***
12:04:51 AM Info    summary: 1
12:04:51 AM Info    etag: "3234758978180000"
12:04:52 AM Info    ***BEFORE***
12:04:52 AM Info    summary: 1
12:04:52 AM Info    etag: "3234758978180000"
12:04:52 AM Info    ***BEFORE***
12:04:52 AM Info    summary: 1
12:04:52 AM Info    etag: "3234758978180000"
12:04:52 AM Info    ***BEFORE***
12:04:52 AM Info    summary: 1
12:04:52 AM Info    etag: "3234758978180000"
12:04:53 AM Info    ***BEFORE***
12:04:53 AM Info    summary: 1
12:04:53 AM Info    etag: "3234758978180000"
12:04:53 AM Info    ***BEFORE***
12:04:53 AM Info    summary: 1
12:04:53 AM Info    etag: "3234758978180000"
12:04:53 AM Info    ***BEFORE***
12:04:53 AM Info    summary: 1
12:04:53 AM Info    etag: "3234758978180000"
12:04:54 AM Info    ***BEFORE***
12:04:54 AM Info    summary: 1
12:04:54 AM Info    etag: "3234758978180000"
12:04:54 AM Info    ***BEFORE***
12:04:54 AM Info    summary: 1
12:04:54 AM Info    etag: "3234758978180000"
12:04:54 AM Info    ***AFTER***
12:04:54 AM Info    summary: 2
12:04:54 AM Info    etag: "3234758983260000"
12:04:54 AM Info    ***AFTER***
12:04:54 AM Info    summary: 2
12:04:54 AM Info    etag: "3234758983260000"
12:04:54 AM Info    ***AFTER***
12:04:54 AM Info    summary: 2
12:04:54 AM Info    etag: "3234758983260000"
12:04:54 AM Info    ***AFTER***
12:04:54 AM Info    summary: 2
12:04:54 AM Info    etag: "3234758983260000"
12:04:54 AM Info    ***AFTER***
12:04:54 AM Info    summary: 2
12:04:54 AM Info    etag: "3234758983260000"
12:04:54 AM Info    ***AFTER***
12:04:54 AM Info    summary: 2
12:04:54 AM Info    etag: "3234758983260000"
12:04:54 AM Info    ***AFTER***
12:04:54 AM Info    summary: 2
12:04:54 AM Info    etag: "3234758983260000"
12:04:54 AM Info    ***AFTER***
12:04:54 AM Info    summary: 2
12:04:54 AM Info    etag: "3234758983260000"
12:04:54 AM Info    ***AFTER***
12:04:54 AM Info    summary: 2
12:04:54 AM Info    etag: "3234758983260000"
12:04:54 AM Info    ***AFTER***
12:04:54 AM Info    summary: 2
12:04:54 AM Info    etag: "3234758983260000"
12:04:54 AM Notice  Execution completed

*

*Notice that Calendar.Events.get() method was executed 10 times before Calendar.Events.patch() was executed. Hence you were able to patch your event once.

*I'm not that expert when it comes to Javascript Promises but you might want to remove your async/await in your update(), get() and patch().


text:
Q: Haskell: writing an function to add Ints and Chars which are mapped by a function to Ints The code bellow works pretty well for input like this:
*Main> eval 'y' (21 :: Int)
42
*Main> eval 'x' 'a'
42
*Main> eval (21 :: Int) (21 :: Int)
42
*Main> eval (42 :: Int) 'a'
42

The general problem behind this is that I want to add two things. Adding to Ints is not hard to realize (it's already built in). But I've a given function (here geti) which resolves Chars to Ints and my add-function now should add two Ints as well as Int combined with Char (in every permutation). The Chars are converted by the geti function to Ints so that they can be added. I've thought about an other solution which might be:
eval (geti 'a') (42 :: Int)

but that is not possible for me.
So in general my question is: is there any way to make this simpler or implement it more elegant?
This is the code:
-- A static function only used to resolve some demo data
geti :: Char -> Int
geti c | c == 'x' = 42
       | c == 'y' = 21
       | c == 'z' = 10
       | otherwise = 0

-- Here comes the problem:
class Eval t1 t2 where
    eval :: t1 -> t2 -> Int

instance Eval Int Int where
    eval a b = a + b

instance Eval Int Char where
    eval a c = a + (geti c)

instance Eval Char Int where
    eval c b = (geti c) + b

instance Eval Char Char where
    eval c1 c2 = (geti c1) + (geti c2)

P.S.: I've also tried to combine the solution from here with an "generic" (yes, it's Java language, but I'm new to Haskell ... sry) function but that didn't work ...

A: I think it would be more straight forward to build a type class for "can be converted to Int" and use that to implement eval:
class Intable a where
   intify :: a -> Int

instance Intable Int where
   intify = id

instance Intable Char where
   intify = geti

eval :: (Intable a, Intable b) => a -> b -> Int
eval a b = intify a + intify b


text:
Q: matplotlib hatched contourf visibility depends on pdf reader I'm struggling with the pdf backend of matplotlib and the contourf function. I try to plot forbidden areas on a 2D colored map. The forbidden areas are represented by hatched contourf with transparent (alpha=0.4) black color. the used code is given below, with two classes written to generate a user defined legend:
import matplotlib
print matplotlib.__version__
import matplotlib.patches as mpatches

class ConstrainedArea(object):
   def __init__(self,axe,_xdata,_ydata,_zdata,boundaries,fc='none',ec='none',lw=None,alpha=None,hatch='//',ls='-',fill=False,label=None):
      self.bnd = boundaries
      self.fc  = fc
      self.ec  = ec
      self.lw  = lw
      self.ls  = ls
      self.al  = alpha
      self.hh  = hatch
      self.fl  = fill
      self.lb = label
      self.ctr = axe.contour(_xdata,_ydata,_zdata,boundaries,linewidths=lw,colors=ec,linestyles=ls)
      #self.ctf = axe.contourf(_xdata,_ydata,_zdata,boundaries,hatches=hatch,colors=fc,facecolors=fc,alpha=alpha)
      self.ctf = axe.contourf(_xdata,_ydata,_zdata,boundaries,hatches=hatch,colors=fc,alpha=alpha,antialiased=False)
   pass
class ConstrainedAreaHandler(object):
   def legend_artist(self,legend,orig_handle,fontsize,handlebox):
      x0,y0 = handlebox.xdescent,handlebox.ydescent
      wi,he = handlebox.width,handlebox.height
      patch = mpatches.Rectangle([x0,y0],wi,he,facecolor=orig_handle.fc,edgecolor=orig_handle.ec,hatch=orig_handle.hh,lw=orig_handle.lw,ls=orig_handle.ls,fill=orig_handle.fl,transform=handlebox.get_transform(),label=orig_handle.lb)
      handlebox.add_artist(patch)

if __name__ == "__main__":
   matplotlib.rcParams['backend'] = 'PDF'
   import numpy,matplotlib.pyplot as plt

   xs, ys = numpy.mgrid[0:30, 0:40]
   zs = (xs - 15) ** 2 + (ys - 20) ** 2 + (numpy.sin(ys) + 10) ** 2

   fig = plt.figure('test',figsize=(16.0,11.8875))
   axe = fig.add_subplot(111)
   pcm = axe.pcolormesh(xs,ys,zs,shading='gouraud')
   cas = []
   for bnd,hch,ls,lb in zip([[zs.min(),200],[400,zs.max()]],['/','\\'],['-','--'],[r'$f<200$',r'$f>400$']):
      cas.append(ConstrainedArea(axe,xs,ys,zs,bnd,hatch=hch,fc='k',ec='k',lw=3,ls=ls,alpha=0.2,fill=False,label=lb))
   cbr = fig.colorbar(pcm)
   legframe = axe.legend(cas,[c.lb for c in cas],loc=3,handler_map={ConstrainedArea:ConstrainedAreaHandler()},ncol=3,fontsize=matplotlib.rcParams['font.size']*1.2**4,numpoints=1,framealpha=0.8)
   #fig.savefig('test.pdf',bbox_inches='tight',facecolor='none',edgecolor='none',transparent=True)
   fig.savefig('test.pdf',bbox_inches='tight',transparent=True)

After reading the tracks on matplotlib issues
GitHub matplotlib issue 3023, and
GitHub matplotlib issue 7421, I installed matplotlib 2.0.0 thinking it would solve my problem, but it didn't.
PROBLEM DEFINITION
Using the pdf backend I save the result as pdf, but reading the same file with evince, okular, or Acrobat Reader gives different screenshots, as illustrated on the figures below:

INFORMATION
The expected output is the one given by evince (visible hatches). As already mentioned in other tracks, the rasterization of the contourf object does give the expected result but I need vectorial images. Furthermore, if rasterized hatches are used with high dpi (>300), the hatch width tends to 0 yielding wrong output. Finally I found this track matplotlib generated PDF cannot be viewed with acrobat reader issue which yielded this workaround solution :

*

*open the matplotlib output pdf file with evince

*print it to pdf

*vizualise the evince-printed output with okular
which gives the screenshot below:

Thanks a lot in advance for any explanation or solution for this problem. Don't hesitate if orther details/information are needed,
Tariq


text:
Q: Background color change makes all elements disappear I would like to change the background color of the entire screen. So I have tried to add this code UIView.appearance().backgroundColor = UIColor.red. It changes the background color but sadly it makes everything else disappear. So if someone let me know what I did wrong I would be very happy about what.
import SwiftUI

struct ContentView: View {
    init() {
        UIView.appearance().backgroundColor = UIColor.red
    }

    var body: some View {
        NavigationView {
            Text("hello")
        }
    }
}

#if DEBUG
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif

A: Forget about UIKIt and UIView. You just need a ZStack:
struct TestView: View {

    var body: some View {
        ZStack {
            Color.red
            Text("hello")
        }   .edgesIgnoringSafeArea(.all)
    }
}


text:
Q: PHP Socket programming to read data from MCU Quick question, I am new to socket, so I was wondering is there a way to read data from a MCU (Atmel)? I'm running a Linux and I can connect an Atmel through RS232, or USB to my computer(server). Is there a way that I can directly read the data that is coming from MCU (USB/COM) to my computer and process them?

A: Sockets are a concept of network communication (IP), so you would need network interfaces on both devices, plus an IP protocol stack on your Atmel (which may be the case for larger boards running a real operating system, e.g. embedded Linux).
If your Atmel has an USB interface, and if it implements a USB storage device, you can probably mount the Atmel to your server.
Otherwise (i.e. with a bare naked processor + peripherals, but no O/S) you really need to architect a solution from scratch - then a serial interface using the Atmel's UART function would be quickest to implement.
On the (Unix/Linux) server side you simply can use a character device to read in the data from serial or USB - e.g. cat < /dev/ttySxx >> SerPort.txt


text:
Q: Suprising Babel error after upgrading a Node.js module (monaco-editor) I'm working on an React-based web application (created using CRA), so it uses Babel to transpile and pack our code and Node.js modules. Creating the production build worked fine until I upgraded the monaco-editor Node.js module from 0.20.0 to 0.21.2. After that an error started showing up, which is totally unexpected and probably caused by (valid) code changes in monaco-editor:
Creating an optimized production build...
Failed to compile.

./node_modules/monaco-editor/esm/vs/editor/contrib/suggest/wordDistance.js
Error: <path>/node_modules/monaco-editor/esm/vs/editor/contrib/suggest/wordDistance.js: unknown Expression of type "ClassExpression"
    at Array.forEach (<anonymous>)

I'm pretty sure this is not a failure in the monaco-editor Node.js module and my web search brought me to some code that made me think this is an error printed by Babel. Beside others, I found this pull request for Babel which fixes a very similar error message.
There's no other information in the error message, so I cannot be 100% sure, and therefore I would also very much welcome anything I could use to get more context for this error message.
I created a minimal example which produces this behavior and allows to prove that the monaco-editor upgrade is the culprit: https://github.com/mike-lischke/babel-test.
But since this is valid JavaScript code, I supposed the real culprit is Babel, not being able to deal with the used syntax (or maybe I need a newer version, but since this is all integrated in CRA it's tricky to use newer versions of automatically installed components).

A: At the time being there's no other way than to return to the previous version of Monaco editor.


text:
Q: Request elevation for java We have to run the updater of our Java-based application using elevation (so it can overwrite files in the install location, usually %ProgramFiles%\<productName>). Until now I used a .vbs script that requests elevation and invokes another script. I was told that in some companies .vbs scripts are not allowed to be run because of security reasons. I'd rather should create a .exe that requires elevation. That's what I did, but now when I try to launch directly that elevation-requiring application from Java it fails with an java.io.IOException: CreateProcess error=740, The requested operation requires elevation.
How to run this application that Windows automatically requests the required elevation?

A: The problem was that there seem to be at least two ways of launching something on Windows. In Java one is implemented using Process. The other I found in SWT's implementation of Program.launch (using ShellExecute). When using the latter, Windows asks the user for elevation if necessary.


text:
Q: How to pair Bluetooth mouse with Apple Watch? Can I pair my Bluetooth mouse with Apple Watch? Or, can I get the functionality of a mouse with my Apple Watch?

A: watchOS wasn't designed to be used with a mouse. As such, it does not include mouse drivers or a mouse cursor, and therefore will not pair with a Bluetooth mouse.


text:
Q: Python - Error in thread when closing tkinter GUI window I am running a function that changes a label value in a thread while my tkinter is running. This code works unless I close the window before my thread stops. I have attached the error below.
How can I fix this problem? Is there a better way to set up these threads when using tkinter?
Code (works unless I close GUI window early):
from tkinter import *
from tkinter import ttk
import threading
import time

def fun():
    for i in range(10):
        var.set(var.get() + 1)
        print(var.get())
        time.sleep(.5)

t = threading.Thread(target=fun)

root = Tk()

var = IntVar()
var.set(0)

mainframe = ttk.Frame(root)
mainframe.grid(column = 0, row = 0)
label = ttk.Label(mainframe, textvariable=var)
label.grid(column = 0, row = 0)

t.start()
root.mainloop()
t.join()
print('Done')

Error when I close GUI window before fun() has finished running:
Exception in thread Thread-1:
Done
Traceback (most recent call last):
  File "C:\Users\PC-User\AppData\Local\Programs\Python\Python36-32\Lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\Users\PC-User\AppData\Local\Programs\Python\Python36-32\Lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "C:/Users/PC-User/PycharmProjects/Arb/example.py", line 8, in fun
    var.set(var.get() + 1)
  File "C:\Users\PC-User\AppData\Local\Programs\Python\Python36-32\Lib\tkinter\__init__.py", line 503, in get
    value = self._tk.globalgetvar(self._name)
RuntimeError: main thread is not in main loop


text:
Q: SQL Merge tables with two different columns I have two tables that look like this:
table1:

table2:

and I'd like to merge them, to create a table with a header like this:
variablenname | mean | stddev | ms_form | dependent | fvalue | probf

The first nine rows should be the first table with empty values in the last 3 columns followed by the three rows from the second table with empty values in the first 4 columns. I'm sorry I can't post pictures or a third link, but my reputation is too low. I hope it's understandable.
I tried to create a new table and select everything from both with union but that didn't work. Can anybody help me?
Thanks!

A: This is how I would like the final table to look like:

A: You can use ALTER to add the last 3 columns to table 1. From there, INSERT table 2 onto table 1. So something like this.
ALTER table1 ADD dependent varchar(16)
ALTER table1 ADD favalue varchar(16)
ALTER table1 ADD probf varchar(16)

INSERT INTO table1(dependent, fvalue, probf)
  SELECT * FROM table2

A: You can use a combination of joins and unions
LEFT JOIN the two tables in first query on fields that won't have a match
then UNION the second query with a RIGHT JOIN of the same tables.
The LEFT JOIN will only show results from the first table, then the RIGHT JOIN will only show results from the second
Something Like:
SELECT * FROM table1 as t1
LEFT JOIN table1 as t2 on t1.variablenname = t2.fValue
UNION
SELECT * FROM table1 as t1
RIGHT JOIN table1 as t2 on t1.variablenname = t2.fValue;


text:
Q: What can be said about $\pi+e$ and $\pi e$? Are these numbers rational or irrational? "homework"

What can be said about $\pi+e$ and $\pi e$? Are these numbers rational or irrational?

I know that both $\pi$ and $e$ are  irrational. What can be said about $\pi+e$, and $\pi e$?

A: It is not currently known whether or not $\pi+e$ is rational. It is also not known whether or not $\pi e$ is rational. However, we can say that $\pi+e$ and $\pi e$ cannot both be rational.
For suppose to the contrary that they are both rational. Then $(\pi+e)^2-4\pi e$ is rational. But this is $(\pi-e)^2$, so $\pi-e$ is algebraic. But then adding and subtracting $\pi+e$, we find that $\pi$ and $e$ are algebraic. But in fact both are transcendental.
The same proof shows that $\pi+e$ and $\pi e$ cannot be both algebraic.
Remark: The natural conjecture is that both $\pi+e$ and $\pi e$ are transcendental. After all, "most" real numbers are. However, settling the question of transcendentality, or even irrationality, of either would represent a major mathematical achievement.


text:
Q: Gradle Kotlin DSL can't find java.io package I'm trying to convert the build.gradle file of an Android app to a Kotlin DSL.
This file has a function like this:
def getLastCommitHash() {
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'rev-parse', '--short', 'HEAD'
        standardOutput = stdout
    }
    return stdout.toString().trim()
}

which I converted to this:
fun getLastCommitHash() {
    val stdout = ByteArrayOutputStream()
    exec {
        commandLine("git", "rev-parse", "--short", "HEAD")
        standardOutput = stdout
    }
    return stdout.toString().trim()
}

I get an Unresolved reference: ByteArrayOutputStream error and applying the import which changes it to java.io.ByteArrayOutputStream() shows an Unresolved reference: io error.
Is there something I'm doing wrong? Thanks in advance.

A: Importing from java.io works when doing it before the plugins block. I could successfully run builds for both Gradle 7.3.2 and 6.9.2 with the following build.gradle.kts:
import java.io.ByteArrayOutputStream

plugins {
    `java-library`
}

println(ByteArrayOutputStream::class)

If you escape the full package name, then you can also make it work without importing the class (tested as above):
plugins {
    `java-library`
}

println(`java.security`.MessageDigest::class)

A: I had this issue in backend project in intellij idea, I added this import at the top of build.gradle file:
import java.io.ByteArrayOutputStream

And now it works.

A: My observation:

*

*close project

*delete .idea and .gradle folders

*open project by selecting root-build.gradle.kts with "open as project"

did help.

A: This was an issue with Android Studio 3.5.6. After upgrading to Android Studio 3.6 everything is working.