问:
A script to toggle WiFi in MacOS
I'm trying to write a script that toggles WiFi on or off.

I'm having trouble with the "if" statement. I'm starting with a simple script that should tell you if Wifi is on or off. It doesn't work as written. I get "Wifi is off" no matter what the WiFi status is

```<code>#!/bin/sh
STATUS=`networksetup -getairportpower en0`
if $STATUS == On
then
   echo "Wifi is on"
else
    echo "Wifi is off"
fi
</code>```

答:
The text value from networksetup is not just "On" it is (on my machine) "Wi-Fi Power (en0): On".  Therefore we need to take into account the text before "On", which we can do with a glob pattern, the asterisk (*) means "zero or more of any character".  For that we need the double [[ command in our if statement:

```<code>#!/bin/bash
status=$(networksetup -getairportpower en0)
if [[ $status == *On ]]
then
    echo "Wifi is on"
else
    echo "Wifi is off"
fi
</code>```

Other notes:  I used #!/bin/bash, rather than sh.  sh is a POSIX shell, which is (arguably) a subset of bash.  If you want bash then you should specify it on the #! line, not sh.

I used the $( ) notation rather than back-ticks ( `` ).  Back-ticks are considered deprecated and difficult to read.

Note the spaces around and within [[ and ]], they are required.

I have replaced STATUS with status.  This is because there are many uppercase variable names used by the shell so using uppercase risks a name collision.  Best to use lower or mixed-case variable names.

Title: A script to toggle WiFi in MacOS

Body:
I'm trying to write a script that toggles WiFi on or off.

I'm having trouble with the "if" statement. I'm starting with a simple script that should tell you if Wifi is on or off. It doesn't work as written. I get "Wifi is off" no matter what the WiFi status is

#!/bin/sh
STATUS=`networksetup -getairportpower en0`
if $STATUS == On
then
   echo "Wifi is on"
else
    echo "Wifi is off"
fi

Body:
The text value from networksetup is not just "On" it is (on my machine) "Wi-Fi Power (en0): On".  Therefore we need to take into account the text before "On", which we can do with a glob pattern, the asterisk (*) means "zero or more of any character".  For that we need the double [[ command in our if statement:

#!/bin/bash
status=$(networksetup -getairportpower en0)
if [[ $status == *On ]]
then
    echo "Wifi is on"
else
    echo "Wifi is off"
fi

Other notes:  I used #!/bin/bash, rather than sh.  sh is a POSIX shell, which is (arguably) a subset of bash.  If you want bash then you should specify it on the #! line, not sh.

I used the $( ) notation rather than back-ticks ( `` ).  Back-ticks are considered deprecated and difficult to read.

Note the spaces around and within [[ and ]], they are required.

I have replaced STATUS with status.  This is because there are many uppercase variable names used by the shell so using uppercase risks a name collision.  Best to use lower or mixed-case variable names.


来源: stackexchange

问:
Android: Specifying a literal '@'?
Is there a way to set some attribute to the character '@' ?

i.e. explicitly not referencing any resource, just want the '@' sign?

答:
Figured it out... just prefix it with \ i.e.:

```<code><Button android:text="\@" />
</code>```

It seems the character '?' requires escaping as well.

ContentLicense: CC BY-SA 2.5

Title: Android: Specifying a literal '@'?

Body:
Figured it out... just prefix it with \ i.e.:

<Button android:text="\@" />

It seems the character '?' requires escaping as well.


问:
How do I load multiple XML nodes with two attributes as key-value pairs?
I have a XML file which is like this;

```<code><?xml version="1.0" encoding="utf-8"?>
<Data>
  <StringMaps>
    <Menu>
      <String Target="BtnFile" Link="Файл" />
      <String Target="BtnOpen" Link="Открыто" />
      <String Target="BtnSave" Link="Сохранить" />
      <String Target="BtnClose" Link="Закрыть" />
    </Menu>
  </StringMaps>
</Data>
</code>```

and I load document using XmlDocument.

And then I have two XmlNodeList which are targetAttrs and linkAttrs.

I'm using this code to get the values;

```<code>        var targetAttrs = xmldoc1.SelectNodes("/Data/StringMaps/Menu/String/@Target");
        var linkAttrs = xmldoc1.SelectNodes("/Data/StringMaps/Menu/String/@Link");
        foreach (XmlNode temptarget in targetAttrs)
        {
            foreach (XmlNode templink in linkAttrs)
            {
                MessageBox.Show(string.Format("{0} = {1}", temptarget.Value, templink.Value));
            }
        }
</code>```

I'm trying to get values as key-value pairs like these;

```<code>BtnFile = Файл
BtnOpen = Открыто
BtnSave = Сохранить
BtnClose = Закрыть
</code>```

But I get these;

```<code>BtnFile = Файл
BtnFile = Открыто
BtnFile = Сохранить
BtnFile = Закрыть
BtnOpen = Файл
BtnOpen = Открыто
BtnOpen = Сохранить
BtnOpen = Закрыть
BtnSave = Файл
BtnSave = Открыто
BtnSave = Сохранить
BtnSave = Закрыть
BtnClose = Файл
BtnClose = Открыто
BtnClose = Сохранить
BtnClose = Закрыть
</code>```

If someone writes the code and explains the exact logic, i would be very appreciated.

答:
The attributes you want belong to the same XMLNode.
Your outer loops finds the elements.
Then your inner loops looks for the same nodes to display the second attribute.

Search for the Nodes once and display both attributes.

```<code>        var MenuItems =xmldoc1.SelectNodes("/Data/StringMaps/Menu/String");

        foreach(XmlNode MenuItem in MenuItems)
        {
             MessageBox.Show(string.Format("{0} ={1}",MenuItem.Attributes["Target"].Value, MenuItem.Attributes["Link"].Value));

        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a XML file which is like this;

<?xml version="1.0" encoding="utf-8"?>
<Data>
  <StringMaps>
    <Menu>
      <String Target="BtnFile" Link="Файл" />
      <String Target="BtnOpen" Link="Открыто" />
      <String Target="BtnSave" Link="Сохранить" />
      <String Target="BtnClose" Link="Закрыть" />
    </Menu>
  </StringMaps>
</Data>

and I load document using XmlDocument.

And then I have two XmlNodeList which are targetAttrs and linkAttrs.

I'm using this code to get the values;

        var targetAttrs = xmldoc1.SelectNodes("/Data/StringMaps/Menu/String/@Target");
        var linkAttrs = xmldoc1.SelectNodes("/Data/StringMaps/Menu/String/@Link");
        foreach (XmlNode temptarget in targetAttrs)
        {
            foreach (XmlNode templink in linkAttrs)
            {
                MessageBox.Show(string.Format("{0} = {1}", temptarget.Value, templink.Value));
            }
        }

I'm trying to get values as key-value pairs like these;

BtnFile = Файл
BtnOpen = Открыто
BtnSave = Сохранить
BtnClose = Закрыть

But I get these;

BtnFile = Файл
BtnFile = Открыто
BtnFile = Сохранить
BtnFile = Закрыть
BtnOpen = Файл
BtnOpen = Открыто
BtnOpen = Сохранить
BtnOpen = Закрыть
BtnSave = Файл
BtnSave = Открыто
BtnSave = Сохранить
BtnSave = Закрыть
BtnClose = Файл
BtnClose = Открыто
BtnClose = Сохранить
BtnClose = Закрыть

If someone writes the code and explains the exact logic, i would be very appreciated.

Body:
The attributes you want belong to the same XMLNode.
Your outer loops finds the elements.
Then your inner loops looks for the same nodes to display the second attribute.

Search for the Nodes once and display both attributes.

        var MenuItems =xmldoc1.SelectNodes("/Data/StringMaps/Menu/String");

        foreach(XmlNode MenuItem in MenuItems)
        {
             MessageBox.Show(string.Format("{0} ={1}",MenuItem.Attributes["Target"].Value, MenuItem.Attributes["Link"].Value));

        }


问:
Regex with nested group and dot causes wacky matching
I cannot understand why the following regex and text yield their results. I am using the regex find function in notepad++ with no Wrap_around and no matching newline. The regex:

```<code>name ="[\w]+\.((?:[\w]*\.?)+)" p
</code>```

when applied to the text:

name ="data.messageHeader.msg_time_tag.$date" pzb

this is line 2

The entire text ends up highlighted, which should be impossible, since the regex should not be able to match the dollar sign or the newline/carriage return.

I have also tried applying the regex to the text with python 're'. In this case, I parsed the full file line by line. Initially, python correctly did not match the lines with dollar signs, but those lines would take a few seconds to finish even though they were only about 100 characters. By the fourth or fifth line that contained the structure of my sample, where the dot-separated words contained a '$', python froze up until I manually stopped it.

The python code used:

```<code>import re
def main():
    pattern = re.compile(r"name =\"\w+\.((?:\w+\.?)+)\" p")
    with open(r"filepath", "r") as f:
        i = 0
        for line in f:
            match = pattern.search(line)
            if (match):
                print('<Match: %r, groups=%r>' % (match.group(), match.groups()))
            else:
                print("line %d nomatch" % (i))
            i+=1
            match = None
            #it = pattern.finditer(f.read())
            #for element in it:
                #displaymatch(element)

def displaymatch(match):
    if match is None:
        return None
    print('<Match: %r, groups=%r>' % (match.group(), match.groups()))
main()
</code>```

Can you explain why this is happening?

答:
Since you want to know why your pattern doesn't work, here's a breakdown of it:

```<code>name ="        - capture a literal string: `name ="`

\w+            - ... followed by one or more word characters (A-Za-z0-9_)

\.             - ... followed by a literal dot

(              - start a capturing group (following matches will be captured as a group)

    (?:        - start a non-capturing group

        \w+    - match one or more word characters (A-Za-z0-9_)
        \.?    - ... optionally followed by a literal dot

    )+         - match as many of these non-capturing groups as possible

)              - close the group, nothing is captured as there is no capturing pattern in it

" p            - followed by a literal string: `" p`
</code>```

Think of a string like:  name ="data.messageHeader.msg_time_tag.$date" pzb
. If you execute the above pattern on it you'll easily capture your name ="data. part and that's when the fun starts - nevermind the outer group, the problem is with the inner group and the + qualifier behind it - it will match the first messageHeader., then it will capture msg_time_tag. and so on until it encounters a quote character... However, since $date doesn't fit the inner pattern, it moves back to the previous match (backtracks) which is messageHeader. and tries again - only to encounter the same issue, and to backtrack again... And again... And again... Eventually shutting the engine and causing non-predictable behavior.

How will the regex engine choose to deal with this depends on the implementation - the most proper way would be to raise an infinite/catastrophic backtracking error (as the search head doesn't move despite the matches and the pattern doesn't provide a resolution), but it might just fail by capturing nothing or capturing everything...

The bottom line is - if you write proper regex pattern, the regex engine will act predictably. If not - anything goes.

Body:
I cannot understand why the following regex and text yield their results. I am using the regex find function in notepad++ with no Wrap_around and no matching newline. The regex:

name ="[\w]+\.((?:[\w]*\.?)+)" p

when applied to the text:

name ="data.messageHeader.msg_time_tag.$date" pzb

this is line 2

The entire text ends up highlighted, which should be impossible, since the regex should not be able to match the dollar sign or the newline/carriage return.

I have also tried applying the regex to the text with python 're'. In this case, I parsed the full file line by line. Initially, python correctly did not match the lines with dollar signs, but those lines would take a few seconds to finish even though they were only about 100 characters. By the fourth or fifth line that contained the structure of my sample, where the dot-separated words contained a '$', python froze up until I manually stopped it.

The python code used:

import re
def main():
    pattern = re.compile(r"name =\"\w+\.((?:\w+\.?)+)\" p")
    with open(r"filepath", "r") as f:
        i = 0
        for line in f:
            match = pattern.search(line)
            if (match):
                print('<Match: %r, groups=%r>' % (match.group(), match.groups()))
            else:
                print("line %d nomatch" % (i))
            i+=1
            match = None
            #it = pattern.finditer(f.read())
            #for element in it:
                #displaymatch(element)

def displaymatch(match):
    if match is None:
        return None
    print('<Match: %r, groups=%r>' % (match.group(), match.groups()))
main()

Can you explain why this is happening?

Body:
Since you want to know why your pattern doesn't work, here's a breakdown of it:

name ="        - capture a literal string: `name ="`

\w+            - ... followed by one or more word characters (A-Za-z0-9_)

\.             - ... followed by a literal dot

(              - start a capturing group (following matches will be captured as a group)

    (?:        - start a non-capturing group

        \w+    - match one or more word characters (A-Za-z0-9_)
        \.?    - ... optionally followed by a literal dot

    )+         - match as many of these non-capturing groups as possible

)              - close the group, nothing is captured as there is no capturing pattern in it

" p            - followed by a literal string: `" p`

Think of a string like:  name ="data.messageHeader.msg_time_tag.$date" pzb
. If you execute the above pattern on it you'll easily capture your name ="data. part and that's when the fun starts - nevermind the outer group, the problem is with the inner group and the + qualifier behind it - it will match the first messageHeader., then it will capture msg_time_tag. and so on until it encounters a quote character... However, since $date doesn't fit the inner pattern, it moves back to the previous match (backtracks) which is messageHeader. and tries again - only to encounter the same issue, and to backtrack again... And again... And again... Eventually shutting the engine and causing non-predictable behavior.

How will the regex engine choose to deal with this depends on the implementation - the most proper way would be to raise an infinite/catastrophic backtracking error (as the search head doesn't move despite the matches and the pattern doesn't provide a resolution), but it might just fail by capturing nothing or capturing everything...

The bottom line is - if you write proper regex pattern, the regex engine will act predictably. If not - anything goes.


问:
Hibernate with Ehcache and Teracotta in stateless clustered application
I am new to using Ehcache and Teracotta. We have a stateless clustered application.

We are using Spring framework and have hibernate in the persistence layer(legacy code). We are using REST APIs. Can someone please help me understand how does Ehcache work with Teracotta in a clustered environment.

More specifically, suppose I have 4 nodes of the application running then each node will have its own Ehcache and they all sync to talk to Teracotta or there can be Ehcache servers running on different nodes(different than the application nodes) and how does Teracotta play a role here.

I apologize if this question is naive, since I am new to all this.

答:
You will use Ehcache in each application. You can then use heap and offheap local caching if wanted.

Then, to get distributed caching, you use a clustered tier that will connect to the Terracotta server. This is where you will store distributed cache data.

You can find documentation and architecture here.


问:
Calling VB Script (macro) within PowerPoint using SharePoint
Is it possible to call macro within a sample powerpoint presentation using SharePoint Page?</p>

答:
Yesterday I searched to find out if it would be possible to call a presentation and a macro from a web page.
This is what I found: http://support.microsoft.com/kb/306683</p>


问:
Android, textviews alignment within listitem
I want to arrange the text views in each of my list items so that textview (id:lnumber) is on the left end,  textview (id:lname) next to it and the textview (id:lname1) under textview (id:lname)

I was able to align the first two textviews but am unable to arrange the third, right below the second

list_item.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/lnumber"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:textColor="@android:color/black"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/lname"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textSize="17sp"
        android:textColor="@android:color/black" />

    <TextView
        android:id="@+id/lname1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_below="@+id/lname"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textSize="17sp"
        android:textColor="@android:color/black" />

    </LinearLayout>
</code>```

答: you can use RelativeLayout .or use another LinearLayout in the first LinearLayout ,just make textview2 and textview3 in the new LinearLayout .</p>

Body:
I want to arrange the text views in each of my list items so that textview (id:lnumber) is on the left end,  textview (id:lname) next to it and the textview (id:lname1) under textview (id:lname)

I was able to align the first two textviews but am unable to arrange the third, right below the second

list_item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/lnumber"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:textColor="@android:color/black"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/lname"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textSize="17sp"
        android:textColor="@android:color/black" />

    <TextView
        android:id="@+id/lname1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_below="@+id/lname"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textSize="17sp"
        android:textColor="@android:color/black" />

    </LinearLayout>


问:
Compilation error: invalid conversion when calling base-type constructor
I'm trying to compile under MinGW-64 lljvm, a not-so-big program. But I am stuck on an error that is driving me nuts.

The code is as follows:

backend.h

```<code>class JVMWritter {
...
static char id;
...
};
</code>```

backend.cpp

```<code>char JVMWriter::id = 0;

JVMWriter::JVMWriter(): FunctionPass(&id) {}
</code>```

Now, FunctionPass is declared in Pass.h like this:

Pass.h

```<code>class FunctionPass {
...
explicit FunctionPass (char &pid) : <initialization here> {}
...
};
</code>```

When I try to compile that, I keep getting the following error:

```<code>backend.cpp:39:16: error: invalid conversion from 'char*' to 'char' [-fpermissive]
   FunctionPass(&JVMWriter::id), targetData(td), out(o), classname(cls), debug(dbg) {
                ^~~~~~~~~~

In file included from D:/dev/msys64/mingw64/include/llvm/IR/DataLayout.h:27:0,
                 from D:/dev/msys64/mingw64/include/llvm/IR/Module.h:20,
                 from D:/dev/msys64/mingw64/include/llvm/IR/PassManager.h:46,
                 from D:/dev/msys64/mingw64/include/llvm/Analysis/LoopInfo.h:47,
                 from backend.h:29,
                 from backend.cpp:23:
D:/dev/msys64/mingw64/include/llvm/Pass.h:300:12: note:   initializing argument 1 of 'llvm::FunctionPass::FunctionPass(char&)'
   explicit FunctionPass(char &pid) : Pass(PT_Function, pid) {}
            ^~~~~~~~~~~~

backend.cpp:39:16: error: cannot bind rvalue '(char)(& JVMWriter::id)' to 'char&'
   FunctionPass(&JVMWriter::id), targetData(td), out(o), classname(cls), debug(dbg) {
                ^~~~~~~~~~

In file included from D:/dev/msys64/mingw64/include/llvm/Pass.h:388:0,
                 from D:/dev/msys64/mingw64/include/llvm/IR/DataLayout.h:27,
                 from D:/dev/msys64/mingw64/include/llvm/IR/Module.h:20,
                 from D:/dev/msys64/mingw64/include/llvm/IR/PassManager.h:46,
                 from D:/dev/msys64/mingw64/include/llvm/Analysis/LoopInfo.h:47,
                 from backend.h:29,
                 from backend.cpp:23:
D:/dev/msys64/mingw64/include/llvm/PassAnalysisSupport.h: In instantiation of 'llvm::AnalysisUsage& llvm::AnalysisUsage::addRequired() [with PassClass = llvm::LoopInfo]':

backend.cpp:52:27:   required from here
D:/dev/msys64/mingw64/include/llvm/PassAnalysisSupport.h:61:39: error: 'ID' is not a member of 'llvm::LoopInfo'
     return addRequiredID(PassClass::ID);
</code>```

My obvious question: why is it complaining that I am attempting a non-valid conversion? I see no such attempt in those fragments.

答: Replace FunctionPass(&id) with FunctionPass(id).

Body:
I'm trying to compile under MinGW-64 lljvm, a not-so-big program. But I am stuck on an error that is driving me nuts.

The code is as follows:

backend.h

class JVMWritter {
...
static char id;
...
};

backend.cpp

char JVMWriter::id = 0;

JVMWriter::JVMWriter(): FunctionPass(&id) {}

Now, FunctionPass is declared in Pass.h like this:

Pass.h

class FunctionPass {
...
explicit FunctionPass (char &pid) : <initialization here> {}
...
};

When I try to compile that, I keep getting the following error:

backend.cpp:39:16: error: invalid conversion from 'char*' to 'char' [-fpermissive]
   FunctionPass(&JVMWriter::id), targetData(td), out(o), classname(cls), debug(dbg) {
                ^~~~~~~~~~

In file included from D:/dev/msys64/mingw64/include/llvm/IR/DataLayout.h:27:0,
                 from D:/dev/msys64/mingw64/include/llvm/IR/Module.h:20,
                 from D:/dev/msys64/mingw64/include/llvm/IR/PassManager.h:46,
                 from D:/dev/msys64/mingw64/include/llvm/Analysis/LoopInfo.h:47,
                 from backend.h:29,
                 from backend.cpp:23:
D:/dev/msys64/mingw64/include/llvm/Pass.h:300:12: note:   initializing argument 1 of 'llvm::FunctionPass::FunctionPass(char&)'
   explicit FunctionPass(char &pid) : Pass(PT_Function, pid) {}
            ^~~~~~~~~~~~

backend.cpp:39:16: error: cannot bind rvalue '(char)(& JVMWriter::id)' to 'char&'
   FunctionPass(&JVMWriter::id), targetData(td), out(o), classname(cls), debug(dbg) {
                ^~~~~~~~~~

In file included from D:/dev/msys64/mingw64/include/llvm/Pass.h:388:0,
                 from D:/dev/msys64/mingw64/include/llvm/IR/DataLayout.h:27,
                 from D:/dev/msys64/mingw64/include/llvm/IR/Module.h:20,
                 from D:/dev/msys64/mingw64/include/llvm/IR/PassManager.h:46,
                 from D:/dev/msys64/mingw64/include/llvm/Analysis/LoopInfo.h:47,
                 from backend.h:29,
                 from backend.cpp:23:
D:/dev/msys64/mingw64/include/llvm/PassAnalysisSupport.h: In instantiation of 'llvm::AnalysisUsage& llvm::AnalysisUsage::addRequired() [with PassClass = llvm::LoopInfo]':

backend.cpp:52:27:   required from here
D:/dev/msys64/mingw64/include/llvm/PassAnalysisSupport.h:61:39: error: 'ID' is not a member of 'llvm::LoopInfo'
     return addRequiredID(PassClass::ID);

My obvious question: why is it complaining that I am attempting a non-valid conversion? I see no such attempt in those fragments.


问:
Invalid scope error when trying to access gmail api
```<code>400. That’s an error.

Error: invalid_scope

You don't have permission to access some scopes. Your project is trying to access scopes that need to go through the verification process. {invalid = [https:// mail.google.com/]} If you need to use one of these scopes, submit a verification request.
</code>```

This is the error that I am getting when I flowed the tutorial in this link:
https://developers.google.com/gmail/api/quickstart/js

In the link they asked me to access webserver via python but I am using apache.
So in the step 1.f,  Authorized JavaScript origins: am using the link http:// localhost instead of http:// localhost:8000. What might be causing the error??

答:
You may refer with this thread.

As per the announcement on May 11, 2017, publicly available applications with access to certain user data must pass review. If you see an access error for your app, submit a request using our OAuth Developer Verification form.

For personal-use apps and those you are testing, join the Google group Risky Access Permissions By Unreviewed Apps, which allows you to approve data access for personal and testing accounts. See the Google API Services User Data Policy for more information.

This blog about how to fix this error might be also helpful.

Body:
400. That’s an error.

Error: invalid_scope

You don't have permission to access some scopes. Your project is trying to access scopes that need to go through the verification process. {invalid = [https:// mail.google.com/]} If you need to use one of these scopes, submit a verification request.

This is the error that I am getting when I flowed the tutorial in this link:
https://developers.google.com/gmail/api/quickstart/js

In the link they asked me to access webserver via python but I am using apache.
So in the step 1.f,  Authorized JavaScript origins: am using the link http:// localhost instead of http:// localhost:8000. What might be causing the error??


问:
Create collection of stubs with mockito
I want to create Collection of stubs so that first Item when I call getId() method return 0, second Item.getId() return 1 and so on. Value of getId() method must be equal index of element. I try this

```<code>@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private List<Item> items;

@Before
public void setUp() throws Exception {
    initMocks(this);
}

@Test
public void mockCollection() throws Exception {
    when(items.get(0).getId()).thenReturn(0);
    when(items.get(1).getId()).thenReturn(1);
    ...
}
</code>```

But I get this Exception:

```<code>java.lang.ClassCastException: org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$42aa7d0b cannot be cast to com.gubin.designpatterns.behavioural.observer.Item
</code>```

How I can do this task?

答:
What you need to do is to mock Item as well.

```<code>@Mock
private Item item1;
@Mock
private Item item2;

@Test
public void mockCollection() throws Exception {
    when(items.get(0)).thenReturn(item1);
    when(items.get(1)).thenReturn(item2);
    when(item1.getId()).thenReturn(1);
    when(item2.getId()).thenReturn(2);
}
</code>```

Title: Create collection of stubs with mockito

Body:
I want to create Collection of stubs so that first Item when I call getId() method return 0, second Item.getId() return 1 and so on. Value of getId() method must be equal index of element. I try this

@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private List<Item> items;

@Before
public void setUp() throws Exception {
    initMocks(this);
}

@Test
public void mockCollection() throws Exception {
    when(items.get(0).getId()).thenReturn(0);
    when(items.get(1).getId()).thenReturn(1);
    ...
}

But I get this Exception:

java.lang.ClassCastException: org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$42aa7d0b cannot be cast to com.gubin.designpatterns.behavioural.observer.Item

How I can do this task?

Body:
What you need to do is to mock Item as well.

@Mock
private Item item1;
@Mock
private Item item2;

@Test
public void mockCollection() throws Exception {
    when(items.get(0)).thenReturn(item1);
    when(items.get(1)).thenReturn(item2);
    when(item1.getId()).thenReturn(1);
    when(item2.getId()).thenReturn(2);
}


问:
How to write Java code that return a line of string into a string variable from Arduino?
How do I make the serial send and receive (RX/TX) code below work like a buffer until Sets a specific byte to buffer until before calling serialEvent() in

http://processing.org/reference/libraries/serial/Serial_bufferUntil_.html

and so as inString = (myPort.readString());

```<code>import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * This version of the TwoWaySerialComm example makes use of the
 * SerialPortEventListener to avoid polling.
 *
 */
public class TwoWaySerialComm
{
    public TwoWaySerialComm()
    {
        super();
    }

    void connect ( String portName ) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(
                  57600,
                  SerialPort.DATABITS_8,
                  SerialPort.STOPBITS_1,
                  SerialPort.PARITY_NONE);

                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();

                (new Thread(new SerialWriter(out))).start();

                serialPort.addEventListener(new SerialReader(in));
                serialPort.notifyOnDataAvailable(true);
            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

    /**
     * Handles the input coming from the serial port. A new line character
     * is treated as the end of a block in this example.
     */
    public static class SerialReader implements SerialPortEventListener
    {
        private InputStream in;
        private byte[] buffer = new byte[1024];

        public SerialReader ( InputStream in )
        {
            this.in = in;
        }

        public void serialEvent(SerialPortEvent arg0) {
            int data;

            try
            {
                int len = 0;
                while ( ( data = in.read()) > -1 )
                {
                    if ( data == '\n' ) {
                        break;
                    }
                    buffer[len++] = (byte) data;
                }
                System.out.print(new String(buffer,0,len));
            }
            catch ( IOException e )
            {
                e.printStackTrace();
                System.exit(-1);
            }
        }
    }

    /** */
    public static class SerialWriter implements Runnable
    {
        OutputStream out;

        public SerialWriter ( OutputStream out )
        {
            this.out = out;
        }

        public void run ()
        {
            try
            {
                int c = 0;
                while ( ( c = System.in.read()) > -1 )
                {
                    this.out.write(c);
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
                System.exit(-1);
            }
        }
    }

    public static void main ( String[] args )
    {
        try
        {
            (new TwoWaySerialComm()).connect("COM3");
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
</code>```

答:
Solved it ....</p>

```<code>package smartOfficeJava;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * This version of the TwoWaySerialComm example makes use of the
 * SerialPortEventListener to avoid polling.
 *
 */
public class Arduino
{
    OutputStream out;
    SerialReader input;
    public Arduino()
    {
        super();
    }

    void connect ( String portName ) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

                InputStream in = serialPort.getInputStream();
                out = serialPort.getOutputStream();

                //(new Thread(new SerialWriter(out))).start();
                input = new SerialReader(in);
                serialPort.addEventListener(input);
                serialPort.notifyOnDataAvailable(true);
                Thread.sleep(3000);
                out.write("yes".getBytes());

            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

    /**
     * Handles the input coming from the serial port. A new line character
     * is treated as the end of a block in this example.
     */
    public static class SerialReader implements SerialPortEventListener
    {
        private InputStream in;
        private byte[] buffer = new byte[1024];
        String buffer_string;
        public SerialReader ( InputStream in )
        {
            this.in = in;
        }

        public void serialEvent(SerialPortEvent arg0) {
            int data;

            try
            {
                int len = 0;
                while ( ( data = in.read()) > -1 )
                {
                    if ( data == '\n' ) {
                        break;
                    }
                    buffer[len++] = (byte) data;
                }
                //System.out.print(new String(buffer,0,len));
                buffer_string = new String(buffer,0,len);
            }
            catch ( IOException e )
            {
                e.printStackTrace();
                System.exit(-1);
            }
        }

    }

    /**
    public static class SerialWriter implements Runnable
    {
        OutputStream out;

        public SerialWriter ( OutputStream out )
        {
            this.out = out;
        }

        public void run ()
        {
            try
            {
                int c = 0;
                while ( ( c = System.in.read()) > -1 )
                {
                    this.out.write(c);
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
                System.exit(-1);
            }
        }
    }*/

   public String getSensor(){
       try
       {
               this.out.write("yes".getBytes());
       }
       catch ( IOException e )
       {
           e.printStackTrace();
       }
       try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
       return (input.buffer_string).trim();

   }

    public static void main ( String[] args )
    {
        Arduino test;
        try
        {
            test = new Arduino();
            test.connect("COM3");
            System.out.println(test.getSensor());
            System.out.println(test.getSensor());
            System.out.println(test.getSensor());
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
</code>```

Body:
How do I make the serial send and receive (RX/TX) code below work like a buffer until Sets a specific byte to buffer until before calling serialEvent() in

http://processing.org/reference/libraries/serial/Serial_bufferUntil_.html

and so as inString = (myPort.readString());

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * This version of the TwoWaySerialComm example makes use of the
 * SerialPortEventListener to avoid polling.
 *
 */
public class TwoWaySerialComm
{
    public TwoWaySerialComm()
    {
        super();
    }

    void connect ( String portName ) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(
                  57600,
                  SerialPort.DATABITS_8,
                  SerialPort.STOPBITS_1,
                  SerialPort.PARITY_NONE);

                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();

                (new Thread(new SerialWriter(out))).start();

                serialPort.addEventListener(new SerialReader(in));
                serialPort.notifyOnDataAvailable(true);
            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

    /**
     * Handles the input coming from the serial port. A new line character
     * is treated as the end of a block in this example.
     */
    public static class SerialReader implements SerialPortEventListener
    {
        private InputStream in;
        private byte[] buffer = new byte[1024];

        public SerialReader ( InputStream in )
        {
            this.in = in;
        }

        public void serialEvent(SerialPortEvent arg0) {
            int data;

            try
            {
                int len = 0;
                while ( ( data = in.read()) > -1 )
                {
                    if ( data == '\n' ) {
                        break;
                    }
                    buffer[len++] = (byte) data;
                }
                System.out.print(new String(buffer,0,len));
            }
            catch ( IOException e )
            {
                e.printStackTrace();
                System.exit(-1);
            }
        }
    }

    /** */
    public static class SerialWriter implements Runnable
    {
        OutputStream out;

        public SerialWriter ( OutputStream out )
        {
            this.out = out;
        }

        public void run ()
        {
            try
            {
                int c = 0;
                while ( ( c = System.in.read()) > -1 )
                {
                    this.out.write(c);
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
                System.exit(-1);
            }
        }
    }

    public static void main ( String[] args )
    {
        try
        {
            (new TwoWaySerialComm()).connect("COM3");
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Body:
Solved it ....

package smartOfficeJava;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * This version of the TwoWaySerialComm example makes use of the
 * SerialPortEventListener to avoid polling.
 *
 */
public class Arduino
{
    OutputStream out;
    SerialReader input;
    public Arduino()
    {
        super();
    }

    void connect ( String portName ) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

                InputStream in = serialPort.getInputStream();
                out = serialPort.getOutputStream();

                //(new Thread(new SerialWriter(out))).start();
                input = new SerialReader(in);
                serialPort.addEventListener(input);
                serialPort.notifyOnDataAvailable(true);
                Thread.sleep(3000);
                out.write("yes".getBytes());

            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

    /**
     * Handles the input coming from the serial port. A new line character
     * is treated as the end of a block in this example.
     */
    public static class SerialReader implements SerialPortEventListener
    {
        private InputStream in;
        private byte[] buffer = new byte[1024];
        String buffer_string;
        public SerialReader ( InputStream in )
        {
            this.in = in;
        }

        public void serialEvent(SerialPortEvent arg0) {
            int data;

            try
            {
                int len = 0;
                while ( ( data = in.read()) > -1 )
                {
                    if ( data == '\n' ) {
                        break;
                    }
                    buffer[len++] = (byte) data;
                }
                //System.out.print(new String(buffer,0,len));
                buffer_string = new String(buffer,0,len);
            }
            catch ( IOException e )
            {
                e.printStackTrace();
                System.exit(-1);
            }
        }

    }

    /**
    public static class SerialWriter implements Runnable
    {
        OutputStream out;

        public SerialWriter ( OutputStream out )
        {
            this.out = out;
        }

        public void run ()
        {
            try
            {
                int c = 0;
                while ( ( c = System.in.read()) > -1 )
                {
                    this.out.write(c);
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
                System.exit(-1);
            }
        }
    }*/

   public String getSensor(){
       try
       {
               this.out.write("yes".getBytes());
       }
       catch ( IOException e )
       {
           e.printStackTrace();
       }
       try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
       return (input.buffer_string).trim();

   }

    public static void main ( String[] args )
    {
        Arduino test;
        try
        {
            test = new Arduino();
            test.connect("COM3");
            System.out.println(test.getSensor());
            System.out.println(test.getSensor());
            System.out.println(test.getSensor());
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}


问:
PHP - Check if a string is a rotation of another string
Need to write a code block which check is one string is a rotation of another.

Looked at loads of posts on here and it is all in Java or C++ but I need to do it in PHP.

I have tried a few different things, trying to work from the C++ and Java examples but I am not having any luck, here is my current code:

```<code><?php

function isSubstring($s1, $s2) {

    if(strlen($s1) != strlen($s2)) {
        return false;
    }

    if(WHAT TO PUT HERE) {
        echo "it is!";
    } else {
        echo "nope";
    }
}

isSubstring("hello", "helol");

?>
</code>```

答:
```<code><?php
function isRotationalString($str1,$str2){
    $len = strlen($str1);
    if($str1 === $str2){
        return true;
    }else{
        if($len == strlen($str2)){
            $flag = true;
            for($i=0;$i<$len;$i++){
                if($str1[0]==$str2[$i]){
                    $tst = $i;$start = true;break;
                }
            }
            if($start){
                for($j=0;$j<$len;$j++){
                    $m = $j+$tst;
                    if($m < $len){
                        if($str1[$j] != $str2[$m]){
                            $flag = false;break;
                        }
                    }else{
                        if($m>=$len)
                        {
                            $k = $m - $len;
                            if($str1[$j] != $str2[$k]){
                                $flag = false;break;
                            }
                        }
                    }
                }
            }else{
                $flag = false;
            }
            return $flag;
        }
    }
}
echo isRotationalString("abcd","bcda")?'It is':'It is not';
?>
</code>```

above script will check whether a string is a rotation of another string or not?

isRotationalString("abcd","bcda") => It is

isRotationalString("abcd","cbda") => It is Not

Body:
Need to write a code block which check is one string is a rotation of another.

Looked at loads of posts on here and it is all in Java or C++ but I need to do it in PHP.

I have tried a few different things, trying to work from the C++ and Java examples but I am not having any luck, here is my current code:

<?php

function isSubstring($s1, $s2) {

    if(strlen($s1) != strlen($s2)) {
        return false;
    }

    if(WHAT TO PUT HERE) {
        echo "it is!";
    } else {
        echo "nope";
    }
}

isSubstring("hello", "helol");

?>

Body:
<?php
function isRotationalString($str1,$str2){
    $len = strlen($str1);
    if($str1 === $str2){
        return true;
    }else{
        if($len == strlen($str2)){
            $flag = true;
            for($i=0;$i<$len;$i++){
                if($str1[0]==$str2[$i]){
                    $tst = $i;$start = true;break;
                }
            }
            if($start){
                for($j=0;$j<$len;$j++){
                    $m = $j+$tst;
                    if($m < $len){
                        if($str1[$j] != $str2[$m]){
                            $flag = false;break;
                        }
                    }else{
                        if($m>=$len)
                        {
                            $k = $m - $len;
                            if($str1[$j] != $str2[$k]){
                                $flag = false;break;
                            }
                        }
                    }
                }
            }else{
                $flag = false;
            }
            return $flag;
        }
    }
}
echo isRotationalString("abcd","bcda")?'It is':'It is not';
?>

above script will check whether a string is a rotation of another string or not?

isRotationalString("abcd","bcda") => It is

isRotationalString("abcd","cbda") => It is Not


问:
SVG <circle> fill covering previous circle
I'm building an svg circular progress graph.

I'm trying to style my svg's stroke to match the visible part of circle.center but when I change the stroke of circle.progress it does not shrink the circle's fill enough to show the black part of circle.progress and match the width of the actual progress bar.

```<code><svg width="300" height="300">
    <circle class="progress" id="progress-radial-1" r="125"/>
    <circle class="center" r="140" cx="140" cy="140" />
    <text text-anchor="middle" x="150" y="185" />
</svg>
</code>```

Here is a fiddle: https://jsfiddle.net/BenRacicot/2kc7c56j/

Here is the svg's outcome (left):

I'm trying to get the results on the right. As you can see the circle.center which controls the blue progress bar (at 50%) also has a fill which is white in the image (gray in fiddle) and covers the black svg stroke too much. I need that stroke to be the same width of the blue.

答:
center and progress circle has different origin and should have the same (now set to 150).

The center has now 25px smaller radius than progress, to fit inside its stroke.

So if you update the markup like this, change the fill for center to #ddd and change the svg background to #000 you will get the layout you want

```<code><div class="pie-wrapper">
  <svg width="300" height="300">
    <circle class="progress" id="pr1" r="125" cx="150" cy="150"/>
    <circle class="center" r="100" cx="150" cy="150" />
    <text text-anchor="middle" x="150" y="175" />
  </svg>
</div>
</code>```

Updated fiddle

Stack snippet

window.addEventListener('load', function() {
  function radialProgress(update, id){
    let rd = document.getElementById(id).getAttribute("r");
    let i = 0;
    let a = 0;
    let x = rd * 2 * Math.PI;
    i = update;
    a = i / 100;
    let p = x * a;

    jQuery(".progress").attr("stroke-dasharray", p + ", " + x);
    jQuery(".progress").attr("stroke", "#0065a4");
    jQuery("text").text(update + "%");
  }

  radialProgress(50, 'pr1');
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pie-wrapper{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
}
    .pie-wrapper svg {
        background: #000;
        border-radius: 50%;
    }

.progress {
    stroke-width: 50;
    transform: rotate(-90deg);
    transform-origin: 50% 50%;
}

.center {
    fill: #ddd;
}

text {
    fill: #fff;
    font-family: 'Share Tech Mono';
    font-size: 80px;
}</code>```

  <svg width="300" height="300">
    <circle class="progress" id="pr1" r="125" cx="150" cy="150"/>
    <circle class="center" r="100" cx="150" cy="150" />
    <text text-anchor="middle" x="150" y="175" />
  </svg>

```

Note, it is the progress circle which controls the blue progress bar (at 50%), not the center, and the black svg doesn't have a stroke, it has (had) only a dark gray background.

Body:
I'm building an svg circular progress graph.

I'm trying to style my svg's stroke to match the visible part of circle.center but when I change the stroke of circle.progress it does not shrink the circle's fill enough to show the black part of circle.progress and match the width of the actual progress bar.

<svg width="300" height="300">
    <circle class="progress" id="progress-radial-1" r="125"/>
    <circle class="center" r="140" cx="140" cy="140" />
    <text text-anchor="middle" x="150" y="185" />
</svg>

Here is a fiddle: https://jsfiddle.net/BenRacicot/2kc7c56j/

Here is the svg's outcome (left):

I'm trying to get the results on the right. As you can see the circle.center which controls the blue progress bar (at 50%) also has a fill which is white in the image (gray in fiddle) and covers the black svg stroke too much. I need that stroke to be the same width of the blue.

Body:
center and progress circle has different origin and should have the same (now set to 150).

The center has now 25px smaller radius than progress, to fit inside its stroke.

So if you update the markup like this, change the fill for center to #ddd and change the svg background to #000 you will get the layout you want

<div class="pie-wrapper">
  <svg width="300" height="300">
    <circle class="progress" id="pr1" r="125" cx="150" cy="150"/>
    <circle class="center" r="100" cx="150" cy="150" />
    <text text-anchor="middle" x="150" y="175" />
  </svg>
</div>

Updated fiddle

Stack snippet

window.addEventListener('load', function() {
  function radialProgress(update, id){
    let rd = document.getElementById(id).getAttribute("r");
    let i = 0;
    let a = 0;
    let x = rd * 2 * Math.PI;
    i = update;
    a = i / 100;
    let p = x * a;

    jQuery(".progress").attr("stroke-dasharray", p + ", " + x);
    jQuery(".progress").attr("stroke", "#0065a4");
    jQuery("text").text(update + "%");
  }

  radialProgress(50, 'pr1');
})

.pie-wrapper{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
}
    .pie-wrapper svg {
        background: #000;
        border-radius: 50%;
    }

.progress {
    stroke-width: 50;
    transform: rotate(-90deg);
    transform-origin: 50% 50%;
}

.center {
    fill: #ddd;
}

text {
    fill: #fff;
    font-family: 'Share Tech Mono';
    font-size: 80px;
}

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<div class="pie-wrapper">
  <svg width="300" height="300">
    <circle class="progress" id="pr1" r="125" cx="150" cy="150"/>
    <circle class="center" r="100" cx="150" cy="150" />
    <text text-anchor="middle" x="150" y="175" />
  </svg>
</div>

Note, it is the progress circle which controls the blue progress bar (at 50%), not the center, and the black svg doesn't have a stroke, it has (had) only a dark gray background.


答: char & pid declares pid as a reference to char, while you pass &id which is a pointer to char.

Title: Compilation error: invalid conversion when calling base-type constructor


问:
Value contains many text in Conditional Format Rules Google Sheet
I want to set conditional format rules in my Google spreadsheet. For the format cell, I select "Text contains", then I type values "PA, MA, CT, NY", formatting style I choose red. When I click DONE, the columns containing these words didn't show the color. I don't want to create rules "PA', "MA", "CT"and "NY" one by one. How can I fix them? Thanks for helping.</p>

答:
As Ed said, but to clarify,

Go to conditional format and select 'Custom formula'

Assuming that your values are in column A, set the range to A1:A and enter the formula =OR($A:A="PA",$A:A="MA",$A:A="CT",$A:A="NY") in the custom formula field.

If the values are not in column A then change the formula as necessary.


问:
How to keep a play button icon centered on an image when screen size is reduced?
Here is a screenshot of the problem:

I used the instructions from this tutorial to learn how to put a play button over animated GIFs: http://www.hongkiat.com/blog/on-click-animated-gif/

For the most part this works but I'm having trouble getting the play button to stay centered when the screen size changes to mobile.

I am using this theme (Hugo): https://github.com/tomanistor/osprey

I'm guessing I need to contain the image and play button icon in a table or something? The tutorial's example has the images contained in a DIV but when I try that, I lose the play button:

```<code><div class="demo-content">
<figure>
<img src="/images/image-placeholder.jpg" alt="Static Image" data-alt="/images/animated-gif.gif">
</figure>
</div>
</code>```

I'm currently using the following to get both the placeholder and play image:

```<code><figure>
<img src="/images/image-placeholder.jpg" alt="Static Image" data-alt="/images/animated-gif.gif">
</figure>
</code>```

I have tried opening my browser's dev tools and playing around with the styles' values but it feels like whack-a-mole.

Here is a snippet of the CSS that I have added to the theme:

```<code>.
.
.
@font-face {
    font-family: 'font-awesome';
    font-style: normal;
    font-weight: 700;
    src: url(https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/fonts/fontawesome-webfont.ttf) format("truetype")
}
.
.
.
figure {
  width: 100%;
  margin: 0;
  float: left;
  padding: 10px;
  position: relative;
  cursor: pointer;
}
figure:before,
figure:after {
  position: absolute;
}
figure:before {
  top: 206px;
  left: 50%;
  margin-left: -50px;
  width: 100px;
  height: 100px;
  border: 3px solid rgba(255, 255, 255, 0.7);
  border-radius: 50px;
  background-color: rgba(204, 209, 217, 0.3);
  font-family: 'font-awesome';
  content: '\f04b';
  text-align: center;
  line-height: 95px;
  font-size: 30px;
  color: #182230;
}
figure:after {
  position: absolute;
  display: inline-block;
  width: auto;
  text-align: center;
  top: 20px;
  right: 20px;
  font-size: 11px;
  font-weight: 600;
  padding: 5px;
  border-radius: 3px;
  color: #656D78;
  background-color: rgba(170, 178, 189, 0.1);
  text-transform: uppercase;
}
figure.play:before {
  display: none;
}
figure.play:after {
  content: 'playing';
  color: #fff;
  background-color: #212121;
  text-transform: uppercase;
}
figcaption {
  padding-top: 15px;
  font-size: 14px;
  text-align: center;
  color: #8d9bad;
}
figcaption a {
  color: #59687b;
  text-decoration: none;
}
</code>```

How can I get my play button to stay exactly centered like in the tutorial example?

答:
Change the figure:before to top: 50% to keep it 50% from the top, then remove your margin-left and use transform: translate(-50%,-50%) instead, which will move the element to the left and up 50% of it's own width/height. margin-left: -50px is the same as translateX(-50%) in your example, but using transform: translate() is simpler.

```<code>figure:before {
    top: 50%;
    left: 50%;
    /* margin-left: -50px; */
    width: 100px;
    height: 100px;
    border: 3px solid rgba(255, 255, 255, 0.7);
    border-radius: 50px;
    background-color: rgba(204, 209, 217, 0.3);
    font-family: 'font-awesome';
    content: '\f04b';
    text-align: center;
    line-height: 95px;
    font-size: 30px;
    color: #182230;
    transform: translate(-50%,-50%);
}
</code>```

Body:
Here is a screenshot of the problem:

I used the instructions from this tutorial to learn how to put a play button over animated GIFs: http://www.hongkiat.com/blog/on-click-animated-gif/

For the most part this works but I'm having trouble getting the play button to stay centered when the screen size changes to mobile.

I am using this theme (Hugo): https://github.com/tomanistor/osprey

I'm guessing I need to contain the image and play button icon in a table or something? The tutorial's example has the images contained in a DIV but when I try that, I lose the play button:

I'm currently using the following to get both the placeholder and play image:

I have tried opening my browser's dev tools and playing around with the styles' values but it feels like whack-a-mole.

Here is a snippet of the CSS that I have added to the theme:

.
.
.
@font-face {
    font-family: 'font-awesome';
    font-style: normal;
    font-weight: 700;
    src: url(https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/fonts/fontawesome-webfont.ttf) format("truetype")
}
.
.
.
figure {
  width: 100%;
  margin: 0;
  float: left;
  padding: 10px;
  position: relative;
  cursor: pointer;
}
figure:before,
figure:after {
  position: absolute;
}
figure:before {
  top: 206px;
  left: 50%;
  margin-left: -50px;
  width: 100px;
  height: 100px;
  border: 3px solid rgba(255, 255, 255, 0.7);
  border-radius: 50px;
  background-color: rgba(204, 209, 217, 0.3);
  font-family: 'font-awesome';
  content: '\f04b';
  text-align: center;
  line-height: 95px;
  font-size: 30px;
  color: #182230;
}
figure:after {
  position: absolute;
  display: inline-block;
  width: auto;
  text-align: center;
  top: 20px;
  right: 20px;
  font-size: 11px;
  font-weight: 600;
  padding: 5px;
  border-radius: 3px;
  color: #656D78;
  background-color: rgba(170, 178, 189, 0.1);
  text-transform: uppercase;
}
figure.play:before {
  display: none;
}
figure.play:after {
  content: 'playing';
  color: #fff;
  background-color: #212121;
  text-transform: uppercase;
}
figcaption {
  padding-top: 15px;
  font-size: 14px;
  text-align: center;
  color: #8d9bad;
}
figcaption a {
  color: #59687b;
  text-decoration: none;
}

How can I get my play button to stay exactly centered like in the tutorial example?

Body:
Change the figure:before to top: 50% to keep it 50% from the top, then remove your margin-left and use transform: translate(-50%,-50%) instead, which will move the element to the left and up 50% of it's own width/height. margin-left: -50px is the same as translateX(-50%) in your example, but using transform: translate() is simpler.

figure:before {
    top: 50%;
    left: 50%;
    /* margin-left: -50px; */
    width: 100px;
    height: 100px;
    border: 3px solid rgba(255, 255, 255, 0.7);
    border-radius: 50px;
    background-color: rgba(204, 209, 217, 0.3);
    font-family: 'font-awesome';
    content: '\f04b';
    text-align: center;
    line-height: 95px;
    font-size: 30px;
    color: #182230;
    transform: translate(-50%,-50%);
}


问:
When Memory is Allocated to Class?
```<code>Class Sample
{
  int a,b;
 public :
  Sample(int p,int q)
   {
     a=p;
     b=q;
   }
  int sum()
  {
    return (a+b);
  }
};
int main()
{
  Sample sm(10,20);
  std::cout<< "Sum :"<< sm.sum()<<endl;
}
</code>```

I am beginner to C++ so please keep language of your answer simple so that I understand well .
Thanks in Advance :)

答:
The only memory allocated for a class is for static member variables. Your example doesn't contain any static member variables.

Memory is allocated for objects. You create one such object, in the line:

```<code>Sample sm;
</code>```

This memory will go away at the end of the block where the variable is declared, when it goes out of scope.

Title: When Memory is Allocated to Class?

Body:
Class Sample
{
  int a,b;
 public :
  Sample(int p,int q)
   {
     a=p;
     b=q;
   }
  int sum()
  {
    return (a+b);
  }
};
int main()
{
  Sample sm(10,20);
  std::cout<< "Sum :"<< sm.sum()<<endl;
}

I am beginner to C++ so please keep language of your answer simple so that I understand well .
Thanks in Advance :)

Body:
The only memory allocated for a class is for static member variables. Your example doesn't contain any static member variables.

Memory is allocated for objects. You create one such object, in the line:

Sample sm;

This memory will go away at the end of the block where the variable is declared, when it goes out of scope.


问:
How can I limit my text to 200 characters only?
I do not know, why I do not see any text:

$(".elipsis").text($(this).text().substr(0, 200)+'...');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

 <p class="elipsis">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p></code>```

答:
Your $(this) is not what you think it is.

It is recognised if you pass a function using the jQuery text-function

$(".elipsis").text(
  function() {
    return $(this).text().substring(0, 200) + '...';
  }
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="elipsis">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>

<p class="elipsis">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p></code>```

CSS Alternative

.truncate {
  width: 550px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>CSS Alternative</b> - for one line only

<p class="truncate">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p></code>```

Body:
I do not know, why I do not see any text:

$(".elipsis").text($(this).text().substr(0, 200)+'...');

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Body:
Your $(this) is not what you think it is.

It is recognised if you pass a function using the jQuery text-function

$(".elipsis").text(
  function() {
    return $(this).text().substring(0, 200) + '...';
  }
);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="elipsis">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>

<p class="elipsis">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>

CSS Alternative

.truncate {
  width: 550px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

<b>CSS Alternative</b> - for one line only

<p class="truncate">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>


问:
Center my navigation buttons
I tried a lot of solutions to center my navigation buttons but non worked and I don't find the right solution. I tried space-between but I want it responsive.

Here is my HTML:

```<code><ul>

    <li class="btn"><a href="">The performances</a></li>

    <li class="btn"><a href="">About Us</a></li>

    <li class="btn"><a href="">Book Now !</a></li>

</ul>
</code>```

Here is my CSS code:

```<code>nav li{
    display: inline-block;
    padding: 10px;}

nav a{
    color:#fff;
    text-decoration:none;
}

nav .btn{
  -webkit-border-radius: 17;
  -moz-border-radius: 17;
  border-radius: 17px;
  font-family: Georgia;
  color: #fff;
  font-size: 20px;
  background: #8B0000;
  padding: 5px 10px 5px 10px;
  margin:0 auto;
  text-decoration: none;
 text-align: center;}

.btn:hover{
  background: #A26161;
  text-decoration: none;
}
</code>```

Thank you for your advices !

答:
Try this solution!

nav{
  text-align: center;
}

nav li{
    display: inline-block;
    padding: 10px;}

nav a{
    color:#fff;
    text-decoration:none;
}

nav .btn{
  -webkit-border-radius: 17;
  -moz-border-radius: 17;
  border-radius: 17px;
  font-family: Georgia;
  color: #fff;
  font-size: 20px;
  background: #8B0000;
  padding: 5px 10px 5px 10px;
  margin:0 auto;
  text-decoration: none;
 text-align: center;}

.btn:hover{
  background: #A26161;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
<ul>

    <li class="btn">The performances</li>

    <li class="btn">About Us</li>

    <li class="btn">Book Now !</li>

</ul>
</nav></code>```

Title: Center my navigation buttons

Body:
I tried a lot of solutions to center my navigation buttons but non worked and I don't find the right solution. I tried space-between but I want it responsive.

Here is my HTML:

The performances

About Us

Book Now !

Here is my CSS code:

nav li{
    display: inline-block;
    padding: 10px;}

nav a{
    color:#fff;
    text-decoration:none;
}

nav .btn{
  -webkit-border-radius: 17;
  -moz-border-radius: 17;
  border-radius: 17px;
  font-family: Georgia;
  color: #fff;
  font-size: 20px;
  background: #8B0000;
  padding: 5px 10px 5px 10px;
  margin:0 auto;
  text-decoration: none;
 text-align: center;}

.btn:hover{
  background: #A26161;
  text-decoration: none;
}

Thank you for your advices !

Body:
Try this solution!

nav{
  text-align: center;
}

nav li{
    display: inline-block;
    padding: 10px;}

nav a{
    color:#fff;
    text-decoration:none;
}

nav .btn{
  -webkit-border-radius: 17;
  -moz-border-radius: 17;
  border-radius: 17px;
  font-family: Georgia;
  color: #fff;
  font-size: 20px;
  background: #8B0000;
  padding: 5px 10px 5px 10px;
  margin:0 auto;
  text-decoration: none;
 text-align: center;}

.btn:hover{
  background: #A26161;
  text-decoration: none;
}

<nav>
<ul>

    <li class="btn"><a href="">The performances</a></li>

    <li class="btn"><a href="">About Us</a></li>

    <li class="btn"><a href="">Book Now !</a></li>

</ul>
</nav>


问:
HTML and enable div's horizontal scrolling but hide the horizontal scrollbar
I need my div to be scrollable. Now it works fine, but I would like to hide the horizontal scrollbar. I do not want to disable it, just hide it.

All I want to see is one vertical scrollbar on the browser window. No horizontal scrollbars on the screen.

No JavaScript/jQuery allowed. I need a cross-browser solution.

#kaaviopohja {
  width: 100%;
  overflow: hidden;
  background-color: yellow;
}

#kaaviotaulukko {
  width: 100%;
  overflow-x: scroll;
  padding-bottom: 17px;
  background-color: pink;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh<br />
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh<br />
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh<br />
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh<br />
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh<br />

<DIV id="kaaviopohja">

  <div id="kaaviotaulukko" style="white-space: nowrap; position: relative; text-align: center;">
    <div style="display:inline-block">
      <!--
        -->
      <DIV STYLE="DISPLAY:INLINE-BLOCK">
        <div style="float:left;width:0">
          <div id="navi7">
            <div style="z-index:100;position:fixed;left:0;top:0;bottom:0;max-height:1em;margin:auto;">A</div>
            <div style="z-index:100;position:fixed;right:0;top:0;bottom:0;max-height:1em;margin:auto;">B</div>
          </div>
        </div>
        <div class="krs" style="display: inline-block; vertical-align: top; width: 300px;">
          <div>
            <h3>LQsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss</h3>
          </div>
          1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /> 1
          <br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />
        </div>
      </DIV>
      <!--
        -->
      <div style="float: right; width: 0;">
        <div id="navi100">
          <div style="z-index: 100; position: fixed; left: 0; top: 500px">C</div>
        </div>
      </div>
      <!--

      -->
      <div style="z-index:99;width:70px;position:fixed;left:0;top:0;bottom:0;margin:auto;background-color:red;"><br />
      </div>

      <div style="z-index:99;width:70px;position:fixed;right:0;top:0;bottom:0;margin:auto;background-color:red;"><br />
      </div>
    </div>
  </div>

</DIV></code>```

答:
You can use CSS properties for this.</p>

```<code>overflow-x: hidden; /* hide horizontal scrollbar */
overflow-y: scroll; /* show vertical scrollbar */
</code>```

Body:
I need my div to be scrollable. Now it works fine, but I would like to hide the horizontal scrollbar. I do not want to disable it, just hide it.

All I want to see is one vertical scrollbar on the browser window. No horizontal scrollbars on the screen.

No JavaScript/jQuery allowed. I need a cross-browser solution.

#kaaviopohja {
  width: 100%;
  overflow: hidden;
  background-color: yellow;
}

#kaaviotaulukko {
  width: 100%;
  overflow-x: scroll;
  padding-bottom: 17px;
  background-color: pink;
}

hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

A

B

LQsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss

          1
2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10
 1

2
3
4
5
6
7
8
9
10

C

Body:
You can use CSS properties for this.

overflow-x: hidden; /* hide horizontal scrollbar */
overflow-y: scroll; /* show vertical scrollbar */


问:
s3cmd ImportError: No module named S3.Exceptions
Received an error after installing and trying to run s3cmd 1.0.0

```<code>s3cmd -h

Problem: ImportError: No module named S3.Exceptions
S3cmd:   unknown version. Module import problem?

Traceback (most recent call last):
  File "/usr/bin/s3cmd", line 1995, in <module>
    from S3.Exceptions import *
ImportError: No module named S3.Exceptions

Your sys.path contains these entries:
</code>```

This error came about after upgrading to the latest Amazon Linux distro 2015.03.0

答:
Neither of the previous answers worked for me, but copying a few lines from the sourcegraph aws-cli dockerfile did:

FROM python:2

RUN apt-get update -q

RUN apt-get install -qy python-pip groff-base

RUN pip install awscli

Body:
Received an error after installing and trying to run s3cmd 1.0.0

s3cmd -h

Problem: ImportError: No module named S3.Exceptions
S3cmd:   unknown version. Module import problem?

Traceback (most recent call last):
  File "/usr/bin/s3cmd", line 1995, in <module>
    from S3.Exceptions import *
ImportError: No module named S3.Exceptions

Your sys.path contains these entries:

This error came about after upgrading to the latest Amazon Linux distro 2015.03.0


问:
Python - Scrapy / can find a Xpath query with @class but not with @id
I´m trying to learn Scrapy for Python with the following guide : http://brutalsimplicity.github.io/2016/07/25/scrapy.html . I have followed the instructions and i am able to manually scrape some data via the scrapy shell, but i have problems targeting what i want. When i try to target the following div class :

```<code><div class="overthrow table_container" id="div_pbp">
</code>```

with @class:

```<code>response.xpath('//div[@class="overthrow table_container"]')
</code>```

then it works and i get

```<code>[<Selector xpath='//div[@class="overthrow table_container"]' data=u'<div class="overthrow table_container" i'>]
</code>```

as a response, but when i try to do the same with @id:

```<code>response.xpath('//div[@id="div_pbp"]')
</code>```

i get empty brackets [] as a response .

Edit1 : Im using windows 10, Python version 2.7.13 , Scrapy version 1.4.0
Am i formulating my queries wrongly or is there some other explenation?

Edit2 : I noticed that my output on the scrapy shell is cut off. When viewing all divs with //div i get the following output :
Image

Could this be the problem ? How can you tell scrapy to get the whole selector and not cut it off?

Edit3 : another Example :

When using the Dev Tools on the website, i see the selector should be :

<Selector xpath='//div[@id="all_game_info"]' data=u'

When i access it with :

response.xpath('//div[@id="all_game_info"]')

then i get :

[<Selector xpath='//div[@id="all_game_info"]' data=u'
]

so it cutt off a part. When i now try to search with the class variable like this

response.xpath('//div[@class="table_wra"]')

or

response.xpath('//div[@class="table_wrapper columns"]')

, then i get empty brackets []

Btw : this was all in the Scrapy shell

答:
I've finally got down to brass tacks and replicated the problem you face. I use neither the Scrapy shell nor IPython so you this will appear slightly different.

I get the content of the page using the requests library then use the scrapy HtmlResponse object to give myself the ability to search the page using xpath expressions.

My experience was the same as yours.

```<code>>>> url = 'http://www.pro-football-reference.com/boxscores/201409040sea.htm'
>>> from scrapy.selector import Selector
>>> import requests
>>> page = requests.get(url).content
>>> response = HtmlResponse(url,body=page)
>>> response.xpath('//div[@class="overthrow table_container"]')
[<Selector xpath='//div[@class="overthrow table_container"]' data='<div class="overthrow table_container" i'>]
>>> response.xpath('//div[@id="div_pbp"]')
[]
</code>```

So I looked at the HTML for div_pbp. I should not have been surprised: this happens so often. What we were looking for is in a comment, and there's only one of them in the page.

EDIT: If the output from a statement will be textual and voluminous then one tactic you can use is to save that output to a Python name and then write that name to a file for examination. Something like this:

```<code>enormousOutput = <statement>
open('temp.txt', 'w').write(enormousOutput)
</code>```

Body:
I´m trying to learn Scrapy for Python with the following guide : http://brutalsimplicity.github.io/2016/07/25/scrapy.html . I have followed the instructions and i am able to manually scrape some data via the scrapy shell, but i have problems targeting what i want. When i try to target the following div class :

with @class:

response.xpath('//div[@class="overthrow table_container"]')

then it works and i get

[<Selector xpath='//div[@class="overthrow table_container"]' data=u'
]

as a response, but when i try to do the same with @id:

response.xpath('//div[@id="div_pbp"]')

i get empty brackets [] as a response .

Edit1 : Im using windows 10, Python version 2.7.13 , Scrapy version 1.4.0
Am i formulating my queries wrongly or is there some other explenation?

Edit2 : I noticed that my output on the scrapy shell is cut off. When viewing all divs with //div i get the following output :
Image

Could this be the problem ? How can you tell scrapy to get the whole selector and not cut it off?

Edit3 : another Example :

When using the Dev Tools on the website, i see the selector should be :

<Selector xpath='//div[@id="all_game_info"]' data=u'

When i access it with :

response.xpath('//div[@id="all_game_info"]')

then i get :

[<Selector xpath='//div[@id="all_game_info"]' data=u'
]

so it cutt off a part. When i now try to search with the class variable like this

response.xpath('//div[@class="table_wra"]')

or

response.xpath('//div[@class="table_wrapper columns"]')

, then i get empty brackets []

Btw : this was all in the Scrapy shell

Body:
I've finally got down to brass tacks and replicated the problem you face. I use neither the Scrapy shell nor IPython so you this will appear slightly different.

I get the content of the page using the requests library then use the scrapy HtmlResponse object to give myself the ability to search the page using xpath expressions.

My experience was the same as yours.

>>> url = 'http://www.pro-football-reference.com/boxscores/201409040sea.htm'
>>> from scrapy.selector import Selector
>>> import requests
>>> page = requests.get(url).content
>>> response = HtmlResponse(url,body=page)
>>> response.xpath('//div[@class="overthrow table_container"]')
[<Selector xpath='//div[@class="overthrow table_container"]' data='<div class="overthrow table_container" i'>]
>>> response.xpath('//div[@id="div_pbp"]')
[]

So I looked at the HTML for div_pbp. I should not have been surprised: this happens so often. What we were looking for is in a comment, and there's only one of them in the page.

EDIT: If the output from a statement will be textual and voluminous then one tactic you can use is to save that output to a Python name and then write that name to a file for examination. Something like this:

enormousOutput = <statement>
open('temp.txt', 'w').write(enormousOutput)


答:
Your CSS contains a navelement, but the HTML doesn't. I added one, and also added nav { text-align: center; }:

nav {
  text-align: center;
}

nav li {
  display: inline-block;
  padding: 10px;
}

nav a {
  color: #fff;
  text-decoration: none;
}

nav .btn {
  -webkit-border-radius: 17px;
  -moz-border-radius: 17px;
  border-radius: 17px;
  font-family: Georgia;
  color: #fff;
  font-size: 20px;
  background: #8B0000;
  padding: 5px 10px 5px 10px;
  margin: 0 auto;
  text-decoration: none;
  text-align: center;
}

.btn:hover {
  background: #A26161;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>

    <li class="btn">The performances</li>

    <li class="btn">About Us</li>

    <li class="btn">Book Now !</li>

  </ul>
</nav></code>```

Title: Center my navigation buttons

Body:
Your CSS contains a navelement, but the HTML doesn't. I added one, and also added nav { text-align: center; }:

nav {
  text-align: center;
}

nav li {
  display: inline-block;
  padding: 10px;
}

nav a {
  color: #fff;
  text-decoration: none;
}

nav .btn {
  -webkit-border-radius: 17px;
  -moz-border-radius: 17px;
  border-radius: 17px;
  font-family: Georgia;
  color: #fff;
  font-size: 20px;
  background: #8B0000;
  padding: 5px 10px 5px 10px;
  margin: 0 auto;
  text-decoration: none;
  text-align: center;
}

.btn:hover {
  background: #A26161;
  text-decoration: none;
}

<nav>
  <ul>

    <li class="btn"><a href="">The performances</a></li>

    <li class="btn"><a href="">About Us</a></li>

    <li class="btn"><a href="">Book Now !</a></li>

  </ul>
</nav>

ContentLicense: CC BY-SA 4.0


问:
Manage pages displayed in Progressive Web Apps ( PWA )
I am new to PWA and was just going through some readups. We have public website and in the website we provide login for users to manage their account. By going with PWA, I understand that users can save the website on the mobile homepage  as an icon. My question is that , when user click on my PWA icon , can we load the login page for the users so that they can only manage account with PWA instead of loading entire website.</p>

答:
The Web App Manifest allows you to control how your app appears and how it's launched. You can specify home screen icons, the page to load when the app is launched, screen orientation, and even whether or not to show the browser chrome.

The web app manifest is a simple JSON file that gives you, the developer, the ability to control how your app appears to the user in areas where they would expect to see apps (for example, a mobile device's home screen), direct what the user can launch, and define its appearance at launch.

You can define how your app is launched, add a query string parameter to the start_url that indicates how it was launched.

```<code>"start_url": "/?utm_source=homescreen"
</code>```

Hope this helps!

Body:
The Web App Manifest allows you to control how your app appears and how it's launched. You can specify home screen icons, the page to load when the app is launched, screen orientation, and even whether or not to show the browser chrome.

The web app manifest is a simple JSON file that gives you, the developer, the ability to control how your app appears to the user in areas where they would expect to see apps (for example, a mobile device's home screen), direct what the user can launch, and define its appearance at launch.

You can define how your app is launched, add a query string parameter to the start_url that indicates how it was launched.

"start_url": "/?utm_source=homescreen"

Hope this helps!


问:
Setting "WindowsState"="Maximized" in Style doesn't work after manual minimize/restore
My Window has a DataTrigger that looks like this:

```<code> <Window.Style>
        <Style TargetType="{x:Type Window}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsFullscreen}" Value="true">
                    <Setter Property="WindowState" Value="Maximized" />
                    <!-- Other setters -->
                </DataTrigger>

                <DataTrigger Binding="{Binding IsFullscreen}" Value="false">
                    <Setter Property="WindowState" Value="Normal" />
                    <!-- Other setters -->
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Style>
</code>```

This works just fine until the user minimizes and restores the window (e.g. by clicking the _ button followed by the taskbar icon). The effects of the other setters continue to evidence after this when IsFullscreen changes, so I know the trigger continues to fire; the problem is that the WindowState setting is no longer heeded. Removing the other setters doesn't fix this, so they're not to blame. What's going on? What can I do to fix it?

Problem is occurring on a Windows 10 PC; no info about what happens with a different OS.

答:
Since dependency properties might be set in different places a precedence list is needed. You can find this list here.

When you minimize your window by clicking the corresponding button, you are setting the local value of the WindowState dependecy property. As per the precedence list we saw before, your DataTrigger can't work anymore.

Body:
My Window has a DataTrigger that looks like this:

 <Window.Style>

        </Style>
    </Window.Style>

This works just fine until the user minimizes and restores the window (e.g. by clicking the _ button followed by the taskbar icon). The effects of the other setters continue to evidence after this when IsFullscreen changes, so I know the trigger continues to fire; the problem is that the WindowState setting is no longer heeded. Removing the other setters doesn't fix this, so they're not to blame. What's going on? What can I do to fix it?

Problem is occurring on a Windows 10 PC; no info about what happens with a different OS.


问:
how to remove extra margin between two cells
I would like to remove extra space between two cells in UICollection.

I find some solutions but or not works fine or lan programming is object-c.

答: Change "min spacing" property for cells in Collection view to 0. In story board, Click on the collection view and check the following properties in the inspector and change the min spacing.


问:
How to make an html table responsive
I have an html table that is created using constant contact and and I would like to make it responsive and fit the container div holding it.

Here is the demo

I tried the following but this doesn't work as well

```<code><table border="0" width="100%" cellspacing="0" cellpadding="0">
</code>```

答:
TL;DR:

I have a solution that works well for a lot of table implementations, given that you are formatting your tables well (table>thead>tr>th^^tbody>tr>td). Find my CodePen here. Depending on the data in your table, this may be a good mobilizing solution.

The Director's Cut

See my CodePen here.

This solution assumes you have built your tables nicely, meaning you are using thead with th and tbody with td. For example:

```<code><table>
  <thead>
    <tr>
      <th>A</th>
      <th>S</th>
      <th>L</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>33</td>
      <td>M</td>
      <td>United States</td>
    </tr>
  </tbody>
</table>
</code>```

Given that the table data isn't characterized by columns and columns of numeric values, this JS / CSS solution works well. You can see it in action on my employer's docs pages (SmartyStreets Documentation) and in human readable form on the CodePen snippet I built for it here. To see it working, resize the screen. Breakpoints are set differently on each implementation, because consistency. Here's how to implement it.

Tables are fed to the tableMobilizer function. Given that it is built on jQuery, this can be done for all tables on the page like so:

```<code>var tables = $(table);
tableMobilizer(tables);
</code>```

You can definitely be more selective about how you mobilize tables with your selector if you need to be.

This will generate a new set of tables for each table passed in and append them after their respective source table. Each new table contains a row of a source table which is transformed with a 90 degree CCW rotation and paired with the table headings.

Old tables are dynamically classed with .hidden-small-down and new tables are classed with .hidden-medium-up for your CSS media queries.

New tables come classed with .mobile-tables (for a collection of all mobile tables generated by a single source table), .mobile-table (for each mobile table representation of a single source table row), .mobile-table-row (for a row in a mobile table), .mobile-table-key (for the first column of a mobile table), and .mobile-table-value (for the second column of a mobile table).

In your CSS, set up your media queries to hide / show the appropriate table views:

```<code>@media only screen and (min-width: 768px) {
  .hidden-medium-up {
    display: none;
  }
}

@media only screen and (max-width: 768px) {
  .hidden-small-down {
    display: none;
  }
}
</code>```

With the media queries implemented, styling the tables is left to your discretion.

After Credits Scene

This is not a silver bullet solution. Visualizations using tabular data can be very complicated. As mentioned above, this solution isn't great for column-heavy tables. It also doesn't handle col and row spanning. As always, seriously consider whether or not you actually need to use a table in your layout (beyond the scope of this comment). If you do, this may be a good solution for mobilizing your tables.

Title: How to make an html table responsive

Body:
TL;DR:

I have a solution that works well for a lot of table implementations, given that you are formatting your tables well (table>thead>tr>th^^tbody>tr>td). Find my CodePen here. Depending on the data in your table, this may be a good mobilizing solution.

The Director's Cut

See my CodePen here.

This solution assumes you have built your tables nicely, meaning you are using thead with th and tbody with td. For example:

<table>
  <thead>
    <tr>
      <th>A</th>
      <th>S</th>
      <th>L</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>33</td>
      <td>M</td>
      <td>United States</td>
    </tr>
  </tbody>
</table>

Given that the table data isn't characterized by columns and columns of numeric values, this JS / CSS solution works well. You can see it in action on my employer's docs pages (SmartyStreets Documentation) and in human readable form on the CodePen snippet I built for it here. To see it working, resize the screen. Breakpoints are set differently on each implementation, because consistency. Here's how to implement it.

Tables are fed to the tableMobilizer function. Given that it is built on jQuery, this can be done for all tables on the page like so:

var tables = $(table);
tableMobilizer(tables);

You can definitely be more selective about how you mobilize tables with your selector if you need to be.

This will generate a new set of tables for each table passed in and append them after their respective source table. Each new table contains a row of a source table which is transformed with a 90 degree CCW rotation and paired with the table headings.

Old tables are dynamically classed with .hidden-small-down and new tables are classed with .hidden-medium-up for your CSS media queries.

New tables come classed with .mobile-tables (for a collection of all mobile tables generated by a single source table), .mobile-table (for each mobile table representation of a single source table row), .mobile-table-row (for a row in a mobile table), .mobile-table-key (for the first column of a mobile table), and .mobile-table-value (for the second column of a mobile table).

In your CSS, set up your media queries to hide / show the appropriate table views:

@media only screen and (min-width: 768px) {
  .hidden-medium-up {
    display: none;
  }
}

@media only screen and (max-width: 768px) {
  .hidden-small-down {
    display: none;
  }
}

With the media queries implemented, styling the tables is left to your discretion.

After Credits Scene

This is not a silver bullet solution. Visualizations using tabular data can be very complicated. As mentioned above, this solution isn't great for column-heavy tables. It also doesn't handle col and row spanning. As always, seriously consider whether or not you actually need to use a table in your layout (beyond the scope of this comment). If you do, this may be a good solution for mobilizing your tables.


问:
VS 2015 Update 1 - Claiming I am debugging a release build
After updating to VS 2015 update 1, if I run a web project (MVC), stop the application, then try to run it again, VS stops and pops up a dialog claiming

You are debugging a Release build of <myproject.dll>.

Using Just My Code with release builds using compiler optimizations results in a degraded debugging experience (e.g. breakpoints won't be hit).

The problem is I'm not running a release build. I'm clearly running the (same) debug build I just ran! Why does VS think I'm running a release build?

Cleaning the solution and re-running clears the error message, so something is hosed somewhere.

答: In my case, I had changed the "Active solution platform" for the whole solution at "Configuration Manager" from x86 to Any CPU, fixed the problem </p>