text:
Q: How to refresh the contents within the Python TKINTER Tab? I have a program that displays some data from MySQL using Treeview. I would like to update the contents of it using a "refresh button" instead of terminating and re-running the program again. I have tried self.destroy() function, but it closes the tab and doesn't reopen the tab. Are there other ways to just refresh the Treeview?
class tab_four(Frame):
    def __init__(self, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs)

...

       #tree.heading("#0", text = " ")
        tree.heading("1", text = "Equipment Type")
        tree.heading("2", text = "Total")
        tree.heading("3", text = "Unavailable")
        tree.heading("4", text = "Available")

        #tree.column('#0', stretch = NO, minwidth = 0, width = 0)
        tree.column('#1', stretch = YES, minwidth = 0, width = 100, anchor = CENTER)
        tree.column('#2', stretch = YES, minwidth = 0, width = 100, anchor = CENTER)
        tree.column('#3', stretch = YES, minwidth = 0, width = 100, anchor = CENTER)
        tree.column('#4', stretch = YES, minwidth = 0, width = 100, anchor = CENTER)

        command = "SELECT et.`Equipment Type`, COUNT(i.`Equipment Type`) Total, SUM(IF(`Status`='Unavailable',1,0)) Unavailable, SUM(IF(`Status`='Available',1,0)) Available FROM `Equipment Types` et LEFT JOIN Inventory i ON et.`Equipment Type` = i.`Equipment Type` GROUP BY 1 ORDER BY 1"
        mycursor.execute(command)
        display = mycursor.fetchall()

        for row in display:
            tree.insert("", "end", values=row)

    def refresh_clicked(self):
        self.destroy()
        self.__init__()

        button_refresh = tk.Button(topframe, text = "Refresh", state = NORMAL, command = self.refresh_clicked)
        button_refresh.grid(row = 1, column = 2, sticky = W, padx = 5, pady = 2)

A: Try to fetch the values again and then insert the new values after deleting the existing values, like:
def refresh_clicked(self):
    command = """SELECT et.`Equipment Type`, COUNT(i.`Equipment Type`) Total, SUM(IF(`Status`='Unavailable',1,0)) Unavailable, SUM(IF(`Status`='Available',1,0)) Available FROM `Equipment Types` et LEFT JOIN Inventory i ON et.`Equipment Type` = i.`Equipment Type` GROUP BY 1 ORDER BY 1"""
    mycursor.execute(command)
    display = mycursor.fetchall()

    self.tree.delete(*self.tree.get_children()) # Delete all times inside the treeview

    for row in display:
        self.tree.insert('','end',value=row) # Insert newly fetched values

Note that I used self.tree, so you need to declare the Treeview with self.tree and do all other methods with self.tree and so on.

A: you can use
for widgets in yourwidgetname.winfo_children():
    widgets.destroy()

and reinitialize it by calling the function that initialize them
you can destroy all the widgets in a Frame by this way and it wont destroy completely your frame. it will destroy its child widgets.


text:
Q: A compact set $K \subset \mathbb{R}$ of positive Lebesgue measure such that $m(K \cap I) < |I|$ for every interval $I$ of positive length
There exists a compact set $K \subset \mathbb{R}$ of positive Lebesgue measure such that $m(K \cap I) < |I|$ for every interval $I$ of positive length

For this question, I am thinking about using a fat Cantor set K . I know there is no interval contained in a fat Cantor set K . But how to proceed to argue that $m(K \cap I) <|I|$ then?
Source: it's an exercise from Tao's book.

A: Summary of the main points made in comments:

*

*Every nonempty open set has positive length.

*For every open interval, $I\setminus K$ is open.

*If $I\setminus K$ is empty, then $K$ contains $I$, so it has nonempty interior.

*Fat Cantor sets have empty interior.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Inverse rotation transformations I'm taking the 2-degree gibmle system and position its alignment point in a arbitrary position (denoted by the axes angles phi for the first degree, and theta for the second). How can I reverse the transformations I did (first rotation of the first axis by phi, then rotation of the seconds axis by theta) and get phi and theta from the resulted alignment point's position on the unit sphere?

A: If your alignment point happens to lie on either of the axes, you cannot undo the operations, because rotation about that axis will leave the alignment point in the same place, so a single "final position" leads to multiple possible input-rotations.
Assuming that the axes start out perpendicular, with the first aligned with the $y$ axis and the second aligned with $x$, and the alignment point on the positive $z$ axis, it's not too difficult. The tricky part is deciding what "first" and "second" mean here.
I mean that if you rotate in $y$, then the $x$-rotation axis remains fixed, but if you rotate in $x$, then the $y$-rotation axis will be moved.
In that case, a rotation by $\phi$ about $y$ moves $(0,0, 1)$ to $(\sin \phi, 0, \cos \phi)$; a further rotation about $x$ by $\theta$ moves the resulting point to
$$
\begin{bmatrix}
1 & 0 & 0 \\
0 & \cos \theta & -\sin \theta \\
0 & \sin \theta & \cos \theta
\end{bmatrix}
\begin{bmatrix}
\sin \phi \\
0 \\
\cos \phi
\end{bmatrix} =
\begin{bmatrix}
\sin \phi \\
-\sin \theta \cos \phi \\
\cos \theta \cos \phi
\end{bmatrix}
$$
Given this location as an $xyz$-triple, how can you recover $\phi$ and $\theta$? Well,
let's assume that $\phi$ is restricted to $-90\deg < \phi < 90 \deg$. In that case, $\cos \phi > 0$, and
$$
\theta = {\mathrm{atan2}}(-y, z)
$$
Now you can compute
$$
u = -x / \sin \theta
$$
or
$$
u = z/ \cos \theta
$$
using whichever formula has a nonzero denominator.
Finally,
$$
\phi = \mathrm{atan2}(x, u).
$$
If you try to actually implement this, there's a good chance that one or both of your angle-directions will be opposite to mine, or that in your assembly the $y$-rotation comes first, etc. So you'll have to work through the analog of this using your conditions. But the main idea is that "atan2" is the solution.


text:
Q: Have access to a button that is located inside a collections view cell from a collectionViewController I have a UICollectionViewController class and a UICollectionViewCell class that is dequeued inside my CollectionView cellForItemAt. I have a button inside my cell and I want to have access to this button inside a function that is located in my collection controller but I don't want to reference this button from inside cellForItemAt. How can I do that?

A: To access your UICollectionViewCell from the UIViewController use:
if let cell = myCollectionView.cellForItem(at: IndexPath(item: theCellIndex, section: 0)) as? CustomCollectionViewCell {
// here you could access your cell.button
}


text:
Q: Using C# brackets without function or class syntax I'm new to C# and I can't find the right things to search for. I'm trying to understand the difference between these three types of syntax:

*

*public string Topic(){}

*public class Topic{}

*public string Topic{}
I know the 1st is a function and the 2nd is a class, but what confuses me is what the 3rd is.
question
what is #3 called and how is it used?
Anything that could provide clarity please.

A: The 3rd is a property. The most common representation in C# is autogenerated properties, like this:
public string Topic { get; set; }

Which is equivalent to:
private string _topic;

public string Topic
{
    get { return _topic; }
    set { _topic = value; }
}

It should be used to hold internal states of the object.
It can be a readonly property, with getter only:
public string Topic { get; }

Or only with setter:
public string Topic { set; }

You can also apply accessibility modificators in getters and setters, for example:
public string Topic { protected get; private set; }

A: The third is a property, when used correctly.  It's basically a variable with built in getter and setter.
public string Topic {get; set;}

This automatically creates a string variable which allows you to set or get directly via Topic = "new topic"
public string Topic {get; private set; }

allows public access to read the value but only the local class can set it.
Often, when more complexity is required than simply setting/getting, they are used with another backing value:
string _topic;
public string Topic {
    get { return _topic; }
    set { _topic = value; }
}

A: The third one is a property in C#. For example, you can have a person object (read class) with few properties. To get and set values for those properties, you use this kind of syntax.
public class Person
    {
        private string _name = "";

        public int Id { get; set; }

        public string Name {
            get{
                return "Jonathan";
            }
            set{
                this._name = value;
            }
        }
    }

Here Person has two properties namely Id and Name. The property syntax for Id is using "Automatic Property" syntax, which means someone can get and set this property like this:
var person = new Person();
person.Id = "1";//set Id value
//Or get Id value like this
var personId = person.Id;

The Name property is being set explicitly. When you request it, the hard coded value "Jonathan" will be returned and when setting, whatever value is assigned, will be set.
You can read more about properties here https://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx
Hope this helps.

A: The third forms a property function. It lives inside of a class. For example:
 public string MyProperty { get; set; }

To find out more you should look up encapsulation.

A: This is a shorthand:
This is getting and setting automatically, which is why they are called Auto-Implemented Properties. These two defined properties below are one & the same.
 public class Constituent{

   public string Name {get; set;} //This is a property,

   public string Name //This is a property, The value can only be of type **string** because we've assigned it that datatype, which would also be the return type.
   {
     get { return _name; }
     set { _name = value; }
     }
   }

You can also use access modifiers private, public, protected on them.
This will determine Whether you can you get & set the property value.
 public string Name {get; private set; }

In order to be be able to access the property you need to instantiate the Class(Constituent).
An example of how you can instantiate would be:
 var constituent = new Constituent();
 constituent.Name = "Jonathon"; //Setting the value of Name property.
 var Member_Name = constituent.Name; //Storing a value into a variable

Hope this Helped you. Auto-Implemented Properties


text:
Q: How to get the PID of a process started by /bin/su -c I'm writing a init.d-script for an java-app. But the java-app should be run by another user.
(The OS I'm using is Debian Squeeze.)
I already got this:
/bin/su - $USER - c "cd $PATH;echo $PASSWORD | $JAVA -Xmx256m -jar $PATH/app.jar -d > /dev/null" & PID=$!
/bin/su - $USER - c "echo $PID > $PIDFILE"

But this will of course only save the pid of the "/bin/su"-process instead of the pid of the created java-process.

A: Echo the PID inside the commands executed by "su":
/bin/su - $USER -c "cd $PATH;echo $PASSWORD | \
  $JAVA -Xmx256m -jar $PATH/app.jar -d > /dev/null & echo $! > $PIDFILE"


text:
Q: React-Native Animate View In and Out Currently, I am struggling with appearing and disappearing animations..
My aim is to animate a view in and again out.. but I want also that the view does 100% disappear after the animation
Idea
    ...

const visible: boolean = props.visible || false;
const [showView, setShowView] = useState<boolean>(visible);
const viewAnimation = useRef<Animatable.View & View>(null);

   useEffect(() => {
        const Animation = async () => {

            if (visible) {
                setShowView(true);
                if (viewAnimation.current)
                    await viewAnimation.current.bounceIn(2000);
            } else {
                if (viewAnimation.current)
                    await viewAnimation.current.bounceOut(2000);
                setShowView(false)
            }
        }

        Animation();
    }, [visible, viewAnimation]);

...

{showView &&
<Animatable.View ref={viewAnimation}>
...
</Animatable.View>
}

...

Problem
The viewAnimationRef get set in the next render cycle and not instant after setting the showView to true
-> the bounceIn animation will never get executed.. because viewAnimation.current is null..
I am using:

*

*react-native 0.62

*react-native-animatable 1.3.3

Maybe sb has an idea how to solve this problem ^^
Thank you

A: The solution is simple just wrap the Animatable.View around a normal view and hide the normal view if you want to hide it
Example:
    ...

const visible: boolean = props.visible || false;
const [showView, setShowView] = useState<boolean>(visible);
const viewAnimation = useRef<Animatable.View & View>(null);

   useEffect(() => {
        const Animation = async () => {

            if (visible) {
                setShowView(true);
                if (viewAnimation.current)
                    await viewAnimation.current.bounceIn(2000);
            } else {
                if (viewAnimation.current)
                    await viewAnimation.current.bounceOut(2000);
                setShowView(false)
            }
        }

        Animation();
    }, [visible, viewAnimation]);

...

<Animatable.View ref={viewAnimation}>
{showView &&
<View>
...
</View>
}
</Animatable.View>

...

A: I created an example in which translation and opacity changes and the view translates in and out of the screen
snack: https://snack.expo.io/QWWCkYS7U
export default function App() {
  const value = new Animated.Value(0);

  React.useEffect(() => {
    Animated.sequence([
      Animated.timing(value, {
        toValue: 1,
        duration: 1000,
        easing: Easing.ease,
      }),
      Animated.timing(value, {
        toValue: 0,
        duration: 1000,
        easing: Easing.ease,
      })
    ]).start()
  }, []);

  const translateX = value.interpolate({
    inputRange: [0, 1],
    outputRange: [width, 0],
  });

  const opacity = value

  return (
    <View style={styles.container}>
      <Animated.View style={[styles.view, { opacity, transform: [{ translateX }] }]} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  view: {
    width: 300,
    height: 100,
    backgroundColor: 'red',
  },
});

A: I use a 3 step approach to create animation using the Animated library.
#1 step - create the value you want to animate
let motion= new Animated.Value(0);
#2 Provide a mechanism to animated this value, use one of the builtin functions, spring, decay, timing
Animated.timing(motion,{toValue:100, duration:3000}).start();
#3 Apply the animated value to a porperty of the component/object you wanna animate
PS. in your case you want to animated the translation so the best approach is to
assign the animated value dynamically on a style and apply the style to the componente
///create a dynamic style
let myStyle = { transform:[{translateX:motion}]}
//adding the custom style to the component
<YourComponent  style={[anyOtherStyle, myStyle]}/>
For more about animation check out this channel:
https://www.youtube.com/watch?v=DwoSyhF3CkY


text:
Q: Grouping selectors by ID I have this code

    10
    34

    20
    5

    14
    23

    28
    8

    54
    55

    13
    99

    18
    55

    99
    66

I want a jquery selector where I can loop over the group of id and fetch the value of td cell. Note: the tr id are generated dynamically and can have none or N rows for each group of id. For example  (groupItem-12863 has 2 and groupItem-73632 has 3 rows)

A: Even if the following solution should do what you are expecting, I strongly suggest you to change the id to another attribute, a custom one like group-id or use CSS classes. By the way:
$(function() {
  var groupedRows = {};
  $.each($('tr[id^=groupItem]'), function() {
     if (groupedRows[$(this).attr('id')]) {
         groupedRows[$(this).attr('id')].push($(this));
     }
     else {
         groupedRows[$(this).attr('id')] = [$(this)];
     }
  });
  console.log(groupedRows);
});

A: HTML must not have same ids, it will be better to use class for your use-case.
After this you can get the elements with a given class and loop over them like

$(function(){
  $('.groupItem-73632').each(function() {
      console.log('grp');
      $(this).find('td').each(function(){
          console.log($(this).text());
      })
  })
})

        10
        34

        20
        5

        14
        23

        28
        8

        54
        55

        13
        99

        18
        55

        99
        66

A: I had to do bit of hack, I know the html was not ideal, we can't have same id's. But sometimes refactoring the older code is out of scope. Here is the solution, not ideal but works :

$('tr[id^=groupItem-]').each(function(){
 var s = 0 ;
  var text = $(this).attr('id');
  var arr = text.split('-');
  var elem = 'tr[id^=groupItem-' + arr[1] + ']';
    $(elem).find("td.selCost").each(function(){
   s += parseFloat($(this).text());
    });
console.log($(this).attr('id')+ '=='+s);
});

A: You can use the wildcard selector like tr[id^=groupItem]. Check Attribute Selector for more example.

$(function() {
  $('tr[id^=groupItem]').css({
    'background-color': 'red'
  });
});

    10
    34

    20
    5

    14
    23

    28
    8

    54
    55

    13
    99

    18
    55

    99
    66


text:
Q: Transferring large amount of data between MCUs running Linux and FreeRTOS I have two MCUs: one running embedded Linux and the other FreeRTOS and I want to be able to send variable-sized payloads between them and large amounts of data (probably upto 5K bytes or so). Ideally, the receiver should determine the number of bytes received rather than the transmitter sending a separate field indicating the number of bytes sent.
The main concern is around determining the physical protocol (e.g UART) given the larger max size of the payload, and allocating a 5K long buffer may be a bit of an overkill on an embedded system perhaps given the payload is not always maxed out.
Also, Linux device uses POSIX APIs including read(), write() that need to know how many bytes need to be received/sent and in my case, the sender isn't specifying the amount of bytes to be sent. The only way I could think of is to read each byte until an end-of-byte char is received but not sure how practical this approach would be
One idea could have been the use of pipes but FreeRTOS and Linux use different mechanisms?

A: SPI at 10 MHz is a good choice.
Use fixed payload size, 1024 for example, in order to use DMA interrupt. You don't want to fire an interrupt each time one byte is received or transmitted.
Use DMA on both Linux and FreeRTOS.

A: Partial answer: a typical way to read variable-length data packets in Linux is to buffer a certain number of bytes in the application. You create a buffer of, say, 16 kilobytes, then you call read to fill up the whole buffer. read won't wait for 16 kilobytes; it'll just return however many bytes have already been received by the kernel. But it does wait for at least 1 byte, so it's not busy-waiting and wasting CPU cycles.
Let's say read returns 5000. So now you have 5000 bytes in your buffer. Then you look at the start of your buffer and somehow figure out if you got the whole packet (that part is up to you). Suppose you got a 3000-byte packet; then you do whatever you want with the packet, and you check the next 2000 bytes. Suppose they aren't a whole packet, because this packet is 2500 bytes long but you've only got the first 2000. Then you shift the 2000 bytes to the start of the buffer, and go back to read. When you call read, you only ask it to read into the last 14k bytes of empty space, so it doesn't overwrite the 2000 bytes you haven't processed yet. And you repeat this forever.
It looks something like this:
char buf[BUF_SIZE];
int bytes_in_buffer = 0;
while(true) {
    int bytes_read = read(..., buf + bytes_in_buffer, BUF_SIZE - bytes_in_buffer);
    // add error checking here
    char *pos = buf;
    while(is_whole_packet(pos, bytes_in_buffer - (pos - buf))) {
        int packet_size = get_packet_size(pos);
        process_packet(pos, packet_size);
        pos += packet_size;
    }
    int bytes_processed = pos - buf;
    memmove(buf, pos, bytes_in_buffer - bytes_processed);
    bytes_in_buffer -= bytes_processed;
}


text:
Q: I can manully ssh2 to remote host, but paramiko can not, why? I want use paramiko to ssh2 to a remote host by public-key authentication, I setup the keys like these steps:
On local:
    Local> ssh-keygen
    Generating 1024-bit dsa key pair
    9 o.oOo..oOo.o
    Key generated.
    Passphrase :
    Again :
    Private key saved to /home/local/.ssh2/id_dsa_1024_a
    Public key saved to /home/local/.ssh2/id_dsa_1024_a.pub

    Local> cd ~/.ssh2
    Local> echo "IdKey id_dsa_1024_a" > identification
    Local> scp id_dsa_1024.pub remote@remote-host:~/.ssh2/local.pub

On remote:
    Remote> ssh-keygen
    ...omit...
    Remote> cd ~/.ssh2
    Remote> echo "Key local.pub" > authorization

After things above, I can just use ssh remote@remote-host to login.
However,I failed to use python's paramiko module to login remote-host:
    conn = paramiko.SSHClient()
    conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    conn.connect(remote-host, 22, username=remote,password='')

Alway error: Authentication failed.
I'm so confused. :(

A: Have you tried setting the key_filename option when connecting? I'm not sure that paramiko will automatically look at your private key in ~/.ssh like the SSH CLI client does.
paramiko documentation

A: import os
import paramiko
ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.abspath('.ssh/known_hosts'))
ssh.connect(some_host_in_known_hosts)

this fixed the same issue for me quite well this morning using python 2.7


text:
Q: Problem with image toggle on dynamically loaded Bootstrap collapse panel with nested collapse panel Can someone help with a dynamically loaded collapse panel with a nested dynamically loaded collapse panel? The issue I'm having is the image toggles for the outer and inner panels.  The collapse part is working fine, the image toggle is what I'm having problems with. Here is something similar to what I have.  Please forgive any syntax errors, I had to make up an example that is similar to mine.

    @foreach(AccountModel aModel in Model.AccountModels)
    {

                        @aModel.Description

                    @foreach(TransactionModel tModel in aModel.Transactions)
                    {
                        //nested collapse panel

                                        @tModel.Description

Some details

More details

                    }

    }


text:
Q: Create a form of an exercise with shadowbox With the following codes
\documentclass[12pt,a4paper]{article}
\usepackage{amsfonts,amsmath,amssymb,graphicx}
\usepackage{tikz,tkz-tab,moreverb} % tableau de signe moreverb not needed
\usetikzlibrary{arrows}
\usepackage[francais]{babel}
\usepackage{pifont} %bouni
\usepackage{fancybox} %pour faire l'encadrement
\usepackage[latin1]{inputenc}
\usepackage{verbatim}
\usepackage{color}
\usepackage[final]{pdfpages} %pour inserer une page pdf
\usepackage{fancyhdr} % pagestyle
%---- Dimensions des marges ---
\usepackage{geometry}
\geometry{left=1.5cm,right=1.5cm,top=1.5cm,bottom=1.5cm}
%\usepackage{setspace}
%\onehalfspacing
%---- Structure Exercice -----
\newtheorem{Exc}{Exercice}
\def\exo#1{\futurelet\testchar\MaybeOptArgmyexoo}
\def\MaybeOptArgmyexoo{\ifx[\testchar \let\next\OptArgmyexoo
                        \else \let\next\NoOptArgmyexoo \fi \next}
\def\OptArgmyexoo[#1]{\begin{Exc}[#1]\normalfont}
\def\NoOptArgmyexoo{\begin{Exc}\normalfont}
\newcommand{\finexo}{\end{Exc}}
\newcommand{\flag}[1]{}
%%%%%%%%%%%%%%%% debut exercice  %%%%%%%%%%%%%%%%%%%
%\exo{{}}:\\

%\finexo
%%%%%%%%%%%%%%%% fin exercice  %%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\definecolor{sfaxlogo}{RGB}{127,176,206}
\colorlet{sfaxblue}{sfaxlogo!70!black!60!blue}
\begin{document}
%%%%%%%%%%%%%%%% debut exercice  %%%%%%%%%%%%%%%%%%%
\exo{{}}:

\finexo
%%%%%%%%%%%%%%%% fin exercice  %%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%% debut exercice  %%%%%%%%%%%%%%%%%%%
\exo{{}}:

\finexo
%%%%%%%%%%%%%%%% fin exercice  %%%%%%%%%%%%%%%%%%%
\end{document}

I get

How can get the exercises with the following form

A: This is a good use case for amsthm, which lets you define a custom theorem style. Also, \newcommand is generally favored over \def, it also allows a much cleaner definition of the behavior you want:
\documentclass[12pt,a4paper]{article}
\usepackage{fancybox}
\usepackage{amsthm}
%any other packages

%---- Structure Exercice -----
\newtheoremstyle{sboxexc}% name of the style to be used
  {\topsep}% measure of space to leave above the theorem. E.g.: 3pt
  {\topsep}% measure of space to leave below the theorem. E.g.: 3pt
  {\itshape}% name of font to use in the body of the theorem
  {0pt}%  of space to indent
  {\bfseries}% name of head font
  {}% punctuation between head and body
  { }% space after theorem head; " " = normal interword space
  {\thmname{#1}}% Manually specify head
\newcounter{counter}
\setcounter{counter}{1}
\theoremstyle{sboxexc}
\newcommand{\optionaltext}{}
\newtheorem*{Exc}{\shadowbox{Exercice \arabic{counter}\optionaltext}}
\newcommand{\exo}[2][]{\renewcommand{\optionaltext}{#2}\begin{Exc}\normalfont $\:$}
\newcommand{\finexo}{\renewcommand{\optionaltext}{}\end{Exc}\addtocounter{counter}{1}}

\begin{document}
%%%%%%%%%%%%%%%% debut exercice  %%%%%%%%%%%%%%%%%%%
\exo

Lorem
\finexo
%%%%%%%%%%%%%%%% fin exercice  %%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%% debut exercice  %%%%%%%%%%%%%%%%%%%
\exo{: optional extra text}

Lorem
\finexo
%%%%%%%%%%%%%%%% fin exercice  %%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%% debut exercice  %%%%%%%%%%%%%%%%%%%
\exo

Lorem
\finexo
%%%%%%%%%%%%%%%% fin exercice  %%%%%%%%%%%%%%%%%%%
\end{document}

Gives

See:

*

*how amsthm's \newtheoremstyle works

*how to use \newcommand with optional arguments

*using a counter


text:
Q: AJAX AutoCompleteExtender help needed I have two text boxes that should be getting filled with Ajax AutoCompleteExtender information. One text done with a Web Service and the other is a code behind Web Method. The Web Service one is for Customer IDs; If I start my page with the web service and put in a number for the ID it works and gives me all of the information but if I try to do it in my actual asp.net form then nothing happens when I type in a number to for my search criteria. Also, for the Web Method from the code behind doesn't seem to find anything for me when I type a letter...... I'm wondering if I am missing a reference or something that is making my actual web page not fetch the data or am I just doing it wrong as this is my first time using this.
I am using Visual Studio 2012
asp.net webform
<%@ Page Language="C#"  AutoEventWireup="true" CodeBehind="Orders.aspx.cs" Inherits="TropicalServer.UI.Orders" %>

<!DOCTYPE html>

    <link type="text/css" rel="stylesheet" href="~/AppThemes/TropicalStyles/Orders.css" />
    <title>Orders Page</title>

    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

                        <asp:Label ID="lblOrderDate" runat="server" Text="Order Date: "></asp:Label>

                        <asp:DropDownList ID="ddlOrderDate" runat="server"></asp:DropDownList>

                        <asp:Label ID="lblCustID" runat="server" Text="Customer ID: "></asp:Label>

                        <asp:TextBox ID="tbCustID" runat="server"></asp:TextBox>
                        <ajaxToolkit:AutoCompleteExtender ID="aceCustID" runat="server"
                            ServicePath="wsOrders.asmx"
                            TargetControlID="tbCustID"
                            MinimumPrefixLength="1"
                            CompletionInterval="100"
                            CompletionSetCount="1"
                            ServiceMethod="GetCustomerID"
                            UseContextKey="true"
                            EnableCaching="true"> </ajaxToolkit:AutoCompleteExtender>

                        <asp:Label ID="lblCustName" runat="server" Text="Customer Name: "></asp:Label>

                        <asp:TextBox ID="tbCustName" runat="server"></asp:TextBox>
                        <ajaxToolkit:AutoCompleteExtender ID="aceCustName" runat="server"
                            TargetControlID="tbCustName"
                            MinimumPrefixLength="1"
                            EnableCaching="true"
                            CompletionInterval="1000"
                            CompletionSetCount="1"
                            UseContextKey="True"
                            ServiceMethod="GetCustomerName">
                        </ajaxToolkit:AutoCompleteExtender>

                        <asp:Label ID="lblSalesManager" runat="server" Text="Sales Manager: "></asp:Label>

                        <asp:DropDownList ID="ddlSalesManager" runat="server"></asp:DropDownList>

Code Behind asp.net
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using TropicalServer.DAL;

namespace TropicalServer.UI
{
    public partial class Orders : System.Web.UI.Page
    {
        #region Declerations
            DALConnection TropConnection;
        #endregion

        #region Constructor
        public Orders()
        {
            TropConnection = new DALConnection();
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        #region WebMethod
        [System.Web.Script.Services.ScriptMethod()]
        [System.Web.Services.WebMethod]
        public List<string> GetCustomerName(string prefixText)
        {
            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "spCustName";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@CustName", prefixText);
            cmd.Connection = TropConnection.GetConnection();
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            sda.Fill(dt);
            List<string> CustomerNames = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                CustomerNames.Add(dt.Rows[i]["CustName"].ToString());
            }
            return CustomerNames;
        }
        #endregion
    }
}

Web Service
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using TropicalServer.DAL;

namespace TropicalServer
{
    ///
    /// Summary description for wsOrders
    ///
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class wsOrders : System.Web.Services.WebService
    {
        #region Declerations
        DALConnection TropConnection;
        #endregion

        #region Constructor
        public wsOrders()
        {
            TropConnection = new DALConnection();
        }
        #endregion
        //"SELECT * FROM tblOrder WHERE OrderCustomerNumber LIKE @CustID+'%'"

        [WebMethod]
        public List<string> GetCustomerID(string prefixText)
        {
            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "spCustID";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@CustID", prefixText);
            cmd.Connection = TropConnection.GetConnection();
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            sda.Fill(dt);
            List<string> CustomerIDs = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                CustomerIDs.Add(dt.Rows[i]["OrderCustomerNumber"].ToString());
            }
            return CustomerIDs;
        }
    }
}

WEB CONFIG
<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
    <add key="TropicalServerConnectionString" value="Initial Catalog=TropicalServer;Data Source=Nicolas-PC\SQLEXPRESS;Integrated Security=true;" />
  </appSettings>
  <connectionStrings>
    <add name="TropicalServerConnectionString" providerName="System.Data.SqlClient" connectionString="Data Source=Nicolas-PC;Initial Catalog=TropicalServer;Integrated Security = true" />

  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
      </assemblies>
    </compilation>
    <authentication mode="Forms">

    </authentication>

  <pages>
      <controls>
        <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
      </controls>
    </pages></system.web>
</configuration>

A: I think your problem is with your method signature. If you have UseContextKey="True", the method should be:
public static string[] GetCustomerID(string prefixText, int count, string contextKey)
{
}

If UseContextKey="False", the method should be:
public static string[] GetCustomerID(string prefixText, int count)
{
}


text:
Q: Multiple IFERROR commands not working between 2 sheets I am trying to create a proper function code in excel 2010 that allows information from a schedule (4 days) to flow to a main schedule depending on the date.  'Main' page (sheet 1) has E1 pulling current date directly from computer. 'Beauty Shop' page has  manually entered date in B3, D3, F3 and H3 and if the dates match the information from A& B5-24, C&D5-24, E&F5-24, G&H5-24 respectively are suppose to pull to the main schedule.  At this point A&B will pull but when the other columns (D3, F3 and H3) have the matching date to main E1 the information from  C&D5-24, E&F5-24, G&H5-24 will not pull ... Here is what we entered
=IFERROR(IF(AND($E$1='Beauty Shop'!$B$3,'Beauty Shop'!A5>0),'Beauty Shop'!A5," "),IFERROR(IF(AND($E$1='Beauty Shop'!$D$3,'Beauty Shop'!C5>0),'Beauty Shop'!C5),IFERROR(IF(AND($E$1='Beauty Shop'!$F$3,'Beauty Shop'!E5>0),'Beauty Shop'!E5),IFERROR(IF(AND($E$1='Beauty Shop'!$H$3,'Beauty Shop'!G5>0),'Beauty Shop'!G5)," "))))
Any suggestions as to why the other 3 functions are not pulling the information to the main schedule??
Here is a link to what we have so far  ...This one should work...If you open it with Zoho sheet it will show all formulas and how we set everything up at this point.
https://drive.google.com/file/d/0B_wFNip-EvKdaXhVRDlnQzdQUzQ/view?usp=sharing

A: Ok, so I'm not 100% certain I understand what you're after but let's see if this helps...
From the spreadsheet you uploaded, and assuming you're referring to the formula in A47 on the main sheet...
=IFERROR(IF(AND($E$1='Beauty Shop'!$B$3,'Beauty Shop'!A5>0),'Beauty Shop'!A5," "),IFERROR(IF(AND($E$1='Beauty Shop'!$D$3,'Beauty Shop'!C5>0),'Beauty Shop'!C5),IFERROR(IF(AND($E$1='Beauty Shop'!$F$3,'Beauty Shop'!E5>0),'Beauty Shop'!E5),IFERROR(IF(AND($E$1='Beauty Shop'!$H$3,'Beauty Shop'!G5>0),'Beauty Shop'!G5)," "))))
LibreOffice's helpful formula editor shows the following for the start of your expression tree...

Let's ignore the IFERRORs for now and look at your first IF...
IF(AND($E$1=$'Beauty Shop'.$B$3,$'Beauty Shop'.A6>0),$'Beauty Shop'.A6," ")
In short...
If Main's E1 (Today's date) = Beauty Shop's B3 AND Beauty Shop's A6 is more than 0 (A time other than midnight), Return the value of Beauty Shop's A6 (The time). Otherwise, return an empty string.
The second IF block will only be executed if the first one errors, not if it returns false.
So the simple fix is to remove the blank string and move the following blocks up one level.
At the very least, make sure your strings aren't empty while debugging - it will make it a lot easier to track where your logic flow ends up.
EDIT: I previously said you could do this with a single IFERROR but that was incorrect.
Hope that helps a little
A simpler approach...
Let's use some hidden cells for some intermediate values to represent which data to pull.
Put the following formulae in Main.H1:K1:
=IFERROR(IF(AND($E$1=$'Beauty Shop'.$B3,$'Beauty Shop'.A5 > 0), 1, 0), 0)
=IFERROR(IF(AND($E$1=$'Beauty Shop'.$D3,$'Beauty Shop'.C5 > 0), 1, 0), 0)
=IFERROR(IF(AND($E$1=$'Beauty Shop'.$F3,$'Beauty Shop'.E5 > 0), 1, 0), 0)
=IFERROR(IF(AND($E$1=$'Beauty Shop'.$H3,$'Beauty Shop'.G5 > 0), 1, 0), 0)

These cells will now contain a 1 or 0 indicating the values should be populated. You can repeat these down the page.
The reason to do this is that there are 2 cases resulting in a 0 (No data and an error) so doing it all in one go would either require repeating the ELSE branch multiple times or doing some maths with the resulting values (which works and is concise but is very hard to follow/maintain)
Then your formula for Main.A47 becomes...
=IF(H1, $'Beauty Shop'.A5,IF(I1, $'Beauty Shop'.C5,IF(J1, $'Beauty Shop'.E5,IF(K1, $'Beauty Shop'.G5,""))))

See below for how today's value is matching (K1 is a 1) which has caused it to pull a record from the Beauty shop page.

Hope that's clearer?


text:
Q: Query XML column - get value based on other value in the same row in my database I have an XML-column that looks like this:
<Root>
  <Row>
    <Einheit>Stck</Einheit>
    <Faktor>1</Faktor>
    <VkPreisEinheit>1</VkPreisEinheit>
    <VkMengenEinheit>1</VkMengenEinheit>
    <EkMengenEinheit>1</EkMengenEinheit>
    <StcklEinheit>1</StcklEinheit>
    <StcklDefinition>1</StcklDefinition>
    <KonsumentenEinheit>1</KonsumentenEinheit>
  </Row>
  <Row>
    <Einheit>Stück</Einheit>
    <Faktor>100</Faktor>
    <EinheitFaktor>Stck</EinheitFaktor>
    <EkPreisEinheit>1</EkPreisEinheit>
  </Row>
</Root>

What I want to achieve ist that I get the value from 'Faktor' only from the row where 'EkPreisEinheit' is 1
I have tried something with:
CASE WHEN isnull(convert(xml,xmlcolumn).value('(/Root/Row/EkPreisEinheit)[1]','nvarchar(max)'),'') = '1'
     THEN isnull(convert(xml,xmlcolumn).value('(/Root/Row/Faktor)[1]','nvarchar(max)'),'')
     WHEN isnull(convert(xml,xmlcolumn).value('(/Root/Row/EkPreisEinheit)[2]','nvarchar(max)'),'') = '1'
     THEN isnull(convert(xml,xmlcolumn).value('(/Root/Row/Faktor)[2]','nvarchar(max)'),'')
     ELSE ''
     END AS Faktor

which would work if EKPreiseinheit would be found in both columns, but it only is in one. Also it could be that it is in the first row, or in the third if there was any. Is there any way to tackle this?

A: When dealing with multiple of the same node, you want to use nodes in the FROM to create a row for each one. This means you end up with something like this:
DECLARE @XML xml = '<Root>
  <Row>
    <Einheit>Stck</Einheit>
    <Faktor>1</Faktor>
    <VkPreisEinheit>1</VkPreisEinheit>
    <VkMengenEinheit>1</VkMengenEinheit>
    <EkMengenEinheit>1</EkMengenEinheit>
    <StcklEinheit>1</StcklEinheit>
    <StcklDefinition>1</StcklDefinition>
    <KonsumentenEinheit>1</KonsumentenEinheit>
  </Row>
  <Row>
    <Einheit>Stück</Einheit>
    <Faktor>100</Faktor>
    <EinheitFaktor>Stck</EinheitFaktor>
    <EkPreisEinheit>1</EkPreisEinheit>
  </Row>
</Root>';

WITH YourTable AS(
    SELECT V.YourXML
    FROM (VALUES(@XML)) V(YourXML))
SELECT R.R.value('(EkPreisEinheit/text())[1]','int') AS EkPreisEinheit
FROM YourTable YT
     --Due to the misuse of datatypes you'll need a CONVERT in a VALUES clause here instead
     CROSS APPLY YT.YourXML.nodes('/Root/Row') R(R)
WHERE R.R.value('(EkPreisEinheit/text())[1]','int') IS NOT NULL;

A: Here is a solution for you. Few points to mention. (0) It handles XML directly from the table. (1) It converts XML data into XML data type via TRY_CAST(). So it will emit NULL when XML is not well-formed without generating any error. (2) It checks via XPath predicate for the <Row> element where 'EkPreisEinheit' element value is 1, and filters out anything else.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY(1,1) PRIMARY KEY, xmlcolumn NVARCHAR(MAX));
INSERT INTO @tbl
VALUES (N'<Root>
    <Row>
        <Einheit>Stck</Einheit>
        <Faktor>1</Faktor>
        <VkPreisEinheit>1</VkPreisEinheit>
        <VkMengenEinheit>1</VkMengenEinheit>
        <EkMengenEinheit>1</EkMengenEinheit>
        <StcklEinheit>1</StcklEinheit>
        <StcklDefinition>1</StcklDefinition>
        <KonsumentenEinheit>1</KonsumentenEinheit>
    </Row>
    <Row>
        <Einheit>Stück</Einheit>
        <Faktor>100</Faktor>
        <EinheitFaktor>Stck</EinheitFaktor>
        <EkPreisEinheit>1</EkPreisEinheit>
    </Row>
</Root>');
-- DDL and sample data population, end

;WITH rs AS
(
   SELECT ID, TRY_CAST(xmlcolumn AS XML) AS xml_data
   from @tbl
)
SELECT ID
    , col.value('(Faktor/text())[1]','INT') AS Faktor
    , col.value('(EkPreisEinheit/text())[1]','INT') AS EkPreisEinheit
FROM rs as tbl
    CROSS APPLY tbl.xml_data.nodes('/Root/Row[EkPreisEinheit="1"]') AS tab(col);

Output

+----+--------+----------------+
| ID | Faktor | EkPreisEinheit |
+----+--------+----------------+
|  1 |    100 |              1 |
+----+--------+----------------+


text:
Q: Group By Statuses using reduce I have been using reduce() method to group by Open and Closes statuses (Status_111, Status_222, etc) which then creates an array of which Ids (item.Id) it is associated with.
Code is working and with an expected result but how do I avoid duplicated check when somewhat it does a similar thing and create blank arrays (Open and Close Status can have same Id (eg: Status_111), I am referring to this block section:
if (item.Open && !obj[item.Open]) {
    obj[item.Open] = {
      Open: [],
      Close: []
    }
}

if (item.Close && !obj[item.Close]) {
  obj[item.Close] = {
    Open: [],
    Close: []
  }
}

Usage:

const items = [
  { Id: 100, Open: 'Status_111', Close: 'Status_111' },
  { Id: 200, Open: 'Status_111', Close: 'Status_222' },
  { Id: 300, Open: 'Status_333', Close: 'Status_444' }
]

function groupByOpenAndClose(items) {
  return items.reduce(function (obj, item) {
    if (item.Open && !obj[item.Open]) {
        obj[item.Open] = {
          Open: [],
          Close: []
        }
    }

    if (item.Close && !obj[item.Close]) {
      obj[item.Close] = {
        Open: [],
        Close: []
      }
    }

    if (obj[item.Open]) {
      obj[item.Open].Open.push(item.Id)
    }

    if (obj[item.Close]) {
      obj[item.Close].Close.push(item.Id)
    }

    return obj
  }, {});
}

console.log(groupByOpenAndClose(items));

A: A reduce with a forEach is one way to get there

const items = [{
    Id: 100,
    Open: 'Status_111',
    Close: 'Status_111'
  },
  {
    Id: 200,
    Open: 'Status_111',
    Close: 'Status_222'
  },
  {
    Id: 300,
    Open: 'Status_333',
    Close: 'Status_444'
  }
]

let status = items.reduce((b, a) => {
  ['Open', 'Close'].forEach(s => {
    b[a[s]] = b[a[s]] || {Open: [], Close: []}
  });
  return b
}, {});

items.forEach(s => {
  status[s.Open].Open.push(s.Id);
  status[s.Close].Close.push(s.Id)
});

console.log(status)


text:
Q: Writing Errors in Multiprocessing Python I am trying to write certain files after editing using multiprocessing code python (2.7). It works like a charm for small number(<20). but when I try for more files (20+), it goes berserk.
I am using Python 2.7.5 on CentOS 6.5 with 4 Core Processor.
import sys, os
import multiprocessing

import glob
list_files = glob.glob("Protein/*.txt")

def Some_func(some_file):
    with open(some_file) as some:
        with open(file_output) as output:
            for lines in Some:
                #Do Something
                #edited_lines = func(lines)
                output.write(edited_lines)

pool = multiprocessing.Pool(10) # Desired number of threads = 10
pool.map(Some_func, list_files,)
pool.close()
pool.join()

The final written files overlap each other.
File 1
Lines 1 .. File 1
Lines 2 .. File 1
Lines 3 .. File 1
Lines 4 .. File 1
Lines 5 .. File 1
Lines 6 .. File 1
Lines 7 .. File 1
Lines 8 .. File 1
Lines 9 .. File 1

File 2
Lines 1 .. File 2
Lines 2 .. File 2
Lines 3 .. File 2
Lines 4 .. File 2
Lines 5 .. File 2
Lines 6 .. File 2
Lines 7 .. File 2
Lines 8 .. File 2
Lines 9 .. File 2

Output:

Lines 1 .. File 1
Lines 2 .. File 1
Lines 3 .. File 1 Lines 1 .. File 2
Lines 4 .. File 1
Lines 5 .. File 1Lines 2 .. File 2
Lines 3 .. File 2
Lines 4 .. File 2
Lines 6 .. File 1

A: The problem is that you're trying to write to the file from many processes in parallel, which isn't synchronized. That means its possible that different processes will try to write at the same time, leading to the oddities you're seeing.
You can solve this by either having a single writer process, with each worker sending the lines to write to that single process, or by synchronizing the writes done by each process using a multiprocessing.Lock.
Using a single writer:
import glob
import multiprocessing
from functools import partial
from threading import Thread

list_files = glob.glob("Protein/*.txt")

def Some_func(out_q, some_file):
    with open(some_file) as some:
        for lines in Some:
            #Do Something
            #edited_lines = func(lines)

            out_q.put(edited_lines)

def write_lines(q):
   with open(file_output) as output:
       for line in iter(q.get, None): # This will end when None is received
           output.write(line)

pool = multiprocessing.Pool(10) # Desired number of threads = 10
m = multiprocessing.Manager()
q = m.Queue()
t = Thread(target=write_lines, args=(q,))
t.start()
pool.map(partial(Some_func, q), list_files)
pool.close()
pool.join()
q.put(None)  # Shut down the writer thread
t.join()

Using a multiprocessing.Lock:
import glob
import multiprocessing
from functools import partial

list_files = glob.glob("Protein/*.txt")

def Some_func(lock, some_file):
    with open(some_file) as some:
        with open(file_output) as output:
            for lines in Some:
                #Do Something
                #edited_lines = func(lines)
                with lock:
                    output.write(edited_lines)

pool = multiprocessing.Pool(10) # Desired number of threads = 10
m = multiprocessing.Manager()
lock = m.Lock()
pool.map(partial(Some_func, lock), list_files)
pool.close()
pool.join()

We need to use a Manager to create the shared objects because you're passing them to a Pool, which requires pickling them. Normal multiprocessing.Lock/multiprocessing.Queue objects can only be passed to a multiprocessing.Process constructor, and will cause an exception when passed to a Pool method like map.


text:
Q: Loop device going into Readonly Mode We are using a network Samba drive for Backup on our Linux Server. In order to store permissions (Samba does not support this), we have created a loop device to a large file (50GB) on the network drive.
This works fine most of the time, but every few weeks the loop device goes into readonly mode.
Here is the fstab snippet for network drive and loop drive:
//xyxyxy.your-backup.de/backup /backup cifs credentials=/root/backup-credentials,iocharset=utf8 0 0
/backup/backup.lp /backup-loop ext3 loop,sync,defaults,_netdev 0 0

I aldo tried standard loop configuration, but the problem maintains:
/backup/backup.lp /backup-loop ext3 loop,sync 0 0

Our assumption:
As far as I know the mounted drive goes into readonly mode when the connection to the physical device is lost. Thus when the network drive loses connection, the loop file is gone and the loop mount goes into readonly mode. The cifs handles reconnecting of its own mount, but loop knows nothing about it.
Our current solution is to force remount of both samba and loop device shortly before our cronjob would start the backup process. This works, but doesn't feel right.
Is there a possibility to trigger remount of loop device when the target loop file gets back online?

A: I think your assumption about things going into read only mode when the connection to the network drive is lost is correct. I made a simple test with a just a small file on a Samba share and the same thing happens if I yank the network cable.
As for a solution to the problem, I would go about it like this:

*

*Depending on how you actually do the backup, I would mount the loop
file rw as part of the backup process and unmount it once done. This
also helps safeguarding the backup against accidental pilfering.

*If you need access to the backup at other times, mount it read-only.
You can keep the file mounted this way at all times, excepting when
you actually want to do a backup

*That way, no one gets hurt and you are able to do what you want when
you want. I would go so far as to say it is even a little bit better
than keeping the loop file mounted rw all the time - given safety
concerns.
If you use rsync to do your backup, you can check on the rsync exit status to figure out if you have been unlucky enough to lose the connection while doing the backup (true for other tools too - just my preference). You may then act accordingly.
This does not get you exactly what you asked for - I would say it gets you something a little better - but I don't think you can expect the loop device to work as you want wo. some trickery anyway.
I hope this helps :-)

A: Years later we replaced this loop drive on samba with Borg backup over ssh.
This is overall better solution for file backup.


text:
Q: Need some ideas on how to implement an evaluation function I am working on a chessgame and now trying to implement a minimax algorithm which calculates a score using a piece square table and Piece value. I have been able to create to following methods show below, but don't know how to go about calculating the piece score within the CalculateScore() and evaluatePieceScore() methods. Please, I am really confused and need assistances.
1) getPieceValue() this method returns a constant values assigned to each chess piece
2) getScoreForPiecePosition() gets the evaluation bonus for the specified position
3) CalculateScore() calculates and returns a score using the piece square table.
4) evaluatePieceScore() adds the calculated score from the CalculateScore() to the original score depending on whos's turn.
public class MinimaxPlayer implements IPlayerHandler, EvaluationAlgorithm{

private Game chessgame;
private MoveChecker checker;
private BoardGUI boardgui;

private static int maxDepth = 2;

public MinimaxPlayer(Game chessgame){
    this.chessgame = chessgame;
    this.checker = chessgame.getMoveChecker();
    this.boardgui = new BoardGUI(chessgame);
}

@Override
public int getPieceValue(int type) {
    switch(type){
    case Piece.TYPE_PAWN: return 100;
    case Piece.TYPE_KNIGHT: return 320;
    case Piece.TYPE_BISHOP: return 325;
    case Piece.TYPE_ROOK: return 500;
    case Piece.TYPE_QUEEN: return 975;
    case Piece.TYPE_KING: return 32767;
    default: throw new IllegalArgumentException("Unknown piece type: "+ type);
    }
}

@Override
public int evaluatePieceScore() {
    int scoreBrown = 0;
    int scoreYellow = 0;
    for (Piece piece : this.chessgame.getPieces()) {
        if(piece.getColor() == Piece.BROWN_COLOR){
            scoreBrown +=
                getScoreForPieceType(piece.getType());
            scoreBrown +=
                getScoreForPiecePosition(piece.getRow(),piece.getColumn());
        }else if( piece.getColor() == Piece.YELLOW_COLOR){
            scoreYellow +=
                getScoreForPieceType(piece.getType());
            scoreYellow +=
                getScoreForPiecePosition(piece.getRow(),piece.getColumn());
        }else{
            throw new IllegalStateException(
                    "unknown piece color found: "+piece.getColor());
        }
    }

    // return evaluation result depending on who's turn it is
    int gameState = this.chessgame.getGameState();

    if( gameState == Game.GAME_STATE_BROWN){
        return scoreBrwon - scoreYellow;

    }else if(gameState == Game.GAME_STATE_YELLOW){
        return scoreYellow - scoreBrown;

    }else if(gameState == Game.GAME_STATE_END_YELLOW_WON
            || gameState == Game.GAME_STATE_END_BROWN_WON){
        return Integer.MIN_VALUE + 1;

    }else{
        throw new IllegalStateException("unknown game state: "+gameState);
    }
}

public int CalculateScore(int index, int pieceValue, int[] SquareTable ){
    int score = pieceValue;

    for(int i = 0; i < SquareTable.length; i++){
        score += getPieceValue(index.get(SquareTable[i]));

    }

    return 0;
}

@Override
public int getScoreForPiecePosition(int row, int column) {
    byte[][] positionWeight =
    { {1,1,1,1,1,1,1,1}
     ,{2,2,2,2,2,2,2,2}
     ,{2,2,3,3,3,3,2,2}
     ,{2,2,3,4,4,3,2,2}
     ,{2,2,3,4,4,3,2,2}
     ,{2,2,3,3,3,3,2,2}
     ,{2,2,2,2,2,2,2,2}
     ,{1,1,1,1,1,1,1,1}
     };
    return positionWeight[row][column];
}

private static int[] PawnSquareTable = new int[]
{
    0,  0,  0,  0,  0,  0,  0,  0,
    50, 50, 50, 50, 50, 50, 50, 50,
    10, 10, 20, 30, 30, 20, 10, 10,
     5,  5, 10, 25, 25, 10,  5,  5,
     0,  0,  0, 20, 20,  0,  0,  0,
     5, -5,-10,  0,  0,-10, -5,  5,
     5, 10, 10,-20,-20, 10, 10,  5,
     0,  0,  0,  0,  0,  0,  0,  0
};

private static int[] KnightSquareTable = new int[]
{
    -50,-40,-30,-30,-30,-30,-40,-50,
    -40,-20,  0,  0,  0,  0,-20,-40,
    -30,  0, 10, 15, 15, 10,  0,-30,
    -30,  5, 15, 20, 20, 15,  5,-30,
    -30,  0, 15, 20, 20, 15,  0,-30,
    -30,  5, 10, 15, 15, 10,  5,-30,
    -40,-20,  0,  5,  5,  0,-20,-40,
    -50,-40,-30,-30,-30,-30,-40,-50,
};

private static int[] BishopSquareTable = new int[]
{
    -20,-10,-10,-10,-10,-10,-10,-20,
    -10,  0,  0,  0,  0,  0,  0,-10,
    -10,  0,  5, 10, 10,  5,  0,-10,
    -10,  5,  5, 10, 10,  5,  5,-10,
    -10,  0, 10, 10, 10, 10,  0,-10,
    -10, 10, 10, 10, 10, 10, 10,-10,
    -10,  5,  0,  0,  0,  0,  5,-10,
    -20,-10,-10,-10,-10,-10,-10,-20,
};

    private static int[] RookSquareTable = new int[]
{
    0,  0,  0,  0,  0,  0,  0,  0,
    5, 10, 10, 10, 10, 10, 10,  5,
   -5,  0,  0,  0,  0,  0,  0, -5,
   -5,  0,  0,  0,  0,  0,  0, -5,
   -5,  0,  0,  0,  0,  0,  0, -5,
   -5,  0,  0,  0,  0,  0,  0, -5,
   -5,  0,  0,  0,  0,  0,  0, -5,
    0,  0,  0,  5,  5,  0,  0,  0,
};

    private static int[] QueenSquareTable = new int[]
{
    -20,-10,-10, -5, -5,-10,-10,-20,
    -10,  0,  0,  0,  0,  0,  0,-10,
    -10,  0,  5,  5,  5,  5,  0,-10,
     -5,  0,  5,  5,  5,  5,  0, -5,
      0,  0,  5,  5,  5,  5,  0, -5,
    -10,  5,  5,  5,  5,  5,  0,-10,
    -10,  0,  5,  0,  0,  0,  0,-10,
    -20,-10,-10, -5, -5,-10,-10,-20,
};

private static int[] KingMiddleGameSquareTable = new int[]
{
    -30,-40,-40,-50,-50,-40,-40,-30,
    -30,-40,-40,-50,-50,-40,-40,-30,
    -30,-40,-40,-50,-50,-40,-40,-30,
    -30,-40,-40,-50,-50,-40,-40,-30,
    -20,-30,-30,-40,-40,-30,-30,-20,
    -10,-20,-20,-20,-20,-20,-20,-10,
     20, 20,  0,  0,  0,  0, 20, 20,
     20, 30, 10,  0,  0, 10, 30, 20,
};

private static int[] KingEndGameSquareTable = new int[]
{
    -50,-40,-30,-20,-20,-30,-40,-50,
    -30,-20,-10,  0,  0,-10,-20,-30,
    -30,-10, 20, 30, 30, 20,-10,-30,
    -30,-10, 30, 40, 40, 30,-10,-30,
    -30,-10, 30, 40, 40, 30,-10,-30,
    -30,-10, 20, 30, 30, 20,-10,-30,
    -30,-30,  0,  0,  0,  0,-30,-30,
    -50,-30,-30,-30,-30,-30,-30,-50,
};

public static int[] reverse(int[] arr){
    ArrayUtils.reverse(arr);
    return arr;
}

}

A: If you feel confused, I would recommend starting with an simple evaluation function taking into account only the value of the pieces (1 point for a pawn, 3 points for a bishop and a knight, 5 points for a rook, 9 points for a queen and a lot of points for a king, let's say 200)
and then your function becomes:
    public int calculateScore()
    {
        return blackPlayer.getMaterial() - whitePlayer.getMaterial()
    }

The function getMaterial() will be the sum of all your pieces points.
Example: black has 1 pawn, 1 queen and a king, then blackPlayer.getMaterial() will return = 1 + 9 + 200 = 210
After if you want to take into account the position of the piece into the evalution function, you can do something like that:
    public int calculateScore()
    {
        int blackScore = blackPlayer.getMaterial() + blackPlayer.getBonusPosition();
        int whiteScore = whitePlayer.getMaterial() + whitePlayer.getBonusPosition();
        return blackScore - whiteScore;
    }

The function getBonusPosition() will return the sum of all the bonus position score of all your pieces:
Example: blackPlayer has 1 pawn at position (0,0), 1 queen at position (0,1) and a king at position (2,2):

*

*the bonus position of the pawn at (0,0) is 0

*the bonus position of the queen at (0,1) is -10

*the bonus position of the king (in the endgame) at (2,2) is -20
blackPlayer.getBonusPosition() will return = 0 - 10 -20 = -30
You can change your coefficients to give more importance to material value or to the position on the board. For instance, in the previous examples the position score was way much too important compared to the material score.
Example: You want give more importance (let's say 10 times more) to the material value and you don't really care about the position of the pieces on the board, then you new calculate score function will be:
    public int calculateScore()
    {
        int blackScore = 10*blackPlayer.getMaterial() + blackPlayer.getBonusPosition();
        int whiteScore = 10*whitePlayer.getMaterial() + whitePlayer.getBonusPosition();
        return blackScore - whiteScore;
    }

A: Your missing part is a function taking type, row and column as arguments :
public int getScoreForPieceTypeAndPosition(int type, int row, int
 column) { public int getPieceValue(int type) {
     switch(type){
     case Piece.TYPE_PAWN: return PawnSquareTable[row * 8 + column ];
     case Piece.TYPE_KNIGHT: return KnightSquareTable[row * 8 + column ];
     case Piece.TYPE_BISHOP: return BishopSquareTable[row * 8 + column ];
     case Piece.TYPE_ROOK: return RookSquareTable[row * 8 + column ];
     case Piece.TYPE_QUEEN: return QueendSquareTable[row * 8 + column ];
     case Piece.TYPE_KING: return KingSquareTable[row *8 + column];
     default: throw new IllegalArgumentException("Unknown piece type: "+ type);
     } }

and use that method in overall computation.
[ not tested ]
It might not be enough for tables that are not symetrical like Pawn, then you need to give BROWN or WHITE argument and call function with ( 7 - row ) instead of row for BROWN by example.
( googling = http://chessprogramming.wikispaces.com/Simplified+evaluation+function )


text:
Q: Laravel - route within view isn't working I'm learning laravel, working with 3 files, Welcome.blade.php / route.php / tryaction.php and it's a controller.
I made three links that fetched from database table => hug, greet and slap
when I click any link it gives me an error that actions is not defined.
my Welcome.blade.php:

    @foreach ($actions as $action)

 $action->name]) }}">{{$action->name}}

    @endforeach

my route.php:
<?php

Route::get('/', [
    'uses'      => 'tryaction@getHome',
]);

//to deal with get requests
Route::get('/{action}/{name?}', [
    'uses'      => 'tryaction@doget',
    'as'            => 'benice'
]);

my tryaction.php controller:
namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\actionstable;

class tryaction extends Controller
{
    public function doget($action, $name = null){
            return view('actions.'.$action,['name'=>$name]);
        }

        public function getHome(){
            $actions = actionstable::all();
            return view('welcome',['actions'=>$actions]);
        }
}

when I replace the href route in welcome.blade.php with # instead of {{ route('benice', ['action' => $action->name]) }} the error stops from showing on
the data are fetched correctly and the data is shown on the page .. the problem in the route and it's that the actions is not defined, here is the error page:


text:
Q: Class relationship in Django model My project(Django Rest Framework) is blog app where logged in users can Post some texts and any logged in users can add comment to Posts.
What are the changed I need to make in the Post and Comment class to establish the logic ?
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings

class User(AbstractUser):
       #User model

class Post(models.Model):
    postdata = models.CharField(max_length=100)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)

class Comment(models.Model):
    body = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)

A: Add a ForeignKey pointing to your Post model in the Comments model:
post = models.ForeignKey('Post', on_delete=models.CASCADE, related_name='comments')

As a good practice, keep using settings.AUTH_USER_MODEL instead of User directly


text:
Q: How to automatically backup Windows event logs? There doesn't appear to be a way to backup (archive) Windows event logs automatically via the GUI.  Is there a way via a script that can be set as a scheduled task to do this?  If so, can someone point me to a beginner's article on how to write this as I'm not a script guy.  Thanks!  This would be for Windows Server 2003 by the way.

A: Our friends over at StackOverflow show how to do this:  https://stackoverflow.com/questions/661782/simple-way-to-backup-event-log-on-windows-server
Also look on the Scripting Guy (Technet) here: How Can I backup the Event Log?


text:
Q: IIS 7 Site using HTTPS not Accessible from Outside Internet (is accessible from intranet) I am trying to set up an HTTPS site on IIS 7. I have added the certificate, set up the appropriate bindings and the site is accesible from within my company's intranet, however no one from the outside internet can access it. I have a 1:1 NAT forward set up for port 443 that should route requests to the IP address for my server. I have the same situation for port 80 and don't have any issues with http sites being accessible.
Any suggestions for what I might be missing here?
UPDATE:
As it turns out, the company that manages my company's firewall had added the exception for https and 443, and the correct routing, but hadn't added an exception for the process that handles https.

A: For starters, from outside, use telnet to see if you can even get to the port from outside:
telnet <host name or ip> 443

Note the space before the port.
If the telnet screen goes fully black, w cursor in top left, you can connect, so it is an iis issue.
If telnet just sits there, it is trying to connect but can't. It may finally throw "connection refused" or "could not connect." This means the problem is on the physical firewall (which needs the inbound path opened) or on the iis server itself (in its firewall or iis config)
In this case, next step:
Do the telnet operation on the IIS server itself, and from the same network as IIS (e.g. not through the firewall).
-- If this works: The problem is the network firewall config
-- If this does not work, you need to check the firewall on the IIS server itself (the windows firewall), and the IIS config itself
Note, on windows 7 and vista, telnet may not be present out of the box. Google how to enable it.


text:
Q: How can I get the [Error]: from NSError.description? I am trying to create a UIAlertView that displays only the error of NSError.description.
For example:
var alert = UIAlertView(title: "Oops!", message: error.description, delegate: self, cancelButtonTitle: "OK")
alert.show()

Say the error.description outputs:
2015-02-01 02:26:43.227 UserLogin[249:13655] [Error]: missing username (Code: 200, Version: 1.6.2)

How can I just get the [Error]: missing username in a String? I am new to app development and I simply want my error messages to make sense to the user and to be simple.
If this does not make sense, I am using Parse and I am working on a registration form. If the error occurs such as "missing username", "username taken", etc. I just wanted to find a way to get a simple error popup to say "username taken".

A: You can use the localizedDescription property of NSError.
Instead of error.description use error.localizedDescription
var alert = UIAlertView(title: "Oops!", message: error.localizedDescription, delegate: self, cancelButtonTitle: "OK")
alert.show()

Note:
UIAlertView is deprecated in iOS 8, use UIAlertController instead.

A: Try using this:
if let dic  = error?.userInfo {
   let errorString = dic[NSUnderlyingErrorKey]?.localizedDescription
   var alert = UIAlertView(title: "Oops!", message:errorString, delegate: self, cancelButtonTitle: "OK")
   alert.show()
}

A: Before you go in that direction, you should think very, very hard whether the NSError that you received is meant to be seen by a user. Many NSErrors are meant to be examined by a programmer only. In this case, "missing username" seems a strong indication that you, the programmer, made a mistake by sending a request without a username and shouldn't have done that in the first place. So showing an error alert may be the totally wrong solution.


text:
Q: How can I use LEMMISI effectively? I've always been converting this glyph immediately.  Revealing three random tiles not only isn't very helpful, it actually removes future healing potential.  I can get the same healing effect from just revealing three tiles that are actually near me.  So why would I ever want to take up one of my glyph slots with LEMMISI?

A: It's basically meant more as a primitive healing factor, which is why there's actually a bonus point reward for using LEMMISI repeatedly in one stage. Don't use it to rob your future healing potential, use it as your healing potential.
If you're not a Wizard or Berserker, you make even with the mana cost. Wizards will regain 1 Mana, while Berserkers will spend 2 extra Mana. It's primarily for usage when you don't want to perform exploration directly. Some reasons you might want to do so include:

*

*As a primer to actual exploration. You have some damage, want to heal it before advancing. Use LEMMISI to possibly see what might be a better direction that you want to head in, rather than bruting through the darkness towards what may have been the worse direction to go.

*As an extension to the above, use it while facing off multiple visible opponents at once. This lets you get the normal healing effect of exploration while exploring the more remote parts of the map, instead of what is right near you.

*If you're in a situation where you can't directly explore due to big tough fellows in the way, but you can defeat one opponent if you had the aid of exploration regeneration (either just to get back to full health, or because you can beat the enemy's regeneration rate), then this helps.

*You've run out of normally reachable exploration, and there's some blackness that's buried inside of a bunch of stone blocks. Unless you're a transmuter (in which case you don't want LEMMISI in the first place), it's far cheaper to use LEMMISI than to dig through the walls.

*If you're a Sorceror, then you get extra healing on account of your ability. Since the mana cost equals the amount you'd regain from actual exploration, it's actually better healing.


text:
Q: not found: value udf error I have a udf defined in my code as follows:
val toOriginalTimestamp = udf((timestamp: String) => timestamp.substring(0, 18))

I'm trying to take a substring of the timestamp field in my dataset. However I'm getting the error as not found: value udf
What am I doing wrong?

A: You probably need this one:
import org.apache.spark.sql.functions.udf

Also, make sure that you are using spark-sql (not just spark-core!) 1.3 or higher dependencies.


text:
Q: Spring Integration Splitter and Aggregator : Release one by one My requirement : incoming xml needs to be split into multiple nodes and each node has to be converted to json and send each node's json to http end point.

*

*I could split the incoming json using XPathMessageSplitter

*Collected all the messages at the Aggregator and converting it to json and right now i have List<String> .

Now i have to iterate the List<String> and send it to HttpRequestExecutingMessageHandler one by one.

*

*Is there any way to release the message one by one at aggregator side so that it will be to sent it to HttpRequestExecutingMessageHandler outbound one by one?

*or after receiving list of string at aggregator , any way to send it to HttpRequestExecutingMessageHandler outbound one by one?

A: Just add a simple splitter after the aggregator. The DefaultMessageSplitter (<splitter/>) will split any collection, iterable, iterator etc.


text:
Q: How to resolve lifetime iterator impl error I have a data structure called 'FluidSim' which is a bunch of cells. Think of a 2d grid (x,y) which then holds a vector of data for each cell (grid location).
I want to make an iterator which lets me iterator over this grid (and in future I want to be able to skip empty cells).
Additionally I want some additional functionality on the iterator to help get data out of the data structure (or put data into it).
get_cell_index is an example function where I am trying to do that.
I'm having trouble getting the Iterator impl working:

struct FluidSimIterator<'a> {
    fluid_sim: &'a FluidSim,
    ix: usize,
    iy: usize,
    skip_empty_buckets: bool
}

impl FluidSimIterator<'_> {
    pub fn get_cell_index(&self) -> usize {
        return self.ix + (self.fluid_sim.bucket_size * self.iy);
    }
}

impl FluidSim {
    pub fn iter(&self) -> FluidSimIterator {
        FluidSimIterator{
            fluid_sim: self,
            ix: 0,
            iy: 0,
            skip_empty_buckets: true
        }
    }
}

impl<'a> Iterator for FluidSimIterator<'a> {
    type Item = &'a mut FluidSimIterator<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        self.ix += 1;
        Some(self)
    }
}

The errors I am seeing are:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
   --> physics/src/fluid_sim.rs:666:9
    |
666 |         Some(self)
    |         ^^^^^^^^^^
    |
note: first, the lifetime cannot outlive the anonymous lifetime defined here...
   --> physics/src/fluid_sim.rs:664:13
    |
664 |     fn next(&mut self) -> Option<Self::Item> {
    |             ^^^^^^^^^
note: ...so that reference does not outlive borrowed content
   --> physics/src/fluid_sim.rs:666:14
    |
666 |         Some(self)
    |              ^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined here...
   --> physics/src/fluid_sim.rs:661:6
    |
661 | impl<'a> Iterator for FluidSimIterator<'a> {
    |      ^^
note: ...so that the types are compatible
   --> physics/src/fluid_sim.rs:664:46
    |
664 |       fn next(&mut self) -> Option<Self::Item> {
    |  ______________________________________________^
665 | |         self.ix += 1;
666 | |         Some(self)
667 | |     }
    | |_____^
    = note: expected `<FluidSimIterator<'a> as Iterator>`
               found `<FluidSimIterator<'_> as Iterator>`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0495`.

full source code is here: https://github.com/bit-shift-io/fluidic-space/blob/main/crates/physics/src/fluid_sim.rs
with this above snippet right at the bottom of the file.
Seems it is something to do with lifetimes which I am still wrapping my head around. SO not exactly sure what the error is saying or how to resolve it.
EDIT:
I managed to get working how I want it to, although I'm not sure how 'ideal' the solution is:

pub struct Iter<'a> {
    pub fluid_sim: &'a FluidSim,
    pub ix: isize,
    pub iy: isize
}

impl<'a> Iterator for Iter<'a> {
    type Item = Iter<'a>; //Cell<'a>; //&'a Cell;

    fn next(&mut self) -> Option<Self::Item> {
        self.ix += 1;
        if self.ix >= self.fluid_sim.x_size as isize {
            self.iy += 1;
            if self.iy >= self.fluid_sim.y_size as isize {
                return None
            }

            self.ix = 0;
        }

        let dup = Iter{
            fluid_sim: self.fluid_sim,
            ix: self.ix,
            iy: self.iy
        };
        Some(dup)
    }
}

impl FluidSim {
    pub fn iter(&self) -> Iter {
        Iter {
            fluid_sim: &self,
            ix: -1,
            iy: 0
        }
    }
}

And a basic example of the usage looks like:
let mut h1 = FluidSim::new(3, 3);

for cell in h1.iter() {
        println!("x: {:?}, y: {:?}", cell.ix, cell.iy)
}

gives me the following output:
x: 0, y: 0
x: 1, y: 0
x: 2, y: 0
x: 3, y: 0
x: 0, y: 1
x: 1, y: 1
x: 2, y: 1
x: 3, y: 1
x: 0, y: 2
x: 1, y: 2
x: 2, y: 2
x: 3, y: 2
x: 0, y: 3
x: 1, y: 3
x: 2, y: 3
x: 3, y: 3

So I can now add other functions on my Iter struct to read and write into the correct cell of my fluid_sim struct.


text:
Q: replace char in specific pattern or after specific character The task at hand is to replace "-" with "/" in a birthday format e.g. 03-12-89 -> 03/12/89. However, the "-" must be able to appear elsewhere in the string e.g. "My-birthday-is-on-the: 03/12/89".
I have tried creating substrings, replace the "-" in the birthday part and then combine the strings again. However, that solution is inflexible and fails the testcases.
I'm thinking I must be able to do this with a regular expression, although I seem unable to construct it. So now I'm back to: String newStr = input.replace("-", "/"); Which remove all instances of "-" which I don't want.
Can anyone help?

A: You can use the following regex:
(?<=\d{2})-

with replacement \/ (no need to escape it in Java)
INPUT:
My-birthday-is-on-the: 03-12-89

OUTPUT:
My-birthday-is-on-the: 03/12/89

demo
Code:
String input = "My-birthday-is-on-the: 03-12-89";
System.out.println(input.replaceAll("(?<=\\d{2})-", "/"));

OUTPUT:
My-birthday-is-on-the: 03/12/89

A: The easiest way which comes to mind is just match \d{2}-\d{2}-\d{2}, with capture groups.  Then, use those captured numbers to rebuild the birthdate the way you want it.  Something like this:
String input = "My-birthday-is-on-the: 03/12/89";
input = input.replaceAll("\\b(\\d{2})-(\\d{2})-(\\d{2})\\b", "$1/$2/$3");

Demo
The advantage of specifying the full pattern is that it avoids the chance of matching anything other than a 6 digit dash-separated birthday.
Edit:
Based on your comment below, it sounds like maybe you want to do this replacement on a two dash separated number, with any number of digits.  In this case, we can slightly modify the above code to the following:
String input = "Your policy number is: 123-45-6789.";
input = input.replaceAll("\\b(\\d+)-(\\d+)-(\\d+)\\b", "$1/$2/$3");


text:
Q: Adding higher-level operator to grammar I am working through Stroustrups Programming Principles and Practice using c++. There is this grammar that he uses in building a calculator through the first few chapters of the book. One of the exercises is to add a factorial operator to the calculator. He gives a hint

Begin by modifying the grammar to account for a higher-level operator

What is a higher-level operator? (unfortunately he hasn't explained it up to that chapter in the book and I don't know if its even been explained in other chapters)
The grammar he is asking to be modified is this:
Expression:
    Term
    Expression "+" Term
    Expression "-" Term
Term:
    Primary
    Term "*" Primary
    Term "/" Primary
    Term "%" Primary
Primary:
    Number
    "(" Expression ")"
Number:
    floating-point-literal

I have grappled with this for a whole day now and I'm getting nowhere. Will be glad for some explanation.

A: A higher-level operator is an operator which has a greater precedence than others.
This can be added to your grammar the same way the multiplication, divisions, and modulo differ from the addition and soustraction.
In other words, your parser should first attempt to parse factorial syntax, then multiplication, then addition


text:
Q: Colorize an image for overlay I want to show an image from a bottle, filled with liquids in various colors. The colors exists as a RGB HEX code. So, showBottle('#ff0000') should show the bottle, filled with red water. My idea is to create two images: The bottle (empty), and another with just the liquid in white. These two images can then be put over another, so I can only colorize the "liquid part".
My questions:

*

*Is it possible to "colorize" an image in Flutter?

*What is the best way to get both images overlay each other?

EDIT:
I've tried to use the Stack widget and two Image widgets with the colorBlendMode, but the transparency does not work. See the image below:
Stack(children: <Widget>[
  Image.asset(
    'assets/images/background.png',
  ),
  Image.asset(
    'assets/images/overlay.png',
    colorBlendMode: BlendMode.color,
    color: Color.fromRGBO(255, 0, 0, 1.0),
  ),
])

Changing the BlendMode to srcIn will result in taking the transparency into account, but drops all information from the overlay.png image.

A: use image blend mode and color.
here is example,
Image.asset(
  'assets/image.jpg',
  height: 300,
  fit: BoxFit.fitHeight,
  color: _color, // Colors.red, Colors.yellow any color you want
  colorBlendMode: _blendMode, // BlendMode.color, BlendMode.darken, BlendMode.saturation, BlendMode.softLight
)

check Image widget and its properties


text: Q: Can I use the autocorrelation function on non-stationary time series? First of all I apologize because I don't have a lot of knowledge in the field.  I would like to know if it is possible to use the ACF function in R to find the autocorrelation coefficient with a lag of 1 despite the fact that the time series is not stationary?


text:
Q: 555 timer based cyclic LED fading circuit problem I have the below circuit with...
R1 100 Ohm
R2 10k Ohm potentiometer
R3 10k Ohm potentiometer
R4 100k Ohm
R5 4.7k Ohm
R6 47 Ohm
C1 470 uF
D1 1N4148
D2 1N4148
T1 BC337 NPN
T2 2N2222 NPN
IC1 555 timer
LED1 white, 25mA, 3.4V

...but no cyclic LED fading; on power up, it lights up and then fades out exactly once. However, when I wire the input of D2 to the 555's pin 3, I obtain cyclic "flashes" that I can adjust with the two potentiometers. What could be the problem here? Thanks!

A: I suspect that when power is applied C1 charges which fades out the LED but the voltage on C1 never reaches 2/3 of Vcc due to the potential divider formed by R1, R2, D1, D2, R4 and the base-emitter junction of T1. So the circuit just sits there with no further rise of C1's voltage.
You could try increasing the value of R4 to try and get C1's voltage to rise further but don't increase R4 so much that T1 has insufficient base current.

A: T1 (thanks for the reference designators!) is wired as a switch rather than as a linear amplifier or buffer.  As such, it is "converting" the capacitor's voltage ramp into a very rapid ramp that looks like a switch to the eye.
I don't see any reason for D2, and in fact I think it hurts what you are trying to achieve.  I recommend:

*

*Eliminate D2.  Connect the left side of R2 directly to pin 2.

*Disconnect the T1 emitter from GND.

*Disconnect the T2 base from the T1 collector.

*Connect the T2 base to the T1 emitter.
This turns the T1-T2 transistors into a Darlington pair, a current amplifier that maintains the input voltage wave shape.  BUT -
The circuit probably will not run well on 5 V.  The capacitor voltage ramps up and down between 1.67 V and 3.33 V.  3.33 V minus two Vbe forward voltage drops does not leave much to run the LED.  You might have to adjust R6 to see anything happen.  A simple thing to try is to run the circuit on 9 V or 12 V.
The problem is the high impedance and relatively small voltage change across the timing capacitor.  A common way around this is to add a second R-C network at the 555 output (pin 3) and connect the darlington pair to that.


text:
Q: How to SendDataToServer? Condition: I've a button. When user click the button (example ADD NEW NAME button) so the data will send to server.
I've question: How to add new data to server?
What should I put into onResponse and onFailure based on this code:
 private void sendDataToServer() {
    APIClient client = ServiceGenerator.createService(APIClient.class);
    Call<ResponseBody> result = client.addNewName(etName.getText().toString(),
            etEnglish.getText().toString(),
            etGender.getText().toString());

    result.enqueue(new Callback<ResponseBody>() {

        @Override
        public void onResponse(Response<ResponseBody> response) {

        }

        @Override
        public void onFailure(Throwable t) {

            }
        }

    );}

*et - Edit Text
Thanks.


text:
Q: How to wrap columns two and two inside of a loop? I'm trying to wrap two columns inside of a row div from inside a php loop.
I came up with this test but it fails no matter what I do.. This is the closest I can come, I can't see where this logic fails.
Take a look:
<?php $i = 0; ?>
<?php while($i < 11) : ?>

  <?php if ($i % 2 === 0) : ?>

row

  <?php endif; ?>

  <?php echo "[" . $i . "]"; ?>

  <?php if (!$i % 2 === 0) : ?>

     /row

  <?php endif; ?>

  <?php $i++; ?>
<?php endwhile; ?>

The produced result:
row [0] [1] /row
row [2] /row
[3] /row
row [4] /row
[5] /row
row [6] /row
[7] /row
row [8] /row
[9] /row
row [10] /row

Here we can see that the first row is working great but then it becomes flawed somewhere in the logic, question is where?

A: Made a little changes to your code.
  <?php $i = 0;
       while($i <= 11) :
       if($i%2==0){
        echo '
 Row';
       }
         echo "[" . $i . "]";

       if($i%2!=0){
        echo " row
";
       }
       $i++;
     endwhile; ?>

It will output
 Row[0][1] row
 Row[2][3] row
 Row[4][5] row
 Row[6][7] row
 Row[8][9] row
 Row[10][11] row

A: Used another counter for columns.
Tested and seems to work: http://sandbox.onlinephpfunctions.com/code/7374de00caef8a3f6b89a6196093326e8133c021
$col = 0;
for($i = 0; $i < 11; $i++){
  if($i % 2 == 0){
    echo '
';
  }

  echo "[".$i."]";
  $col++;

  if($col == 2){
    echo "
";
    $opened = false;
    $col = 0;
  }

}

A: Something like this:
<?php
  $count = 14;
  for($i = 0; $i <= $count; $i += 2) {
    if ($i % 2 == 0) {
       echo('row ');
    }

    echo('['.$i.']');
    if ($i < $count) {
      echo('['.($i+1).']');
    }

    if ($i % 2 == 0) {
       echo(' /row ');
    }
  }
?>

Result:
row [0][1] /row
row [2][3] /row
row [4][5] /row
row [6][7] /row
row [8][9] /row
row [10][11] /row
row [12][13] /row
row [14] /row

A: Try this

<?php

$i = 0;
while ($i < 11) :
$row = $i % 2 === 0;
?>

    <?php if ($row): ?>
<?php endif;?>
    <?php echo '[' . $i . ']'; ?>
    <?php if (!$row): ?>
<?php endif;?>

<?php
    $i++;
endwhile; ?>

output:


text:
Q: Converting mp4 to mp3 with ffmpeg fails with: Unable to find a suitable output format for '\ffmpeg' I want to convert a church service mp4 video into a mp3 soundtrack.
I found ffmpeg and I tried a lot of syntax. Even the easiest didin't work.
ffmpeg -i 2026857739212839680.mp4 output_file.mp3

From other articels I found that this should be the most best match to what I want to do.
But again the failure.
What am I doing wrong?
ffmpeg -i 2026857739212839680.mp4 -vn -b:a 128k -c:a libmp3lame output_file.mp3

Here the output:
    Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '2026857739212839680.mp4':
      Metadata:
        major_brand     : isom
        minor_version   : 512
        compatible_brands: isomiso2avc1mp41
        encoder         : Lavf58.29.100
      Duration: 00:22:18.94, start: 0.000000, bitrate: 2916 kb/s
        Stream #0:0(eng): Video: h264 (Baseline) (avc1 / 0x31637661), yuv420p, 1920x1080, 2849 kb/s, 29.76 fps, 29.85 tbr, 90k tbn, 180k tbc (default)
        Metadata:
          handler_name    : VSH264 stream handler
        Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 16000 Hz, mono, fltp, 63 kb/s (default)
        Metadata:
          handler_name    : AAC stream handler
      [NULL @ 000002ad5c2b00c0] Unable to find a suitable output format for '\ffmpeg'
\ffmpeg: Invalid argument


text:
Q: How does the Teamviewer Android App gets the screen in a project I want to send the screen of my Android device to a remote service. There are some possibilities how to do that. For example copy the grafic memory (root required) or get the current bitmap of my app.
Anyway either I need root rights or I only get the screen of my own App. I saw that the Teamviewer app does something like that too.
At the end my question. How?

A: I think you can just make a screenshot, send it to the other phone(or to a server). Make a screenshot 2x a second, and I think it will look fine. If you really want to know how Teamviewer does it, you have to decompile the .apk file(ofcourse, at your own risk).


text:
Q: Expand variables in upstart script I have written several upstart scripts to start transmission-daemon for several users. The script is this:
start on (local-filesystems and net-device-up IFACE=eth0 and runlevel [235])
stop on runlevel [016]

kill timeout 50

respawn

env USER=user
env PIDFILE=/var/run/transmission-user.pid

script
    DAEMON=$(which transmission-daemon) || exit 0
    CONFIGDIR=/home/$USER/.config/transmission-daemon

    exec start-stop-daemon --start --quiet --chuid $USER --pidfile $PIDFILE --make-pidfile --exec $DAEMON -- -f --config-dir $CONFIGDIR --logfile $CONFIGDIR/daemon.log
end script

post-stop exec rm -f $PIDFILE

I would convert this:
env USER=user
env PIDFILE=/var/run/transmission-user.pid

To this:
env USER=user
env PIDFILE=/var/run/transmission-$USER.pid

But upstart doesn't allow.
I can do it if I move those lines to the script section:
script
    USER=user
    PIDFILE=/var/run/transmission-$USER.pid
    ...
end script

But in this case, the PIDFILE, in post-stop section, is empty.
Is there any way to do this?

A: This is a fairly old bug in upstart:
https://bugs.launchpad.net/upstart/+bug/328366
To get the variable in post-stop and script... you'll just have to set it both times to work around the bug.


text:
Q: How to use separate() properly? I have some difficulties to extract an ID in the form:
27da12ce-85fe-3f28-92f9-e5235a5cf6ac

from a data frame:
a<-c("NAME_27da12ce-85fe-3f28-92f9-e5235a5cf6ac_THOMAS_MYR",
        "NAME_94773a8c-b71d-3be6-b57e-db9d8740bb98_THIMO",
         "NAME_1ed571b4-1aef-3fe2-8f85-b757da2436ee_ALEX",
         "NAME_9fbeda37-0e4f-37aa-86ef-11f907812397_JOHN_TYA",
         "NAME_83ef784f-3128-35a1-8ff9-daab1c5f944b_BISHOP",
         "NAME_39de28ca-5eca-3e6c-b5ea-5b82784cc6f4_DUE_TO",
         "NAME_0a52a024-9305-3bf1-a0a6-84b009cc5af4_WIS_MICHAL",
         "NAME_2520ebbb-7900-32c9-9f2d-178cf04f7efc_Sarah_Lu_Van_Gar/Thomas")

Basically its the thing between the first and the second underscore.
Usually I approach that by:
library(tidyr)
df$a<-as.character(df$a)
df<-df[grep("_", df$a), ]
df<- separate(df, a, c("ID","Name") , sep = "_")
df$a<-as.numeric(df$ID)

However this time there a to many underscores...and my approach fails. Is there a way to extract that ID?

A: I think you should use extract instead of separate. You need to specify the patterns which you want to capture. I'm assuming here that ID is always starts with a number so I'm capturing everything after the first number until the next _ and then everything after it
df <- data.frame(a)
df <- df[grep("_", df$a),, drop = FALSE]
extract(df, a, c("ID", "NAME"), "[A-Za-z].*?(\\d.*?)_(.*)")
#                                     ID                    NAME
# 1 27da12ce-85fe-3f28-92f9-e5235a5cf6ac              THOMAS_MYR
# 2 94773a8c-b71d-3be6-b57e-db9d8740bb98                   THIMO
# 3 1ed571b4-1aef-3fe2-8f85-b757da2436ee                    ALEX
# 4 9fbeda37-0e4f-37aa-86ef-11f907812397                JOHN_TYA
# 5 83ef784f-3128-35a1-8ff9-daab1c5f944b                  BISHOP
# 6 39de28ca-5eca-3e6c-b5ea-5b82784cc6f4                  DUE_TO
# 7 0a52a024-9305-3bf1-a0a6-84b009cc5af4              WIS_MICHAL
# 8 2520ebbb-7900-32c9-9f2d-178cf04f7efc Sarah_Lu_Van_Gar/Thomas

A: try this (which assumes that the ID is always the part after the first unerscore):
sapply(strsplit(a, "_"), function(x) x[[2]])

which gives you "the middle part" which is your ID:
[1] "27da12ce-85fe-3f28-92f9-e5235a5cf6ac" "94773a8c-b71d-3be6-b57e-db9d8740bb98"
[3] "1ed571b4-1aef-3fe2-8f85-b757da2436ee" "9fbeda37-0e4f-37aa-86ef-11f907812397"
[5] "83ef784f-3128-35a1-8ff9-daab1c5f944b" "39de28ca-5eca-3e6c-b5ea-5b82784cc6f4"
[7] "0a52a024-9305-3bf1-a0a6-84b009cc5af4" "2520ebbb-7900-32c9-9f2d-178cf04f7efc"

if you want to get the Name as well a simple solution would be (which assumes that the Name is always after the second underscore):
Names <- sapply(strsplit(a, "_"), function(x) Reduce(paste, x[-c(1,2)]))

which gives you this:
[1] "THOMAS MYR"              "THIMO"                   "ALEX"                    "JOHN TYA"
[5] "BISHOP"                  "DUE TO"                  "WIS MICHAL"              "Sarah Lu Van Gar/Thomas"


text:
Q: How to prevent Viewstate tampering in AngularJS? This is an Interview Question I was asked today -_-. I dont understand the question actually, because I dont understand how anything can be tampered in the scenario. He asked this when I was talking about using AJAX with $http.

A: Let me divide the question
0 : Prevent 1 : viewstate 2 : tempering 3 : in angularjs
Viewstate tampering in AngularJS :
Might be a normal customer action (form or view) in angularjs
where user tries to ( temper or change or edit) the form
and now how will we come to know the (state or change) of (form or view or viewstate)has changed
Now here comes dirty tracking concept .
In Angular there are couple of ways for that.
So for (Preventing or knowing the changes we can use) $digest or $watch in angular
And
$http : dosen't knows any thing about dirty tracking he just sends or brings data


text:
Q: Understanding Qemu address translations This is my setup:
Inside a vm, in userspace program, I store a variable with value "8" at address bf9ee1a0.
I get a physical address of ff9ee1a0 corresponding to the address when I call virt_to_phys function in kernel space inside vm.
On the qemu, pte and pte_addr are a5913865 and bf955f78 respectively.I just used the x86_cpu_handle_mmu_fault function and added certain printf statements.
My understanding was the mapping that the os and the qemu has should be same. i.e. bf9ee1a0 should be mapped to a5913865.
I know there are many levels of translations involved here. Guest virtual — Guest physical — Host virtual.
Here is my questions:
1. I wanted to know where is the data actually stored?

*What does the virt_to_phys() then mean?

*I made sure that the address used in control registers are the same in both os inside vm and in qemu for paging. Then why is this discrepency?

*If one needs to print the contents of the page that pte has in qemu, how does one use printf statements to print them?
Any insight is greatly appreciated.


text:
Q: Краш приложения на андроид android studio ListView listView1;

    String [] Title = {"one","two","four","five"};

    int[] imgid = {R.drawable.dela, R.drawable.gnev, R.drawable.psy};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        listView1 = (ListView)findViewById(R.id.listview1);

        CustomAdapter customAdapter = new CustomAdapter();

        listView1.setAdapter(customAdapter);

        }

    class CustomAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return imgid.length;
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            View view1 = getLayoutInflater().inflate( R.layout.title,null);

            ImageView imageView2 = (ImageView)findViewById(R.id.imageView2);
            TextView textView = (TextView)findViewById(R.id.textView1);

            imageView2.setImageResource(imgid[i]);
            textView.setText(Title[i]);

            return view1;
        }
    }
}

A: Ваш адаптер определён в классе активити, засим строка

ImageView imageView2 = (ImageView)findViewById(R.id.imageView2);

расшифровывается компилятором в
ImageView imageView2 = (ImageView)ActivityClassName.this.findViewById(R.id.imageView2);

т.е. вы ищите ImageView в разметке активити, а не разметке элемента списка. Так происходит потому, что компилятор видит метод findViewById и сначала пытается его найти в классе адаптера. Но у него такого метода нет. Засим компилятор ищет в обрамляющем классе этот метод. Находит его, вызывает на экземпляре этого класса, но вьюху там не находит, она становится null, после чего вы и получаете NPE. Вы бы избежали этого, если бы описали ваш адаптер в отдельном классе, как и следует делать, если вы пишите реальное приложение, а не разбираете пример.
Вам надо искать вашу вьюху в разметке элемента списка, вызывая метод на ней так:
ImageView imageView2 = (ImageView) view1.findViewById(R.id.imageView2);

Также, советую переходить на RecyclerView -  современную версию ListView.


text:
Q: VS Code, Python, Intellisense and import module as VS Code and Python Intellisense does not function when I import a "module as" such as:
import multiprocessing as mp
import cv2
import cv2.aruco as aruco

I get intellisense clues when typing
cv2.aruco.***

I do not get clues when typing
aruco.***

Has anyone else experienced this before? Any way to solve this?

A: It works for me with the following code:
import importlib.abc as i_abc
i_abc.

You can also solve this by changing your import statement to from cv2 import aruco.


text:
Q: Unable install cmake and ccmake? So the thing is I'm trying to install Cmake and cmake-curses-gui.
I have updated the system with apt-get-update.

sudo apt-get install cmake
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package cmake is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'cmake' has no installation candidate

sudo apt-get install cmake-curses-gui
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package cmake-curses-gui

That's strange. Can anyone give some pointers?
Pastbin sources.list :- http://pastebin.com/DufycYfZ


text:
Q: Why does (boolean ^ int > 0) work? When you try to do something like this:
if (true ^ 1) {
  //do something
}

the compiler reasonably says that operator ^ is not defined for argument types boolean and int.
But if you use it like this:
if (true ^ 1 > 0) {
  //do something
}

the code compiles (for Java 8 at least) and flawlessly works.
Basically these operations:
false ^ -1 > 0
false ^ 1 > 0
true ^ -1 > 0
true ^ 1 > 0

Act like a valid logical XOR:
     | ^
-----+--
 F F | F
 F T | T
 T F | T
 T T | F

Could anybody please explain what happens under the hood?

A: It's simple: > has higher precedence than ^, so
if (true ^ 1 > 0) {

is equivalent to
if (true ^ (1 > 0)) {

which is equivalent to
if (true ^ true)

... which is just logical XOR.
I would never write code like this, mind you. I would be surprised to see an example which couldn't be written more clearly in a different way.

A: Because order (priority) of operations is important, > has higher priority than ^
Here, first we check 1 > 0 and then first operation is XORed (^) with first result
Is equivalent to if(true ^ (1 > 0 ))
But, of course You can't XORed boolean with int

A: Because operation > has higher priority than ^, so it is equivalent to true ^ (1>0) which is operating with same types (boolean ^ boolean).

A: 1 is of type int.
1 > 0 is of type boolean.
^ means XOR; and you can't XOR boolean and int.
In other words: the first expression "1" evaluates to a number; the second expression "1> 0" evaluates to boolean logic. The reason behind that is the operator predecence.


text:
Q: Type 'number[]' cannot be used as an index type const groupAnagrams = (arr: string[]) => {
    const hash: { [key: number]: string[] } = {};

    arr.forEach((str) => {
        // Here you can see count type
        const count: number[] = Array(26).fill(0);

        for (let char of str) {
            count[char.charCodeAt(0) - "a".charCodeAt(0)] += 1;
        }

        if (hash[count]) {
            hash[count] = hash[count].concat(str);
        } else {
            hash[count] = [str];
        }
    });

    return Object.entries(hash).map(([_, arr]) => arr);
};

In the code snippet above, you can see where I want to use number array as a string, and TypeScript has other plans on this. When you assign array as an object key, it implicitly convert it to string [1,2,3] => '1,2,3'. How can I make it work, without assigning to count any?


text:
Q: Regex - Match string before a character using regex in Sublime Text. I'd like to find all characters before a tab (\t). The string:
Peace love and happiness    2

Would return:
Peace love and happiness

I'm essentially doing this to nuke the first column in a tab-seperated document (.tsv). There is probably a better way to delete tab-seperated columns in Sublime Text, but I haven't found it.

A: I don't know if Sublime has any particularly special regex rules, but it should be:
(.*)(?:\t)


text:
Q: Determining if $R=\mathbb{Z}[x]/(x^2)$ is a local ring or not I was trying to use the following result which says: if $I$ is a ideal of $R$ such that $R\setminus I$ is the set of all units of $R$ then $I$ is the only maximal ideal of $R$.
I showed that the units of $R$ are $\overline{ aX+1 }$ where $a \in \mathbb{Z}$ but it seems that the complement of the preceding set isn't an ideal. So, it looks to me as if $R$ is not a local ring.
I wasn't able to prove my claim. Can someone drop some hints? Thanks in advance.

A: For any prime $p$, you can readily find a homomorphism $R\to \Bbb F_p$


text:
Q: Why to test while we are using interface in typescript? I am pretty new to testing. So, I don't understand why to use testing while we can make use of the interface.
What interface does is almost similar to testing. So do we need to test the code of an interface itself?
Here is a code of an interface, please suggest how should I test it.
interface boardMeeting{
    get_team(): Team;
    get_partner(): Partner;
    get_secretary(): Secretary;
}

Thank YOU.