答:
You may add an alternative branch like |\|{1,2} to the regex of yours:

```<code>/AND|OR|and|or|XOR|&&|<=|>=|<|>|!=|==|&|OR*|!|\|{1,2}/gi
</code>```

See the regex demo.

The \|{1,2} matches 2 or 1 (since {1,2} is a greedy version of a limiting quantifier, it will try to match as many | as it can) | symbols (this | must be escaped since otherwise, it is an alternation operator in a regex).

If you want to enhance it (get rid of redundancy), use

```<code>/and|x?or|&&|[<>!=]=|[<>&!]|\|{1,2}/gi
</code>```

See another regex demo. Note that the words might need to be matched as whole words only, and then you'd need /\b(?:and|x?or)\b|&&|[<>!=]=|[<>&!]|\|{1,2}/gi.

Title: How to find logic operators in string with regex?

Body:
You may add an alternative branch like |\|{1,2} to the regex of yours:

/AND|OR|and|or|XOR|&&|<=|>=|<|>|!=|==|&|OR*|!|\|{1,2}/gi

See the regex demo.

The \|{1,2} matches 2 or 1 (since {1,2} is a greedy version of a limiting quantifier, it will try to match as many | as it can) | symbols (this | must be escaped since otherwise, it is an alternation operator in a regex).

If you want to enhance it (get rid of redundancy), use

/and|x?or|&&|[<>!=]=|[<>&!]|\|{1,2}/gi

See another regex demo. Note that the words might need to be matched as whole words only, and then you'd need /\b(?:and|x?or)\b|&&|[<>!=]=|[<>&!]|\|{1,2}/gi.


来源: stackexchange

问:
Perforce (p4v) - Simple create/push/merge branch for git developer

Background

I come from a git background, and have been using it for years. Prior to that, I used subversion for several years, and had to occasionally use CVS.

Question

I'm starting on a large perforce project and want to create a feature branch so that:

I don't impact trunk/mainline/master.

I can backup my work at end-of-day to the remote server.

With a tool like git, this was pretty easy:

```<code>git checkout -b my_branch
# make some edits
git add -u
git commit
git push
</code>```

How do I accomplish the same (more or less) in perforce, using the command-line interface? Apparently I have to first use p4 branch to "create a branch spec", and then use p4 integrate to "open files for merging or branching", but couldn't find any concrete examples that make sense.

Thank you.

答:
If you want something that's comparable to the git experience you probably want to be using Perforce's DVCS mode:  https://www.perforce.com/perforce/r15.2/manuals/dvcs/

So, assuming you're doing this in your own local server, the flow is like this:

```<code>p4 fetch
p4 switch -c my_branch
# make some edits
p4 submit -d "Made my edits."
p4 switch main
p4 fetch
p4 merge --from my_branch
p4 resolve -am
p4 submit -d "Merged my edits into main."
p4 push
</code>```

If you're doing this directly on a shared server that uses streams, you can skip the fetching and pushing part since every submit is already going straight to the "remote" (although I'll assume the allwrite/auto-reconcile feature that mimics "git commit -a" isn't on in that case, so you'll be using "p4 edit" to open your files for edit):

```<code>p4 switch -c my_branch
p4 edit (your files)
# make some edits
p4 submit -d "Made my edits."
p4 switch main
p4 merge --from my_branch
p4 resolve -am
p4 submit -d "Merged my edits into main."
</code>```

If you're doing this on a shared server that doesn't use streams (i.e. "classic Perforce") then it's:

```<code>p4 integ //depot/main/... //depot/my_branch/...
cd my_branch
p4 submit -d "Created my branch."
p4 edit (your files)
# make some edits
p4 submit -d "Made my edits."
p4 integ //depot/my_branch/... //depot/main/...
p4 resolve -am
p4 submit -d "Merged my edits into main."
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Background

I come from a git background, and have been using it for years. Prior to that, I used subversion for several years, and had to occasionally use CVS.

Question

I'm starting on a large perforce project and want to create a feature branch so that:

I don't impact trunk/mainline/master.

I can backup my work at end-of-day to the remote server.

With a tool like git, this was pretty easy:

git checkout -b my_branch
# make some edits
git add -u
git commit
git push

How do I accomplish the same (more or less) in perforce, using the command-line interface? Apparently I have to first use p4 branch to "create a branch spec", and then use p4 integrate to "open files for merging or branching", but couldn't find any concrete examples that make sense.

Thank you.

Body:
If you want something that's comparable to the git experience you probably want to be using Perforce's DVCS mode:  https://www.perforce.com/perforce/r15.2/manuals/dvcs/

So, assuming you're doing this in your own local server, the flow is like this:

p4 fetch
p4 switch -c my_branch
# make some edits
p4 submit -d "Made my edits."
p4 switch main
p4 fetch
p4 merge --from my_branch
p4 resolve -am
p4 submit -d "Merged my edits into main."
p4 push

If you're doing this directly on a shared server that uses streams, you can skip the fetching and pushing part since every submit is already going straight to the "remote" (although I'll assume the allwrite/auto-reconcile feature that mimics "git commit -a" isn't on in that case, so you'll be using "p4 edit" to open your files for edit):

p4 switch -c my_branch
p4 edit (your files)
# make some edits
p4 submit -d "Made my edits."
p4 switch main
p4 merge --from my_branch
p4 resolve -am
p4 submit -d "Merged my edits into main."

If you're doing this on a shared server that doesn't use streams (i.e. "classic Perforce") then it's:

p4 integ //depot/main/... //depot/my_branch/...
cd my_branch
p4 submit -d "Created my branch."
p4 edit (your files)
# make some edits
p4 submit -d "Made my edits."
p4 integ //depot/my_branch/... //depot/main/...
p4 resolve -am
p4 submit -d "Merged my edits into main."


问:
Pandas DataFrame Apply function, multiple arguments
I have a Pandas dataframe and one of the columns is a string.  I imported a function from an external module to do some RegEx checking and reduce this string to a short classification.

This works:

```<code>df['PageCLass'] = df['PageClass'].apply(lambda x: PageClassify.page_classify(x))
</code>```

However what I would really like to do is incorporate another column 'Rev' in the dataframe which happens to be either be a float or NaN into the checking.

When I did this:

```<code>df['PageCLass'] = df['PageClass'].apply(lambda x: PageClassify.page_classify(x,df['Rev']))
</code>```

and I was doing logical checks inside the classification function on the 2nd argument, I got this error:

```<code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

What I am looking for is a way to capture the 2nd argument value by value, just as lambda x:  captures the first argument value by value.

答:
The method above is ok I guess if it worked... In my opinion it does not answer the question because you're concatenating two arguments into one.

A way to do this to allow you to pass two arguments to apply:

```<code>df['PageCLass'] = df[['PageClass','Rev']].apply(lambda x: PageClassify.page_classify(*x), axis=1)
</code>```

I don't know what the page_classify method looks like but if it takes two arguments the above should work. Does this work for you?

Body:
I have a Pandas dataframe and one of the columns is a string.  I imported a function from an external module to do some RegEx checking and reduce this string to a short classification.

This works:

df['PageCLass'] = df['PageClass'].apply(lambda x: PageClassify.page_classify(x))

However what I would really like to do is incorporate another column 'Rev' in the dataframe which happens to be either be a float or NaN into the checking.

When I did this:

df['PageCLass'] = df['PageClass'].apply(lambda x: PageClassify.page_classify(x,df['Rev']))

and I was doing logical checks inside the classification function on the 2nd argument, I got this error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

What I am looking for is a way to capture the 2nd argument value by value, just as lambda x:  captures the first argument value by value.

Body:
The method above is ok I guess if it worked... In my opinion it does not answer the question because you're concatenating two arguments into one.

A way to do this to allow you to pass two arguments to apply:

df['PageCLass'] = df[['PageClass','Rev']].apply(lambda x: PageClassify.page_classify(*x), axis=1)

I don't know what the page_classify method looks like but if it takes two arguments the above should work. Does this work for you?


问:
How to update numbers of subchapter in the given chapter in a text file?
I have a text files with the TABLE OF CONTENTS of a book.

I have to create an index.txt file that can be read by ghostscript.

The text file is available HERE, and looks like:

```<code>Chapter 1 Introduction 1
Chapter 2 Fundamental Observations 7
2.1 Dark night sky   7
2.2 Isotropy and homogeneity  11
2.3 Redshift proportional to distance  15
2.4 Types of particles  22
2.5 Cosmic microwave background  28
Chapter 3 Newton Versus Einstein 32
3.1 Equivalence principle  33
3.2 Describing curvature  39
3.3 Robertson-Walker metric  44
3.4 Proper distance 47
</code>```

This has to be changed to:

```<code>[/Count -0 /Page 7 /Title (Chapter: 1 Introduction ) /OUT pdfmark
[/Count -5 /Page 13 /Title (Chapter: 2 Fundamental Observations ) /OUT pdfmark
[/Count 0 /Page 13 /Title (Chapter: 2.1 Dark night sky   ) /OUT pdfmark
[/Count 0 /Page 17 /Title (Chapter: 2.2 Isotropy and homogeneity  ) /OUT pdfmark
[/Count 0 /Page 21 /Title (Chapter: 2.3 Redshift proportional to distance  ) /OUT pdfmark
[/Count 0 /Page 28 /Title (Chapter: 2.4 Types of particles  ) /OUT pdfmark
[/Count 0 /Page 34 /Title (Chapter: 2.5 Cosmic microwave background  ) /OUT pdfmark
[/Count -4 /Page 38 /Title (Chapter: 3 Newton Versus Einstein ) /OUT pdfmark
[/Count 0 /Page 39 /Title (Chapter: 3.1 Equivalence principle  ) /OUT pdfmark
[/Count 0 /Page 45 /Title (Chapter: 3.2 Describing curvature  ) /OUT pdfmark
[/Count 0 /Page 50 /Title (Chapter: 3.3 Robertson-Walker metric  ) /OUT pdfmark
[/Count 0 /Page 53 /Title (Chapter: 3.4 Proper distance   ) /OUT pdfmark
</code>```

In the above, notice that:

```<code>Count = number of sub chapter in the given chapter
Page = given page in table of content + 6
</code>```

How can we do this?

So far I have tried this.

```<code>def get_Count_Page_and_Title(bookmark, offset=6):
    """Get chapters and page numbers."""
    with open(bookmark, 'r') as fi, open('temp_index.txt', 'w') as fo:
        for line in fi:
            line = r'[/Count -0 /Page 0 /Title (Chapter: 1 Introduction ) /OUT pdfmark'
            print(line, file = fo)
</code>```

Some related links are:

python reading text file

Read .txt file line by line in Python

答:
I very slightly modify the above answer, so that I can read data from a text file and write into another text file.<br>
The code is given below:  </p>

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Author      : Stephen Rauch
# Modified by : Bhishan Poudel; Physics PhD Student, Ohio University
# Date        : Mar 5, 2017
# pastebin link for index.txt: http://pastebin.com/LP8KXAmU

def print_count_page_and_title(data, page_offset=0):
    """Get chapters and page numbers."""
    fo = open('index.txt', 'w', encoding='utf-8')
    print('Creating: ', 'index.txt')
    chapters = []
    chapter = None
    for line in data:
        if line.startswith('Chapter'):
            if chapter is not None:
                chapters.append(chapter)
            chapter = (line.strip().rsplit(' ', 1), [])
            # chapter is tuple of two lists
            # second list is empty list
            # first list has two elements,
            # second element is separated by white space in end by rsplit.
            # print(line)
            # Chapter 1 Introduction 1
            # print(chapter)
            # (['Chapter 1 Introduction', '1'], [])
            # print("\n")
        else:
            subchapter = line.strip().rsplit(' ', 1)
            chapter[1].append(subchapter)

    if chapter is not None:
        chapters.append(chapter)

    def page_num(page):
        return int(page) + page_offset

    fmt_chapter = '[/Count -%d /Page %d /Title (%s) /OUT pdfmark'
    fmt_sub_chapter = '[/Count 0 /Page %d /Title (%s) /OUT pdfmark'

    for chapter in chapters:
        print(fmt_chapter % (
            len(chapter[1]), page_num(chapter[0][1]), chapter[0][0]), file=fo)
        for sub_chapter in chapter[1]:
            print(fmt_sub_chapter % (
                page_num(sub_chapter[1]), sub_chapter[0]), file=fo)
        pass
    fo.close()

if __name__ == "__main__":
    test_data = open('toc_ryden.txt', 'r', encoding='utf-8').readlines()
    print_count_page_and_title(test_data, page_offset=6)
</code>```

Body:
I have a text files with the TABLE OF CONTENTS of a book.

I have to create an index.txt file that can be read by ghostscript.

The text file is available HERE, and looks like:

Chapter 1 Introduction 1
Chapter 2 Fundamental Observations 7
2.1 Dark night sky   7
2.2 Isotropy and homogeneity  11
2.3 Redshift proportional to distance  15
2.4 Types of particles  22
2.5 Cosmic microwave background  28
Chapter 3 Newton Versus Einstein 32
3.1 Equivalence principle  33
3.2 Describing curvature  39
3.3 Robertson-Walker metric  44
3.4 Proper distance 47

This has to be changed to:

[/Count -0 /Page 7 /Title (Chapter: 1 Introduction ) /OUT pdfmark
[/Count -5 /Page 13 /Title (Chapter: 2 Fundamental Observations ) /OUT pdfmark
[/Count 0 /Page 13 /Title (Chapter: 2.1 Dark night sky   ) /OUT pdfmark
[/Count 0 /Page 17 /Title (Chapter: 2.2 Isotropy and homogeneity  ) /OUT pdfmark
[/Count 0 /Page 21 /Title (Chapter: 2.3 Redshift proportional to distance  ) /OUT pdfmark
[/Count 0 /Page 28 /Title (Chapter: 2.4 Types of particles  ) /OUT pdfmark
[/Count 0 /Page 34 /Title (Chapter: 2.5 Cosmic microwave background  ) /OUT pdfmark
[/Count -4 /Page 38 /Title (Chapter: 3 Newton Versus Einstein ) /OUT pdfmark
[/Count 0 /Page 39 /Title (Chapter: 3.1 Equivalence principle  ) /OUT pdfmark
[/Count 0 /Page 45 /Title (Chapter: 3.2 Describing curvature  ) /OUT pdfmark
[/Count 0 /Page 50 /Title (Chapter: 3.3 Robertson-Walker metric  ) /OUT pdfmark
[/Count 0 /Page 53 /Title (Chapter: 3.4 Proper distance   ) /OUT pdfmark

In the above, notice that:

Count = number of sub chapter in the given chapter
Page = given page in table of content + 6

How can we do this?

So far I have tried this.

def get_Count_Page_and_Title(bookmark, offset=6):
    """Get chapters and page numbers."""
    with open(bookmark, 'r') as fi, open('temp_index.txt', 'w') as fo:
        for line in fi:
            line = r'[/Count -0 /Page 0 /Title (Chapter: 1 Introduction ) /OUT pdfmark'
            print(line, file = fo)

Some related links are:

python reading text file

Read .txt file line by line in Python

Body:
I very slightly modify the above answer, so that I can read data from a text file and write into another text file.

The code is given below:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Author      : Stephen Rauch
# Modified by : Bhishan Poudel; Physics PhD Student, Ohio University
# Date        : Mar 5, 2017
# pastebin link for index.txt: http://pastebin.com/LP8KXAmU

def print_count_page_and_title(data, page_offset=0):
    """Get chapters and page numbers."""
    fo = open('index.txt', 'w', encoding='utf-8')
    print('Creating: ', 'index.txt')
    chapters = []
    chapter = None
    for line in data:
        if line.startswith('Chapter'):
            if chapter is not None:
                chapters.append(chapter)
            chapter = (line.strip().rsplit(' ', 1), [])
            # chapter is tuple of two lists
            # second list is empty list
            # first list has two elements,
            # second element is separated by white space in end by rsplit.
            # print(line)
            # Chapter 1 Introduction 1
            # print(chapter)
            # (['Chapter 1 Introduction', '1'], [])
            # print("\n")
        else:
            subchapter = line.strip().rsplit(' ', 1)
            chapter[1].append(subchapter)

    if chapter is not None:
        chapters.append(chapter)

    def page_num(page):
        return int(page) + page_offset

    fmt_chapter = '[/Count -%d /Page %d /Title (%s) /OUT pdfmark'
    fmt_sub_chapter = '[/Count 0 /Page %d /Title (%s) /OUT pdfmark'

    for chapter in chapters:
        print(fmt_chapter % (
            len(chapter[1]), page_num(chapter[0][1]), chapter[0][0]), file=fo)
        for sub_chapter in chapter[1]:
            print(fmt_sub_chapter % (
                page_num(sub_chapter[1]), sub_chapter[0]), file=fo)
        pass
    fo.close()

if __name__ == "__main__":
    test_data = open('toc_ryden.txt', 'r', encoding='utf-8').readlines()
    print_count_page_and_title(test_data, page_offset=6)


问:
Best Approach to consume APIs
What is the best way to consume APIs required for data processing/ data warehousing.

I have multiple data sources that I would like to obtain via APIs. Some of the modules have over 20 API calls others have 5-6. How do I get all this data for each system/ data source.

Would the best approach be to use Console Application like Azure Web Job Service, etc. Is that the most amount of work since it will require programming from scratch? Or should I use a middleware like Talend, Pentaho to consume these APis and transfer to a database?

Any help will be immensely appreciated.

答:
The only benefit that WebJobs will give you is the ability to execute code on a schedule. You'll be writing your own code to pull data from various APIs and store it whenever you choose to warehouse the data. </p>

<p>In my opinion, if you've already got .NET code that hits these APIs and saves the necessary data written, then WebJobs would be a reasonable choice. If you've got to write the code to call APIs from scratch, I'd first look to a third party data integration tool such as Talend and see if it will work for you. </p>

Title: Best Approach to consume APIs

Body:
The only benefit that WebJobs will give you is the ability to execute code on a schedule. You'll be writing your own code to pull data from various APIs and store it whenever you choose to warehouse the data.

In my opinion, if you've already got .NET code that hits these APIs and saves the necessary data written, then WebJobs would be a reasonable choice. If you've got to write the code to call APIs from scratch, I'd first look to a third party data integration tool such as Talend and see if it will work for you.


问:
Set field value with reflection
I'm working with one project which is not opensource and I need to modify one or more its classes.

In one class is following collection:

```<code>private Map<Integer, TTP> ttp = new HashMap<>();
</code>```

All what I need to do is use reflection and use concurrenthashmap here.
I've tried following code but it doesnt work.

```<code>Field f = ..getClass().getDeclaredField("ttp");
f.setAccessible(true);
f.set(null, new ConcurrentHashMap<>());
</code>```

答:
The method below sets a field on your object even if the field is in a superclass</p>

```<code>/**
 * Sets a field value on a given object
 *
 * @param targetObject the object to set the field value on
 * @param fieldName    exact name of the field
 * @param fieldValue   value to set on the field
 * @return true if the value was successfully set, false otherwise
 */
public static boolean setField(Object targetObject, String fieldName, Object fieldValue) {
    Field field;
    try {
        field = targetObject.getClass().getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
        field = null;
    }
    Class superClass = targetObject.getClass().getSuperclass();
    while (field == null && superClass != null) {
        try {
            field = superClass.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            superClass = superClass.getSuperclass();
        }
    }
    if (field == null) {
        return false;
    }
    field.setAccessible(true);
    try {
        field.set(targetObject, fieldValue);
        return true;
    } catch (IllegalAccessException e) {
        return false;
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Set field value with reflection

Body:
I'm working with one project which is not opensource and I need to modify one or more its classes.

In one class is following collection:

private Map<Integer, TTP> ttp = new HashMap<>();

All what I need to do is use reflection and use concurrenthashmap here.
I've tried following code but it doesnt work.

Field f = ..getClass().getDeclaredField("ttp");
f.setAccessible(true);
f.set(null, new ConcurrentHashMap<>());

Body:
The method below sets a field on your object even if the field is in a superclass

/**
 * Sets a field value on a given object
 *
 * @param targetObject the object to set the field value on
 * @param fieldName    exact name of the field
 * @param fieldValue   value to set on the field
 * @return true if the value was successfully set, false otherwise
 */
public static boolean setField(Object targetObject, String fieldName, Object fieldValue) {
    Field field;
    try {
        field = targetObject.getClass().getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
        field = null;
    }
    Class superClass = targetObject.getClass().getSuperclass();
    while (field == null && superClass != null) {
        try {
            field = superClass.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            superClass = superClass.getSuperclass();
        }
    }
    if (field == null) {
        return false;
    }
    field.setAccessible(true);
    try {
        field.set(targetObject, fieldValue);
        return true;
    } catch (IllegalAccessException e) {
        return false;
    }
}


问:
Create assignment executable script
Whats going on so for my unix/linux class the teacher wants us to create a create_assignment executable to use for all of our work or he takes off points. I have been trying for a week now and asked the teacher twice and it hasn't helped at all. so when I type ./create_assignment assignment3 it is suppose to make assignment 3 with a header I know I'm suppose to use chmod +x create_assignment to make it executable. I got it to make a create_assignment executable one time but it wouldnt do anything so I need to be shown how to make it executable and make it create the new assignment, I can post pictures if needed. </p>

答: Please share the code of your script. Have you checked file permissions? What user is running the job, and does that user own the destination folder/file? </p>

Title: Create assignment executable script


问:
vhdl simulation does not work
I was writing VHDL code in order to find the numbers in a set ranging from 0 to 7 which do not have any common divisors with the other numbers in the set. I tried to implement it on BASYS 3 board. It is working on BASYS 3 but when I tried to write a test bench for my code, I got lots of U's and UU's.Why do you think this is the case? How can I write a proper test bench? I'm a beginner so any idea would help.

TOP MODULE:

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;

-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity Top is
    Port ( Basys_Clock_Top : in STD_LOGIC;
           New_Clock_Top : out std_logic_vector(3 downto 0);
           SegDisp_Top : out std_logic_vector(6 downto 0);
           Binary_Top : out std_logic_vector(3 downto 0);
           F : out STD_LOGIC);
end Top;

architecture Behavioral of Top is
    --clock component
    component NewClock
        Port ( New_Clock : out std_logic_vector(3 downto 0);
               Basys_Clock : in STD_LOGIC);
    end component;

    --ssd component
    component SSD
    Port ( Basys_Clock : in STD_LOGIC;
               Binary : in std_logic_vector(3 downto 0);
               SegDisplay : out std_logic_vector(6 downto 0));
    end component;

    --signals
    signal X, Y, Z, Cont : std_logic;
    signal BCD_Top : std_logic_vector(3 downto 0);

begin
    --port maps
    NewClockModule : NewClock port map( New_Clock => New_Clock_Top, Basys_Clock => Basys_Clock_Top);
    SSDModule : SSD port map( Basys_Clock => Basys_Clock_Top, Binary => BCD_Top, SegDisplay => SegDisp_Top);

    --input assignment
    New_Clock_Top(0) <= Z;
    New_Clock_Top(1) <= Y;
    New_Clock_Top(2) <= X;

    Binary_Top <= "1110";
    F <= Z or ((not X) and Y);
    F <= Cont;

    process(BCD_Top, Cont)
    begin
        if(Cont = '1') then
            BCD_Top(0) <= Z;
            BCD_Top(1) <= Y;
            BCD_Top(2) <= X;
            BCD_Top(3) <= '0';
        else
            BCD_Top <= "1111";
        end if;
    end process;
end Behavioral;
</code>```

This is the test bench:

TEST BENCH:

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;

-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity TestBench is
--  Port ( );
end TestBench;

architecture Behavioral of TestBench is
    component Top
        Port ( Basys_Clock_Top : in STD_LOGIC;
               New_Clock_Top : out std_logic_vector(3 downto 0);
               SegDisp_Top : out std_logic_vector(6 downto 0);
               Binary_Top : out std_logic_vector(3 downto 0);
               F : out STD_LOGIC);
    end component;

    --signals
    signal Basys_Clock_Top : STD_LOGIC;
    signal New_Clock_Top : std_logic_vector(3 downto 0);
    signal Binary_Top : std_logic_vector(3 downto 0);
    signal SegDisp_Top : std_logic_vector(6 downto 0);
    signal F : std_logic;

begin
    uut : Top Port Map ( Basys_Clock_Top => Basys_Clock_Top, New_Clock_Top => New_Clock_Top, SegDisp_Top => SegDisp_Top, Binary_Top => Binary_Top, F => F);

    stim_proc : process
    begin
        Basys_Clock_Top <= '0';
        wait for 10 ps;
        Basys_Clock_Top <= '1';
        wait for 10 ps;
        Basys_Clock_Top <= '0';
    end process;
end Behavioral;
</code>```

答: One thing I notice: in your TOP module, X, Y, Z, and Cont are not assigned anything.  But you use their values....which will therefore be U

Title: vhdl simulation does not work

Body:
I was writing VHDL code in order to find the numbers in a set ranging from 0 to 7 which do not have any common divisors with the other numbers in the set. I tried to implement it on BASYS 3 board. It is working on BASYS 3 but when I tried to write a test bench for my code, I got lots of U's and UU's.Why do you think this is the case? How can I write a proper test bench? I'm a beginner so any idea would help.

TOP MODULE:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;

-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity Top is
    Port ( Basys_Clock_Top : in STD_LOGIC;
           New_Clock_Top : out std_logic_vector(3 downto 0);
           SegDisp_Top : out std_logic_vector(6 downto 0);
           Binary_Top : out std_logic_vector(3 downto 0);
           F : out STD_LOGIC);
end Top;

architecture Behavioral of Top is
    --clock component
    component NewClock
        Port ( New_Clock : out std_logic_vector(3 downto 0);
               Basys_Clock : in STD_LOGIC);
    end component;

    --ssd component
    component SSD
    Port ( Basys_Clock : in STD_LOGIC;
               Binary : in std_logic_vector(3 downto 0);
               SegDisplay : out std_logic_vector(6 downto 0));
    end component;

    --signals
    signal X, Y, Z, Cont : std_logic;
    signal BCD_Top : std_logic_vector(3 downto 0);

begin
    --port maps
    NewClockModule : NewClock port map( New_Clock => New_Clock_Top, Basys_Clock => Basys_Clock_Top);
    SSDModule : SSD port map( Basys_Clock => Basys_Clock_Top, Binary => BCD_Top, SegDisplay => SegDisp_Top);

    --input assignment
    New_Clock_Top(0) <= Z;
    New_Clock_Top(1) <= Y;
    New_Clock_Top(2) <= X;

    Binary_Top <= "1110";
    F <= Z or ((not X) and Y);
    F <= Cont;

    process(BCD_Top, Cont)
    begin
        if(Cont = '1') then
            BCD_Top(0) <= Z;
            BCD_Top(1) <= Y;
            BCD_Top(2) <= X;
            BCD_Top(3) <= '0';
        else
            BCD_Top <= "1111";
        end if;
    end process;
end Behavioral;

This is the test bench:

TEST BENCH:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;

-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity TestBench is
--  Port ( );
end TestBench;

architecture Behavioral of TestBench is
    component Top
        Port ( Basys_Clock_Top : in STD_LOGIC;
               New_Clock_Top : out std_logic_vector(3 downto 0);
               SegDisp_Top : out std_logic_vector(6 downto 0);
               Binary_Top : out std_logic_vector(3 downto 0);
               F : out STD_LOGIC);
    end component;

    --signals
    signal Basys_Clock_Top : STD_LOGIC;
    signal New_Clock_Top : std_logic_vector(3 downto 0);
    signal Binary_Top : std_logic_vector(3 downto 0);
    signal SegDisp_Top : std_logic_vector(6 downto 0);
    signal F : std_logic;

begin
    uut : Top Port Map ( Basys_Clock_Top => Basys_Clock_Top, New_Clock_Top => New_Clock_Top, SegDisp_Top => SegDisp_Top, Binary_Top => Binary_Top, F => F);

    stim_proc : process
    begin
        Basys_Clock_Top <= '0';
        wait for 10 ps;
        Basys_Clock_Top <= '1';
        wait for 10 ps;
        Basys_Clock_Top <= '0';
    end process;
end Behavioral;


问:
Ruby Watir Iterate through list and find element
I have an unordered list.
ul-list

```<code>------------ li-ola
Ola
Description
------------ li-james
James
Description
------------ li-jake
Joe
Description
------------
</code>```

All descriptions are embedded in a div using the same id name "description"
I need to verify that all items in the list has a description. Without knowing how big the list is.

So far i have:

```<code>bb = @browser.ul(:id => 'ul-list')
bb.lis.each do |li|
  fail unless @browser.div(:class => 'description').exists?
end
</code>```

Fixed my previous error but now the test pass even when there is nothing in the list. :/

Sample HTML

```<code><ul id=“ul-list”>
<li id=“li-ola”>
        <div class=“return”>
          <table>
            <tbody>
            <tr class=“info_return”>
              <td class="info_return_label">Brand</td>
              <td class="info_return_value">
              Ola
              </td>
            </tr>
            <tr class="info_return_row">
              <td class="info_return_desc_label">Description</td>
              <td class="info_return_description">
              Test Data
              </td>
            </tr>
            </tbody>
          </table>
        </div>
      </li>
</ul>
</code>```

答:
For your sample html, this code prints success. Are you sure it does not work for you?

```<code>bb = browser.ul(:id => 'ul-list')
bb.lis.each do |li|
  puts 'success' if li.td(:class => 'info_return_description').exists?
end
</code>```

Body:
I have an unordered list.
ul-list

------------ li-ola
Ola
Description
------------ li-james
James
Description
------------ li-jake
Joe
Description
------------

All descriptions are embedded in a div using the same id name "description"
I need to verify that all items in the list has a description. Without knowing how big the list is.

So far i have:

bb = @browser.ul(:id => 'ul-list')
bb.lis.each do |li|
  fail unless @browser.div(:class => 'description').exists?
end

Fixed my previous error but now the test pass even when there is nothing in the list. :/

Sample HTML

              Brand

              Ola

              Description

              Test Data

Body:
For your sample html, this code prints success. Are you sure it does not work for you?

bb = browser.ul(:id => 'ul-list')
bb.lis.each do |li|
  puts 'success' if li.td(:class => 'info_return_description').exists?
end


问:
Selenium Chromedriver "Failed to Load Extension"
Can anyone point me in the right direction?

I'm running Chrome using the following Python code:

```<code>opts = Options()
opts.add_argument("--disable-extensions")
self.browser = webdriver.Chrome(chrome_options=opts)
</code>```

I am receiving the following error:

I've tried disabling extensions through code... as well as actually removing all extensions from Chrome before running the code. Neither solution has worked.

I'm running code using the following:

ChromeDriver 2.28

Chrome V57.0.2987.110

Selenium 3.3.1

Python 2.7

答:
Here's the solution to your Question:

Add the following ChromeOptions to overcome the error:

```<code>ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
options.addArguments("start-maximized");
options.addArguments("--js-flags=--expose-gc");
options.addArguments("--enable-precise-memory-info");
options.addArguments("--disable-popup-blocking");
options.addArguments("--disable-default-apps");
options.addArguments("test-type=browser");
options.addArguments("disable-infobars");
WebDriver driver = new ChromeDriver(options);`
</code>```

Apologies as the code is in Java, you have to convert it into Python format.

Let me know if this helps you.

Body:
Can anyone point me in the right direction?

I'm running Chrome using the following Python code:

opts = Options()
opts.add_argument("--disable-extensions")
self.browser = webdriver.Chrome(chrome_options=opts)

I am receiving the following error:

I've tried disabling extensions through code... as well as actually removing all extensions from Chrome before running the code. Neither solution has worked.

I'm running code using the following:

ChromeDriver 2.28

Chrome V57.0.2987.110

Selenium 3.3.1

Python 2.7

Body:
Here's the solution to your Question:

Add the following ChromeOptions to overcome the error:

ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
options.addArguments("start-maximized");
options.addArguments("--js-flags=--expose-gc");
options.addArguments("--enable-precise-memory-info");
options.addArguments("--disable-popup-blocking");
options.addArguments("--disable-default-apps");
options.addArguments("test-type=browser");
options.addArguments("disable-infobars");
WebDriver driver = new ChromeDriver(options);`

Apologies as the code is in Java, you have to convert it into Python format.

Let me know if this helps you.


问:
Change column width bootstrap tables
I have a static PHP site I'm using Bootstrap on. The tables are controlled by Bootstrap.

I've noticed that I have seemingly no control over the lengths of the TD sections so that I can prevent the phone numbers, etc..., from wrapping. As you can see there is plenty of space on the end, just don't know how to spread that space out.

I tried inline widths on the  but nothing happens:

```<code>  <table class="table table-condensed table-striped  table-hover">
  <thead>
    <tr>
        <th>#</th>
        <th width="12%">Last Name</th>
        <th width="12%">First Name</th>
        <th width="12%">Spouse's Name</th>
        <th width="20%">Address</th>
        <th width="5%">City</th>
        <th  width="12%"class="did_phone">Phone</th>
        <th width="15%">E-Mail</th>
         <th width="15%"></th>
    </tr>
  </thead>
  <tbody>
</code>```

So... how does one change the  widths, make adjustments so there is no wrapping, in Bootstrap?

答:
You could try using this style="width:12%" in each th.

Example:

```<code><table class="table table-bordered">
 <thead>
 <tr>
    <th>#</th>
    <th style="width:12%">Last Name</th>
    <th style="width:12%">First Name</th>
    <th style="width:12%">Spouse's Name</th>
    <th style="width:20%">Address</th>
    <th style="width:5%">City</th>
    <th  style="width:12%"class="did_phone">Phone</th>
    <th style="width:15%">E-Mail</th>
 </tr>
 </thead>
 <tbody>
    <tr>
        <td>1</td>
        <td>Last Name</td>
        <td>First Name</td>
        <td>Spouse's Name</td>
        <td>Adress</td>
        <td>City</td>
        <td>Phone</td>
        <td>E-Mail</td>
    </tr>
 </tbody>
</table>
</code>```

Title: Change column width bootstrap tables

Body:
I have a static PHP site I'm using Bootstrap on. The tables are controlled by Bootstrap.

I've noticed that I have seemingly no control over the lengths of the TD sections so that I can prevent the phone numbers, etc..., from wrapping. As you can see there is plenty of space on the end, just don't know how to spread that space out.

I tried inline widths on the  but nothing happens:

        #
        Last Name
        First Name
        Spouse's Name
        Address
        City
        Phone
        E-Mail

So... how does one change the  widths, make adjustments so there is no wrapping, in Bootstrap?

Body:
You could try using this style="width:12%" in each th.

Example:

<table class="table table-bordered">
 <thead>
 <tr>
    <th>#</th>
    <th style="width:12%">Last Name</th>
    <th style="width:12%">First Name</th>
    <th style="width:12%">Spouse's Name</th>
    <th style="width:20%">Address</th>
    <th style="width:5%">City</th>
    <th  style="width:12%"class="did_phone">Phone</th>
    <th style="width:15%">E-Mail</th>
 </tr>
 </thead>
 <tbody>
    <tr>
        <td>1</td>
        <td>Last Name</td>
        <td>First Name</td>
        <td>Spouse's Name</td>
        <td>Adress</td>
        <td>City</td>
        <td>Phone</td>
        <td>E-Mail</td>
    </tr>
 </tbody>
</table>


问:
powershell how to setup parameter as variables
Powershell how to setup parameter as variable ?

The code like this:

```<code>get-stat -Entity (get-vmhost ) -Disk -Start 'date-time' -Finish 'date-time'
</code>```

For parameter -Disk, there are other options can be used. I want to setup this parameter as a variable by the following so I can choose what to run for.

```<code>$item = read-host -prompt 'Select Disk, CPU, Network or Common'
get-stat -Entity (get-vmhost ) -$item -Start 'date-time' -Finish 'date-time'
</code>```

But it wont work returning error message "A positional parameter can't be found"

Any solution to that please?

答:
you can use PowerShell Splatting a way of bundling parameters to send to a command:</p>

```<code>$item = read-host -prompt 'Select Disk, CPU, Network or Common'
$aB = @{$item = $true;
       Entity = (get-vmhost );
       Start = 'date-time';
       Finish  = 'date-time'}
get-stat @aB
</code>```

Body:
Powershell how to setup parameter as variable ?

The code like this:

get-stat -Entity (get-vmhost ) -Disk -Start 'date-time' -Finish 'date-time'

For parameter -Disk, there are other options can be used. I want to setup this parameter as a variable by the following so I can choose what to run for.

$item = read-host -prompt 'Select Disk, CPU, Network or Common'
get-stat -Entity (get-vmhost ) -$item -Start 'date-time' -Finish 'date-time'

But it wont work returning error message "A positional parameter can't be found"

Any solution to that please?

Body:
you can use PowerShell Splatting a way of bundling parameters to send to a command:

$item = read-host -prompt 'Select Disk, CPU, Network or Common'
$aB = @{$item = $true;
       Entity = (get-vmhost );
       Start = 'date-time';
       Finish  = 'date-time'}
get-stat @aB


问:
In Javascript, what is a sure way to loop through an array of 3 strings?
Something like this works, but looks a bit clumsy:

```<code>for (i in {foo: 1, bar: 1, wah: 1}) {  // loops through foo, bar, wah
  console.log(i + " haha");            // can view using Firebug or Chrome
}
</code>```

if using an array, I don't want to create any global temporary variable for the array...  Also, this has to work in any modern browser IE7 / FF / Chrome / Safari.  thanks.

答:
You want to be careful when using for in as you may get keys that are in the prototype chain and not actually part of the object. So in your example you'd want to use:</p>

```<code>var obj = {foo: 1, bar: 1, baz: 1};
for(var key in obj) {
   if(obj.hasOwnProperty(key)) {
       console.log(key, obj[key]); //key, value
   }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Something like this works, but looks a bit clumsy:

for (i in {foo: 1, bar: 1, wah: 1}) {  // loops through foo, bar, wah
  console.log(i + " haha");            // can view using Firebug or Chrome
}

if using an array, I don't want to create any global temporary variable for the array...  Also, this has to work in any modern browser IE7 / FF / Chrome / Safari.  thanks.

Body:
You want to be careful when using for in as you may get keys that are in the prototype chain and not actually part of the object. So in your example you'd want to use:

var obj = {foo: 1, bar: 1, baz: 1};
for(var key in obj) {
   if(obj.hasOwnProperty(key)) {
       console.log(key, obj[key]); //key, value
   }
}


问:
Access control for Apache spark
Is it possible to set access controls for Apache spark such that we can control which users can submit jobs via spark-submit. Ideally this would integrate with active directory so permissions signs could be controlled by ad groups.</p>

答:
Spark uses Kerberos and that can be configured to work with Active Directory.
Check: </p>

```<code>http://spark.apache.org/docs/latest/configuration.html
http://spark.apache.org/docs/latest/security.html
https://www.slideshare.net/cloudera/securing-your-apache-spark-applications
</code>```

<p>Some settings to consider: </p>

```<code>spark.acls.enable # true
spark.admin.acls # set to admin users
spark.modify.acls # user who can modify
</code>```

Title: Access control for Apache spark

Body:
Spark uses Kerberos and that can be configured to work with Active Directory.
Check:

http://spark.apache.org/docs/latest/configuration.html
http://spark.apache.org/docs/latest/security.html
https://www.slideshare.net/cloudera/securing-your-apache-spark-applications

Some settings to consider:

spark.acls.enable # true
spark.admin.acls # set to admin users
spark.modify.acls # user who can modify


问:
Segoe UI Semilight in CSS not working on Chrome
I'm trying to use Segoe UI Light, Segoe UI Semilight, and Segoe UI on a web page. It renders great in IE, but Chrome doesn't seem to differentiate between Light and Semilight.

I'm using the CSS suggested on this StackOverflow answer, as suggested by Microsoft.

```<code>/*
Explicitly define a Segoe UI font-family so that we can assign Segoe UI
Semilight to an appropriate font-weight.
*/
@font-face {
    font-family: "Segoe UI";
    font-weight: 200;
    src: local("Segoe UI Light");
}
@font-face {
    font-family: "Segoe UI";
    font-weight: 300;
    src: local("Segoe UI Semilight");
}
@font-face {
    font-family: "Segoe UI";
    font-weight: 400;
    src: local("Segoe UI");
}
@font-face {
    font-family: "Segoe UI";
    font-weight: 600;
    src: local("Segoe UI Semibold");
}
@font-face {
    font-family: "Segoe UI";
    font-weight: 700;
    src: local("Segoe UI Bold");
}
@font-face {
    font-family: "Segoe UI";
    font-style: italic;
    font-weight: 400;
    src: local("Segoe UI Italic");
}
@font-face {
    font-family: "Segoe UI";
    font-style: italic;
    font-weight: 700;
    src: local("Segoe UI Bold Italic");
}
</code>```

The following jsfiddle shows various font weights of Segoe UI, including Light and Semilight:
http://jsfiddle.net/nHXDA/

Here's the results.

Chrome:

IE:

Any ideas on how to fix this?

答:
Beside the fact that your font will only be displayed on Windows Devices correctly while it will be ignored on all others that don't have the font installed you need to make sure you have a matching fallback in place.

The second thing is that your font definition is wrong and doesn't work cross browser. While Internet Explorer is able to use directly the correct font file, specified by src: local("Segoe UI Semibold"); all other browser need to refer to the font family. src: local("Segoe UI");.

In case of semibold you need to specify the font definition like this:

```<code>@font-face {
    font-family: "Segoe UI";
    font-weight: 300;
    src: local("Segoe UI Semilight"), local("Segoe UI");
}
</code>```

Once you fixed your font definition it should look like the following screenshot shows. In those Screenshots you also see that if the font-family is specified with the full name instead of the font family name the font will fallback to Times New Roman. This happens because the browser cannot resolve the font name, which seems to be exclusive for IE.

Not sure if it is because I use the local font and if the available web font have been fixed you need to make additional adjustments to look the font good. It might be the case that the web fonts has special hinted for web use.

Body:
I'm trying to use Segoe UI Light, Segoe UI Semilight, and Segoe UI on a web page. It renders great in IE, but Chrome doesn't seem to differentiate between Light and Semilight.

I'm using the CSS suggested on this StackOverflow answer, as suggested by Microsoft.

/*
Explicitly define a Segoe UI font-family so that we can assign Segoe UI
Semilight to an appropriate font-weight.
*/
@font-face {
    font-family: "Segoe UI";
    font-weight: 200;
    src: local("Segoe UI Light");
}
@font-face {
    font-family: "Segoe UI";
    font-weight: 300;
    src: local("Segoe UI Semilight");
}
@font-face {
    font-family: "Segoe UI";
    font-weight: 400;
    src: local("Segoe UI");
}
@font-face {
    font-family: "Segoe UI";
    font-weight: 600;
    src: local("Segoe UI Semibold");
}
@font-face {
    font-family: "Segoe UI";
    font-weight: 700;
    src: local("Segoe UI Bold");
}
@font-face {
    font-family: "Segoe UI";
    font-style: italic;
    font-weight: 400;
    src: local("Segoe UI Italic");
}
@font-face {
    font-family: "Segoe UI";
    font-style: italic;
    font-weight: 700;
    src: local("Segoe UI Bold Italic");
}

The following jsfiddle shows various font weights of Segoe UI, including Light and Semilight:
http://jsfiddle.net/nHXDA/

Here's the results.

Chrome:

IE:

Any ideas on how to fix this?

Body:
Beside the fact that your font will only be displayed on Windows Devices correctly while it will be ignored on all others that don't have the font installed you need to make sure you have a matching fallback in place.

The second thing is that your font definition is wrong and doesn't work cross browser. While Internet Explorer is able to use directly the correct font file, specified by src: local("Segoe UI Semibold"); all other browser need to refer to the font family. src: local("Segoe UI");.

In case of semibold you need to specify the font definition like this:

@font-face {
    font-family: "Segoe UI";
    font-weight: 300;
    src: local("Segoe UI Semilight"), local("Segoe UI");
}

Once you fixed your font definition it should look like the following screenshot shows. In those Screenshots you also see that if the font-family is specified with the full name instead of the font family name the font will fallback to Times New Roman. This happens because the browser cannot resolve the font name, which seems to be exclusive for IE.

Not sure if it is because I use the local font and if the available web font have been fixed you need to make additional adjustments to look the font good. It might be the case that the web fonts has special hinted for web use.


问:
How to set headers properly for suds soap client
I am trying to send a request to an api using suds client.

The request is formed like this:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v20="https://API">
   <soapenv:Header>
      <v20:apiHeader>
         <v20:username>username</v20:username>
         <v20:password>password</v20:password>
         <!--Optional:-->
         <v20:name>?</v20:name>
      </v20:apiHeader>
   </soapenv:Header>
   <soapenv:Body>
      <v20:getLoginDetails/>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

I am sending the request for this like:

```<code>client = Client('https://wsdl', faults=False)

client.set_options(headers={'username': username 'authToken': auth_token, 'name': ''})
client.service.getLoginDetails()
</code>```

the error I am receiving is:

```<code>(<HTTPStatus.INTERNAL_SERVER_ERROR: 500>, (Fault){
   faultcode = "soap:Server"
   faultstring = "apiHeader should not be null"
   detail = ""
 })
</code>```

Is this how I should be sending the request? It is definitely something to do with the apiHeader I think; not sure what though, I get the same error using this:

```<code>username = Element('username').setText(name)
        password= Element('password').setText(pass)
        header_list = [username, pass]
        self.client.set_options(soapheaders=header_list)
        return self.client.service.getLoginDetails()
</code>```

答:
I've made this work by using something similar to this:</p>

```<code>from suds.sax.element import Element
from suds.sax.attribute import Attribute
code = Element('serviceCode').setText('PABB4BEIJING')
pwd = Element('servicePwd').setText('QWERTPABB')

reqsoapheader = Element('ReqSOAPHeader').insert(code)
reqsoap_attribute = Attribute('xmlns', "http://schemas.acme.eu/")
reqsoapheader.append(reqsoap_attribute)

client.set_options(soapheaders=reqsoapheader)
</code>```

Body:
I am trying to send a request to an api using suds client.

The request is formed like this:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v20="https://API">
   <soapenv:Header>
      <v20:apiHeader>
         <v20:username>username</v20:username>
         <v20:password>password</v20:password>

         <v20:name>?</v20:name>
      </v20:apiHeader>
   </soapenv:Header>
   <soapenv:Body>
      <v20:getLoginDetails/>
   </soapenv:Body>
</soapenv:Envelope>

I am sending the request for this like:

client = Client('https://wsdl', faults=False)

client.set_options(headers={'username': username 'authToken': auth_token, 'name': ''})
client.service.getLoginDetails()

the error I am receiving is:

(<HTTPStatus.INTERNAL_SERVER_ERROR: 500>, (Fault){
   faultcode = "soap:Server"
   faultstring = "apiHeader should not be null"
   detail = ""
 })

Is this how I should be sending the request? It is definitely something to do with the apiHeader I think; not sure what though, I get the same error using this:

username = Element('username').setText(name)
        password= Element('password').setText(pass)
        header_list = [username, pass]
        self.client.set_options(soapheaders=header_list)
        return self.client.service.getLoginDetails()

Body:
I've made this work by using something similar to this:

from suds.sax.element import Element
from suds.sax.attribute import Attribute
code = Element('serviceCode').setText('PABB4BEIJING')
pwd = Element('servicePwd').setText('QWERTPABB')

reqsoapheader = Element('ReqSOAPHeader').insert(code)
reqsoap_attribute = Attribute('xmlns', "http://schemas.acme.eu/")
reqsoapheader.append(reqsoap_attribute)

client.set_options(soapheaders=reqsoapheader)


问:
stringsasfactors=FALSE equivalent in sqlfetch r
I have a RODBC connection using odbcConnect to a DB.
I am reading in a table into a variable.

This table has a text column, however when I submit a subset on the text column, I get a factor.
I am looking for a stringsasfactors=FALSE equivalent while reading a table using RODBC.
Any thoughts on how I might be able to achieve this?
Thanks!

答:
Use eg the stringsAsFactors option to sqlQuery.  Documentation is eg here.

Modifying the basic example from the help page:

```<code>channel <- odbcConnect("test")
sqlSave(channel, USArrests, rownames = "State", verbose = TRUE)
options(dec=".") # optional, if DBMS is not locale-aware or set to ASCII
## note case of State, Murder, Rape are DBMS-dependent,
## and some drivers need column and table names double-quoted.
sqlQuery(channel, paste("select State, Murder from USArrests",
                         "where Rape > 30 order by Murder"),
         stringsAsFactors=FALSE)   ## your option here
close(channel)
</code>```

As sqlFetch() passes arguments through via ..., it will work the same way.  Just add stringsAsFactors=FALSE, or even set it globally via options().

Body:
Use eg the stringsAsFactors option to sqlQuery.  Documentation is eg here.

Modifying the basic example from the help page:

channel <- odbcConnect("test")
sqlSave(channel, USArrests, rownames = "State", verbose = TRUE)
options(dec=".") # optional, if DBMS is not locale-aware or set to ASCII
## note case of State, Murder, Rape are DBMS-dependent,
## and some drivers need column and table names double-quoted.
sqlQuery(channel, paste("select State, Murder from USArrests",
                         "where Rape > 30 order by Murder"),
         stringsAsFactors=FALSE)   ## your option here
close(channel)

As sqlFetch() passes arguments through via ..., it will work the same way.  Just add stringsAsFactors=FALSE, or even set it globally via options().


问:
How to clear elements created programmatically from UITableViewCell before it's reuse

I am writing an application in Swift 3 that involves a UITableView. I am creating my table view cells pragmatically. The problem I am experiencing is that the cell's label text is persistent after the .reloadData() function. Is there a function to clear all elements and formatting from a cell before it's use? I am instantiating the UILabel via code and cannot access it across iterations. Unfortunately, I have already put a ton of time into programmatically creating the table, so I'd like to avoid going back and making a cell class if possible.

I am planning to use a function something like this:

```<code>var label: UILabel
                if reloadCount > 0 {
                    //clear all formatting from the cell
                }

                    label = UILabel(frame: CGRect(x: 30, y: 0, width: self.screenWidth - 100, height: 50))
                    label.textAlignment = .center
                    label.lineBreakMode = NSLineBreakMode.byWordWrapping
                    label.textColor = UIColor(red: 127.0/255, green: 140.0/255, blue: 142.0/255, alpha: 1.0)
                    label.font = UIFont(name: "Tahoma", size: CGFloat(22))
                    label.numberOfLines = 0
                    label.tag = Int(self.thoughtFeed[indexPath.row].dbId!)!
                    label.text = thoughtFeed[indexPath.row].thoughtText!.fromBase64()
                    label.isUserInteractionEnabled = true
                    label.addGestureRecognizer(labelTap)
                    cell.addSubview(label)
</code>```

Thank you very much for the help.

答:
You'll need to somehow "remember" the UILabel and either reuse it or remove it. Since you say you don't want to subclass UITableViewCell you can use tags to get a reference to your label. In your cellForRowAtIndexPath do something like this:

```<code>if let label = cell.viewWithTag(42) as? UILabel {
    // now you have a reference to the existing label.
    // Just update the text (or whatever you need to do)
} else {
    label = UILabel(frame: CGRect(x: 30, y: 0, width: self.screenWidth - 100, height: 50))

    // add a tag so we can remember it when we dequeue a cell later
    label.tag = 42
    cell.addSubview(label)
}
</code>```

Body:
I am writing an application in Swift 3 that involves a UITableView. I am creating my table view cells pragmatically. The problem I am experiencing is that the cell's label text is persistent after the .reloadData() function. Is there a function to clear all elements and formatting from a cell before it's use? I am instantiating the UILabel via code and cannot access it across iterations. Unfortunately, I have already put a ton of time into programmatically creating the table, so I'd like to avoid going back and making a cell class if possible.

I am planning to use a function something like this:

var label: UILabel
                if reloadCount > 0 {
                    //clear all formatting from the cell
                }

                    label = UILabel(frame: CGRect(x: 30, y: 0, width: self.screenWidth - 100, height: 50))
                    label.textAlignment = .center
                    label.lineBreakMode = NSLineBreakMode.byWordWrapping
                    label.textColor = UIColor(red: 127.0/255, green: 140.0/255, blue: 142.0/255, alpha: 1.0)
                    label.font = UIFont(name: "Tahoma", size: CGFloat(22))
                    label.numberOfLines = 0
                    label.tag = Int(self.thoughtFeed[indexPath.row].dbId!)!
                    label.text = thoughtFeed[indexPath.row].thoughtText!.fromBase64()
                    label.isUserInteractionEnabled = true
                    label.addGestureRecognizer(labelTap)
                    cell.addSubview(label)

Thank you very much for the help.

Body:
You'll need to somehow "remember" the UILabel and either reuse it or remove it. Since you say you don't want to subclass UITableViewCell you can use tags to get a reference to your label. In your cellForRowAtIndexPath do something like this:

if let label = cell.viewWithTag(42) as? UILabel {
    // now you have a reference to the existing label.
    // Just update the text (or whatever you need to do)
} else {
    label = UILabel(frame: CGRect(x: 30, y: 0, width: self.screenWidth - 100, height: 50))

    // add a tag so we can remember it when we dequeue a cell later
    label.tag = 42
    cell.addSubview(label)
}


问:
Cloning objects in Fabric.js
I am cloning a selected object on a canvas in Fabric.js using a simple function.

```<code>function duplicateObj() {
  var obj = canvas.getActiveObject();
  var clone = fabric.util.object.clone(obj);
  clone.set({left: 100,top: 100});
  canvas.add(clone);
}
</code>```

That works absolutely fine. Now if I work with the object and the clone is not required anymore and I select and delete it, both objects, the clone and the original object are deleted. The delete function is:

```<code>function deleteObj() {
  var obj = canvas.getActiveObject();
  canvas.fxRemove(obj);
}
</code>```

The objects are the same. Is there are way to clone objects and make the clone independent of the of the original? I tried this:

```<code>function duplicateObj() {
  var obj = canvas.getActiveObject();
  var clone = fabric.util.object.clone(obj);
  clone.initialize();
  $.extend(clone, obj);
  fabric.util.object.extend(clone, obj);
  clone.set({left: 100,top: 100});
  canvas.add(clone);
}
</code>```

It works, however the objects are the same again and if I only use initialize I am ending up with an object that has now properties set.

答:
Here is my implementation of cloning selected object or group.

https://jsfiddle.net/milanhlinak/rxtjm7w0/1/

```<code><!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src="lib/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="lib/fabric.min.js"></script>
</head>

<body>

    <button onclick="cloneSelected()">Clone selected</button>
    <canvas id="canvas" style="border: 1px solid #cccccc"></canvas>

    <script>
        var canvas = new fabric.Canvas('canvas', {
            width: 500,
            height: 500,
        });

        canvas.add(new fabric.Rect({
            left: 100,
            top: 100,
            width: 50,
            height: 50,
            fill: '#faa'

        }));
        canvas.add(new fabric.Circle({
            left: 300,
            top: 300,
            radius: 25,
            fill: '#afa'
        }));

        function cloneSelected() {
            console.log('cloneSelected');

            var activeObject = canvas.getActiveObject();
            var activeGroup = canvas.getActiveGroup();

            if (activeObject) {
                console.log('object selected');

                var clonedObject = null;
                var json = activeObject.toJSON();
                if (json.type == 'rect') {
                    clonedObject = new fabric.Rect(json);
                } else if (json.type == 'circle') {
                    clonedObject = new fabric.Circle(json);
                } else {
                    console.log('unknown object type: ' + json.type);
                    return;
                }

                var oldLeft = clonedObject.getLeft();
                var oldTop = clonedObject.getTop();

                clonedObject.setLeft(oldLeft + 10);
                clonedObject.setTop(oldTop + 10);

                var boundingRect = clonedObject.getBoundingRect(true);
                if (boundingRect.left + boundingRect.width > canvas.getWidth()) {
                    clonedObject.setLeft(oldLeft);
                }
                if (boundingRect.top + boundingRect.height > canvas.getHeight()) {
                    clonedObject.setTop(oldTop);
                }

                canvas.add(clonedObject);
                canvas.setActiveObject(clonedObject);
                canvas.renderAll();
                console.log('selected object cloned');

            } else if (activeGroup) {
                console.log('group selected');

                canvas.discardActiveGroup();

                var clonedObjects = [];

                activeGroup.getObjects().forEach(function (object) {

                    var clonedObject = null;

                    var json = object.toJSON();
                    if (json.type == 'rect') {
                        clonedObject = new fabric.Rect(json);
                    } else if (json.type === 'circle') {
                        clonedObject = new fabric.Circle(json);
                    } else {
                        console.log('unknown object type: ' + json.type);
                        return;
                    }

                    clonedObject.setCoords();
                    canvas.add(clonedObject);
                    clonedObject.set('active', true);
                    clonedObjects.push(clonedObject);
                });

                var group = new fabric.Group(clonedObjects.reverse(), {
                    canvas: canvas
                });

                group.addWithUpdate(null);

                var oldLeft = group.getLeft();
                var oldTop = group.getTop();

                group.setLeft(oldLeft + 10);
                group.setTop(oldTop + 10);

                var boundingRect = group.getBoundingRect(true);
                if (boundingRect.left + boundingRect.width > canvas.getWidth()) {
                    group.setLeft(oldLeft);
                }
                if (boundingRect.top + boundingRect.height > canvas.getHeight()) {
                    group.setTop(oldTop);
                }

                group.setCoords();
                canvas.setActiveGroup(group);
                group.saveCoords();
                canvas.renderAll();
                console.log('selected objects cloned');
            } else {
                console.log('no object selected');
            }

        }
    </script>

</body>

</html>
</code>```

Title: Cloning objects in Fabric.js

Body:
I am cloning a selected object on a canvas in Fabric.js using a simple function.

function duplicateObj() {
  var obj = canvas.getActiveObject();
  var clone = fabric.util.object.clone(obj);
  clone.set({left: 100,top: 100});
  canvas.add(clone);
}

That works absolutely fine. Now if I work with the object and the clone is not required anymore and I select and delete it, both objects, the clone and the original object are deleted. The delete function is:

function deleteObj() {
  var obj = canvas.getActiveObject();
  canvas.fxRemove(obj);
}

The objects are the same. Is there are way to clone objects and make the clone independent of the of the original? I tried this:

function duplicateObj() {
  var obj = canvas.getActiveObject();
  var clone = fabric.util.object.clone(obj);
  clone.initialize();
  $.extend(clone, obj);
  fabric.util.object.extend(clone, obj);
  clone.set({left: 100,top: 100});
  canvas.add(clone);
}

It works, however the objects are the same again and if I only use initialize I am ending up with an object that has now properties set.

Body:
Here is my implementation of cloning selected object or group.

https://jsfiddle.net/milanhlinak/rxtjm7w0/1/

<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src="lib/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="lib/fabric.min.js"></script>
</head>

<body>

    <button onclick="cloneSelected()">Clone selected</button>
    <canvas id="canvas" style="border: 1px solid #cccccc"></canvas>

    <script>
        var canvas = new fabric.Canvas('canvas', {
            width: 500,
            height: 500,
        });

        canvas.add(new fabric.Rect({
            left: 100,
            top: 100,
            width: 50,
            height: 50,
            fill: '#faa'

        }));
        canvas.add(new fabric.Circle({
            left: 300,
            top: 300,
            radius: 25,
            fill: '#afa'
        }));

        function cloneSelected() {
            console.log('cloneSelected');

            var activeObject = canvas.getActiveObject();
            var activeGroup = canvas.getActiveGroup();

            if (activeObject) {
                console.log('object selected');

                var clonedObject = null;
                var json = activeObject.toJSON();
                if (json.type == 'rect') {
                    clonedObject = new fabric.Rect(json);
                } else if (json.type == 'circle') {
                    clonedObject = new fabric.Circle(json);
                } else {
                    console.log('unknown object type: ' + json.type);
                    return;
                }

                var oldLeft = clonedObject.getLeft();
                var oldTop = clonedObject.getTop();

                clonedObject.setLeft(oldLeft + 10);
                clonedObject.setTop(oldTop + 10);

                var boundingRect = clonedObject.getBoundingRect(true);
                if (boundingRect.left + boundingRect.width > canvas.getWidth()) {
                    clonedObject.setLeft(oldLeft);
                }
                if (boundingRect.top + boundingRect.height > canvas.getHeight()) {
                    clonedObject.setTop(oldTop);
                }

                canvas.add(clonedObject);
                canvas.setActiveObject(clonedObject);
                canvas.renderAll();
                console.log('selected object cloned');

            } else if (activeGroup) {
                console.log('group selected');

                canvas.discardActiveGroup();

                var clonedObjects = [];

                activeGroup.getObjects().forEach(function (object) {

                    var clonedObject = null;

                    var json = object.toJSON();
                    if (json.type == 'rect') {
                        clonedObject = new fabric.Rect(json);
                    } else if (json.type === 'circle') {
                        clonedObject = new fabric.Circle(json);
                    } else {
                        console.log('unknown object type: ' + json.type);
                        return;
                    }

                    clonedObject.setCoords();
                    canvas.add(clonedObject);
                    clonedObject.set('active', true);
                    clonedObjects.push(clonedObject);
                });

                var group = new fabric.Group(clonedObjects.reverse(), {
                    canvas: canvas
                });

                group.addWithUpdate(null);

                var oldLeft = group.getLeft();
                var oldTop = group.getTop();

                group.setLeft(oldLeft + 10);
                group.setTop(oldTop + 10);

                var boundingRect = group.getBoundingRect(true);
                if (boundingRect.left + boundingRect.width > canvas.getWidth()) {
                    group.setLeft(oldLeft);
                }
                if (boundingRect.top + boundingRect.height > canvas.getHeight()) {
                    group.setTop(oldTop);
                }

                group.setCoords();
                canvas.setActiveGroup(group);
                group.saveCoords();
                canvas.renderAll();
                console.log('selected objects cloned');
            } else {
                console.log('no object selected');
            }

        }
    </script>

</body>

</html>


问:
RULES(NOEVENPACK) in Enterprise COBOL. Why we need to check if packed-decimal is not in even digits?
I am reading the following statement and I am not sure why we must have the packed-decimal in odd digits? Is the following statement true, that you can only have odd number of digits in hardware? Can you give me a example to show why it says that?

RULES(NOEVENPACK) This compiler option will tell you if you
  accidentally define a Pack Decimal data item within even number of
  digits. You can only have odd number of digits in hardware. If you
  have one byte you have one digit , 2 byte you have 3 digit, 3 byte
  -->5 digit.

答:
In a packed-decimal field, the right-most half-byte (nybble) is the sign position. Each other half-byte in the field is a digit, 0-9.

This means that the storage occupied by a packed-decimal field represents an odd number of digits. You have no choice over that.

If you define PACKED-DECIMAL PIC 9(4) you get

```<code>?NNNNS
</code>```

Where N is a digit (see, there are four of them) and S is the sign (since the field is defined as unsigned, it will have a sign of F, which is always treated as positive).

What about that ?. It can't not be there. Since it can't not be there, the compiler has to generate code so that it can only contain a zero, which won't affect the value of the field.

If you define PACKED-DECIMAL PIC 9(5) you get

```<code>NNNNNS
</code>```

Five digits, sign, and nothing else for the compiler to worry about. No code generated beyond what is otherwise required for the field.

So your code runs faster.

You may wonder "how much does that matter?". If you consider how many packed-decimal fields you may see in a program, if each of those, every time it was referenced, had code to make the first digit zero, you've got quite a lot of code, for every pass through the program.

On the Mainframe you, generally, pay for resource-usage. If you avoid that in 5,000 programs which are processing 10,000,000 transactions a day, 365 days a year, then it adds up.

Body:
In a packed-decimal field, the right-most half-byte (nybble) is the sign position. Each other half-byte in the field is a digit, 0-9.

This means that the storage occupied by a packed-decimal field represents an odd number of digits. You have no choice over that.

If you define PACKED-DECIMAL PIC 9(4) you get

?NNNNS

Where N is a digit (see, there are four of them) and S is the sign (since the field is defined as unsigned, it will have a sign of F, which is always treated as positive).

What about that ?. It can't not be there. Since it can't not be there, the compiler has to generate code so that it can only contain a zero, which won't affect the value of the field.

If you define PACKED-DECIMAL PIC 9(5) you get

NNNNNS

Five digits, sign, and nothing else for the compiler to worry about. No code generated beyond what is otherwise required for the field.

So your code runs faster.

You may wonder "how much does that matter?". If you consider how many packed-decimal fields you may see in a program, if each of those, every time it was referenced, had code to make the first digit zero, you've got quite a lot of code, for every pass through the program.

On the Mainframe you, generally, pay for resource-usage. If you avoid that in 5,000 programs which are processing 10,000,000 transactions a day, 365 days a year, then it adds up.


问:
Does anyone know of a good quick and dirty text / grammar parser?
I have a "mad lib" scenario in which I want to

a) determine the parts of speech of every (or most) words in a sentence

b) have the user select alternatives to those words - or replace them computationally with equivalent words

I looked at the Stanford parser but its a bit slow ... any suggestions?

答:
Use a POS tagger

If you're just using the part-of-speech (POS) tags and not the parse trees, you don't actually need to use a parser. Instead, you can just use a standalone POS tagger.

POS tagging is much faster than phrase-structure parsing. On a Xeon E5520, the Stanford POS tagger can tag 1700 sentences in 3 seconds, while the same data takes about 10 minutes to parse using the Stanford Parser (Cer et al. 2010).

There's a fairly comprehensive list of other POS taggers here.


问:
bathtub model sprout using decision rules
newbie in netlogo here. I'm simulating a flood model using cellular-automata. It's just a simple one -  cell should be filled (change color) or sprout if water > elevation.

For a dummy code, I'm trying to do it this way:

```<code>to go
    ask patches with [pcolor != blue] ;remove ocean
    water_rise
    tick
end

 to water_rise ; saturates cell
  if not any? turtles [
    ask patch x-breach y-breach [     ;;; This will be the breach patch, will start to fill at first tick, a specific location in my map
      set cell-storage elevation * fill-rate
    ]
  ]
  ask patches [
    ;;; This has a patch check if any neighbors have sprouted.
    ;;; If any have, that patch starts to fill.
    if any? neighbors4 with [ any? turtles-here ] [
       set cell-storage elevation * fill-rate
      let minv min [ cell-storage ] of patches
      let maxv max [ cell-storage ] of patches
      set pcolor scale-color green cell-storage 0 5 ;idea is to have a graduated color depending on fill stage
    ]
  ]
  ;;; Once all patches have had a chance this tick to fill,
  ;;; see if any are "full"
  ask patches [
    if cell-storage > elevation [
        ;; If the patch gets "full" and they have not already sprouted,
    if not any? turtles-here [
      sprout 1 [
        set color yellow
        set size 1
        set shape "square"
      ]
  ]

]
</code>```

]
end
Thanks in advance!

BTW, I'm working on a DEM re: elevation values.

I set fill-rate as a slider with 0.3 for now.

-Nands

答:
I played around with this a little and it seems to me like you want your starting patch to fill up, and once it hits its maximum value, to start flooding into other cells that repeat the process. I think the main problem is that in your water-rise, you have are asking all patches with elevation greater than -9999 to first call the starting-point procedure and then also to sprout a turtle if they have any neighbors with elevation is less than cell-storage. It appears that all patches satisfy that condition, so all patches will sprout a turtle.

It may work better to rework your flow of logic, so that filling up your breach patch is independent of other patches. Something like:

```<code>to water_rise ; saturates cell
  if not any? turtles [
    ask patch 0 0 [     ;;; This would be your breach patch, will start to fill at first tick
      set cell-storage cell-storage + fill-rate
    ]
  ]
  ask patches [
    ;;; This has a patch check if any neighbors have sprouted.
    ;;; If any have, that patch starts to fill.
    if any? neighbors4 with [ any? turtles-here ] [
      set cell-storage cell-storage + fill-rate
    ]
  ]
  ;;; Once all patches have had a chance this tick to fill,
  ;;; see if any are "full"
  ask patches [
    if cell-storage > 0 [
      if cell-storage > 5 [
        set cell-storage 5
        ;; If the patch gets "full" and they have not already sprouted, sprout 1
        if not any? turtles-here [
          sprout 1 [
            set color yellow
            set size 0.5
            set shape "circle"
          ]
        ]
      ]
      set pcolor cell-storage + 82
    ]
  ]
end
</code>```

Full toy model with variables and setup here.

Obviously, you would need to modify your starting patch (I used 0 0 for convenience and simplicity). Additionally, I included fill-rate as a way to slow the rate of filling as more and more patches begin getting filled up.

Body:
newbie in netlogo here. I'm simulating a flood model using cellular-automata. It's just a simple one -  cell should be filled (change color) or sprout if water > elevation.

For a dummy code, I'm trying to do it this way:

to go
    ask patches with [pcolor != blue] ;remove ocean
    water_rise
    tick
end

 to water_rise ; saturates cell
  if not any? turtles [
    ask patch x-breach y-breach [     ;;; This will be the breach patch, will start to fill at first tick, a specific location in my map
      set cell-storage elevation * fill-rate
    ]
  ]
  ask patches [
    ;;; This has a patch check if any neighbors have sprouted.
    ;;; If any have, that patch starts to fill.
    if any? neighbors4 with [ any? turtles-here ] [
       set cell-storage elevation * fill-rate
      let minv min [ cell-storage ] of patches
      let maxv max [ cell-storage ] of patches
      set pcolor scale-color green cell-storage 0 5 ;idea is to have a graduated color depending on fill stage
    ]
  ]
  ;;; Once all patches have had a chance this tick to fill,
  ;;; see if any are "full"
  ask patches [
    if cell-storage > elevation [
        ;; If the patch gets "full" and they have not already sprouted,
    if not any? turtles-here [
      sprout 1 [
        set color yellow
        set size 1
        set shape "square"
      ]
  ]

]

]
end
Thanks in advance!

BTW, I'm working on a DEM re: elevation values.

I set fill-rate as a slider with 0.3 for now.

-Nands

Body:
I played around with this a little and it seems to me like you want your starting patch to fill up, and once it hits its maximum value, to start flooding into other cells that repeat the process. I think the main problem is that in your water-rise, you have are asking all patches with elevation greater than -9999 to first call the starting-point procedure and then also to sprout a turtle if they have any neighbors with elevation is less than cell-storage. It appears that all patches satisfy that condition, so all patches will sprout a turtle.

It may work better to rework your flow of logic, so that filling up your breach patch is independent of other patches. Something like:

to water_rise ; saturates cell
  if not any? turtles [
    ask patch 0 0 [     ;;; This would be your breach patch, will start to fill at first tick
      set cell-storage cell-storage + fill-rate
    ]
  ]
  ask patches [
    ;;; This has a patch check if any neighbors have sprouted.
    ;;; If any have, that patch starts to fill.
    if any? neighbors4 with [ any? turtles-here ] [
      set cell-storage cell-storage + fill-rate
    ]
  ]
  ;;; Once all patches have had a chance this tick to fill,
  ;;; see if any are "full"
  ask patches [
    if cell-storage > 0 [
      if cell-storage > 5 [
        set cell-storage 5
        ;; If the patch gets "full" and they have not already sprouted, sprout 1
        if not any? turtles-here [
          sprout 1 [
            set color yellow
            set size 0.5
            set shape "circle"
          ]
        ]
      ]
      set pcolor cell-storage + 82
    ]
  ]
end

Full toy model with variables and setup here.

Obviously, you would need to modify your starting patch (I used 0 0 for convenience and simplicity). Additionally, I included fill-rate as a way to slow the rate of filling as more and more patches begin getting filled up.


问:
React Native + CodePush: Do updates only appear the 2nd time the app has been loaded?
I have an app already in production on the app store. I just pushed an important bug fix through code push without going through the app store.

However, from my knowledge the user has to first open the app, fetch the updated code, and only on the 2nd time that the app is started will the update take effect. Is this true? If so, does that mean I should still try pushing a new version through the app store?

答:
If you released via Code Push using the { installMode: InstallMode.IMMEDIATE } parameter, the patch is applied instantly without app restart.

The user will see a white flash in the app when the patch is applied, and then the app is resumed.

https://microsoft.github.io/code-push/docs/tutorials.html

If an update is available, it will be silently downloaded, and
  installed the next time the app is restarted (either explicitly by the
  end user or by the OS). However, developers can modify the install
  behavior if they so choose, by leveraging the installMode parameter:

IMMEDIATE: The update will be applied to the running application immediately. The application will be reloaded with the new content immediately.

...


问:
Programmatically show Layout to preface an activity
What I want to do:

I want to have multiple activities each prefaced with a page explaining to the user what the activity is about.

What I'm currently doing:

So my main class BaseModuleActivity extends Activity and I am trying to write a function called showTutorial() which will explain the next steps to the users.

Here is my attempt in doing so:

```<code>public void showTutorial(String title, String explanation){
               setContentView(R.layout.tutorial_screen);
        TextView tv1 = (TextView)findViewById(R.id.tutoTextTitle);
        tv1.setText(title);

        TextView tv2 = (TextView)findViewById(R.id.tutoTextExplanation);
        tv2.setText(explanation);

        findViewById(R.id.tutoButton).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                //remove the tutorial's view
                findViewById(R.id.tutoLayout).setVisibility(View.GONE);
            }
        });
    }
</code>```

And this method is called in the following:

```<code>public class myFirstActivity extends BaseModuleActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_first);

        //First show tuto
        super.showTutorial(getString(R.string.upTitle),getString(R.string.upExplanation));

        //TODO then actually do the activity stuff
        /*
        (findViewById(R.id.next_button)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        */
    }
}
</code>```

Problem:

I think the problem is mainly conceptual. I don't know the best approach to do this and the approach I'm taking is not working.

What I'm doing is not working because the view just become empty. I thought setting the visibility of the linearLayout to gone would make it disappear and the actual activity will able to take place.

What I need:

I need to understand if I can do what I want with my approach or not? Or what approach should I take.

I found some similar questions. However, the answer to these questions didn't seem to fit my problem.

I also looked into layout inflater and fragment, but layout inflater seem to be more for listView and fragment uses layout inflater.

答:
Seems that what you want is actually an introduction. Take a look at this project:

https://github.com/rubengees/introduction

From each introduction page you can launch the correspondent activity.

Body:
What I want to do:

I want to have multiple activities each prefaced with a page explaining to the user what the activity is about.

What I'm currently doing:

So my main class BaseModuleActivity extends Activity and I am trying to write a function called showTutorial() which will explain the next steps to the users.

Here is my attempt in doing so:

public void showTutorial(String title, String explanation){
               setContentView(R.layout.tutorial_screen);
        TextView tv1 = (TextView)findViewById(R.id.tutoTextTitle);
        tv1.setText(title);

        TextView tv2 = (TextView)findViewById(R.id.tutoTextExplanation);
        tv2.setText(explanation);

        findViewById(R.id.tutoButton).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                //remove the tutorial's view
                findViewById(R.id.tutoLayout).setVisibility(View.GONE);
            }
        });
    }

And this method is called in the following:

public class myFirstActivity extends BaseModuleActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_first);

        //First show tuto
        super.showTutorial(getString(R.string.upTitle),getString(R.string.upExplanation));

        //TODO then actually do the activity stuff
        /*
        (findViewById(R.id.next_button)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        */
    }
}

Problem:

I think the problem is mainly conceptual. I don't know the best approach to do this and the approach I'm taking is not working.

What I'm doing is not working because the view just become empty. I thought setting the visibility of the linearLayout to gone would make it disappear and the actual activity will able to take place.

What I need:

I need to understand if I can do what I want with my approach or not? Or what approach should I take.

I found some similar questions. However, the answer to these questions didn't seem to fit my problem.

I also looked into layout inflater and fragment, but layout inflater seem to be more for listView and fragment uses layout inflater.


问:
How do you raise an instanced method from a static dependent property in C# similar to VB
So I am having a little bit of a problem converting from VB to C# code on a user control that is the base of other user controls.  Specifically event handling on a callback trying to get an instanced method from a static.  So I have this piece of C# for a dependent property:

```<code>public static readonly DependencyProperty ChartDataProperty = DependencyProperty.Register("ChartData", typeof(ObservableCollection<PlotTrend>), typeof(BaseChart), new UIPropertyMetadata(new ObservableCollection<PlotTrend>(), ChartDataChanged));
public ObservableCollection<PlotTrend> ChartData
{
   get { return (ObservableCollection<PlotTrend>)GetValue(ChartDataProperty); }
   set { SetValue(ChartDataProperty, value); }
}
</code>```

The callback should hookup like so:

```<code>public static void ChartDataChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
      var o = (BaseChart)d;

      if ((e.OldValue != null))
      {
        var OldCollection = e.OldValue as ObservableCollection<PlotTrend>;
        OldCollection.CollectionChanged -= o.CalculatePlotTrends;
      }

      if ((e.NewValue != null))
      {
        var NewCollection = e.NewValue as ObservableCollection<PlotTrend>;
        NewCollection.CollectionChanged += o.CalculatePlotTrends;
      }
}
</code>```

So this attempting to reach this:

```<code>public abstract void CalculatePlotTrends();
</code>```

That then gets to an instanced class inheriting from this base and it will fire on an override method.  Let me be clear this works fine as it should in VB but in C# this subscribing must have subtle differences.  I tried to see what Visual Studio might auto generate and it gives me static delegates, but I need to get an instanced method somehow.  I was using Telerik's Code converter and this was the code that originally worked just fine:

```<code>Public Shared Sub ChartDataChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs)
    Dim o = DirectCast(d, BaseChart)

    If Not IsNothing(e.OldValue) Then
      Dim OldCollection = TryCast(e.OldValue, ObservableCollection(Of PlotTrend))
      RemoveHandler OldCollection.CollectionChanged, AddressOf o.CalculatePlotTrends
    End If

    If Not IsNothing(e.NewValue) Then
      Dim NewCollection = TryCast(e.NewValue, ObservableCollection(Of PlotTrend))
      AddHandler NewCollection.CollectionChanged, AddressOf o.CalculatePlotTrends
    End If
  End Sub

  Public MustOverride Sub CalculatePlotTrends()
</code>```

答:
Change the signature of the CalulatePlotTrends event handler to this:

```<code>public abstract void CalculatePlotTrends(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e);
</code>```

In C# you must include the parameters in the signature of an event handler.

Body:
So I am having a little bit of a problem converting from VB to C# code on a user control that is the base of other user controls.  Specifically event handling on a callback trying to get an instanced method from a static.  So I have this piece of C# for a dependent property:

public static readonly DependencyProperty ChartDataProperty = DependencyProperty.Register("ChartData", typeof(ObservableCollection<PlotTrend>), typeof(BaseChart), new UIPropertyMetadata(new ObservableCollection<PlotTrend>(), ChartDataChanged));
public ObservableCollection<PlotTrend> ChartData
{
   get { return (ObservableCollection<PlotTrend>)GetValue(ChartDataProperty); }
   set { SetValue(ChartDataProperty, value); }
}

The callback should hookup like so:

public static void ChartDataChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
      var o = (BaseChart)d;

      if ((e.OldValue != null))
      {
        var OldCollection = e.OldValue as ObservableCollection<PlotTrend>;
        OldCollection.CollectionChanged -= o.CalculatePlotTrends;
      }

      if ((e.NewValue != null))
      {
        var NewCollection = e.NewValue as ObservableCollection<PlotTrend>;
        NewCollection.CollectionChanged += o.CalculatePlotTrends;
      }
}

So this attempting to reach this:

public abstract void CalculatePlotTrends();

That then gets to an instanced class inheriting from this base and it will fire on an override method.  Let me be clear this works fine as it should in VB but in C# this subscribing must have subtle differences.  I tried to see what Visual Studio might auto generate and it gives me static delegates, but I need to get an instanced method somehow.  I was using Telerik's Code converter and this was the code that originally worked just fine:

Public Shared Sub ChartDataChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs)
    Dim o = DirectCast(d, BaseChart)

    If Not IsNothing(e.OldValue) Then
      Dim OldCollection = TryCast(e.OldValue, ObservableCollection(Of PlotTrend))
      RemoveHandler OldCollection.CollectionChanged, AddressOf o.CalculatePlotTrends
    End If

    If Not IsNothing(e.NewValue) Then
      Dim NewCollection = TryCast(e.NewValue, ObservableCollection(Of PlotTrend))
      AddHandler NewCollection.CollectionChanged, AddressOf o.CalculatePlotTrends
    End If
  End Sub

  Public MustOverride Sub CalculatePlotTrends()

Body:
Change the signature of the CalulatePlotTrends event handler to this:

public abstract void CalculatePlotTrends(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e);

In C# you must include the parameters in the signature of an event handler.


问:
Destructure a map in another map?
I have the following data structure:

```<code>{:file #<File /foo.bar>, :resolution {:width 1280, :height 1024}}
</code>```

I would like to write a function that destructures the :resolution key into width and height symbols.  Something like

```<code>(defn to-directory-name [{{:keys [width height]}} wallpaper]
  (str width "x" height))
</code>```

Is something like that possible with destructuring?

Thanks.

答:
You must first destructure :resolution, then get width and height:</p>

```<code>{{:keys [width height]} :resolution}
</code>```

Title: Destructure a map in another map?

Body:
I have the following data structure:

{:file #<File /foo.bar>, :resolution {:width 1280, :height 1024}}

I would like to write a function that destructures the :resolution key into width and height symbols.  Something like

(defn to-directory-name [{{:keys [width height]}} wallpaper]
  (str width "x" height))

Is something like that possible with destructuring?

Thanks.

Body:
You must first destructure :resolution, then get width and height:

{{:keys [width height]} :resolution}


问:
Atleast one drop down value must be selected from multiple drop downs using jquery validation plugin
I have multiple drop downs in a table and at least one drop-down from table  should be selected as per the business rule. I am using jquery validation plugin and jsf.
  Thanks in advance!!
// jsf code

```<code>div id="hoursShiftsModal">
   <table id="hoursShiftsTable">
          <col width="5%"/>
          <col width="5%"/>
           <col width="5%"/>
           <col width="5%"/>
        <thead>
        <tr>
              <th>Hours</th>
             <th>Jan</th>
             <th>Feb</th>
     </tr>
    </thead>
    <tbody>
    <tr>
     <td><label>Starting</label></td>
    <td>
    <h:selectOneMenu id="janStartTime" class="required timeZone      workShiftsGroup" >
    <f:selectItem itemValue="Select" itemLabel="Select" ></f:selectItem>
    <f:selectItems value=" "></f:selectItems>
   </h:selectOneMenu>
   </td>
  <td>
   <h:selectOneMenu id="febStartTime" class="required timeZone workShiftsGroup "  >
   <f:selectItem itemValue="Select" itemLabel="Select" ></f:selectItem>
   <f:selectItems ></f:selectItems>
 </h:selectOneMenu>
 </td>
</tbody>
</table>
</code>```

enter image description here

答:
That might work: it will search for 'selected' options nested in your tables.</p>

```<code>function valid() {
    return $('#hoursShiftsTable select option[selected=selected][value!=" "]').size() > 0;
}
</code>```

Body:
I have multiple drop downs in a table and at least one drop-down from table  should be selected as per the business rule. I am using jquery validation plugin and jsf.
  Thanks in advance!!
// jsf code

div id="hoursShiftsModal">

          <col width="5%"/>
          <col width="5%"/>
           <col width="5%"/>
           <col width="5%"/>

              Hours
             Jan
             Feb

     Starting

    <h:selectOneMenu id="janStartTime" class="required timeZone      workShiftsGroup" >
    <f:selectItem itemValue="Select" itemLabel="Select" ></f:selectItem>
    <f:selectItems value=" "></f:selectItems>
   </h:selectOneMenu>

   <h:selectOneMenu id="febStartTime" class="required timeZone workShiftsGroup "  >
   <f:selectItem itemValue="Select" itemLabel="Select" ></f:selectItem>
   <f:selectItems ></f:selectItems>
 </h:selectOneMenu>

enter image description here

Body:
That might work: it will search for 'selected' options nested in your tables.

function valid() {
    return $('#hoursShiftsTable select option[selected=selected][value!=" "]').size() > 0;
}


问:
Fixed Position Div, displaying on top of following div
I have the following fiddle  https://jsfiddle.net/0vau6psp/  This is the minimum code required to replicated the error.  I am assuming it has something to do with position:fixed but I can not figure it out.

The problem is resulting in my header being display directly on top of the main content which is causing the main content to not be seen,  I would like the content to display underneath the header.

Any help would be appreciated! Below Is my code as well for reference:

HTML:

```<code>    <header class="site-header" >
  <div class="header-main" id="header-flow">
    <div class="container-fluid header-cont-top-nav">
      <div class="row">
        <div class="col-md-5 text-right hidden-xs hidden-sm">
            <ul>
            <li>Link</li>
            <li>Link</li>
            <li>Link</li>
            </ul>
        </div>
      </div>
    </div><!--/.container-->
  </div><!--/.header-main-->
</header>
  <main class="site-main-content" id="mainscrollcontent">
      <p>
       {{ content_for_layout }}
       Test
       Test Content
       Test Content line 4
       </p>
  </main>
</code>```

CSS:

```<code>#header-flow {
    border-bottom: #73b2b2 3px solid;
    z-index: 1000;
    background-color: #fff;
    position: fixed;
    width: 100%;
}
#header-flow li{
display:inline-block;
}
.site-main-content {
    margin-bottom: 0;
    display:block;
}
</code>```

答: You can add padding-top or margin-top to your .site-main-content css to bring it down

Body:
I have the following fiddle  https://jsfiddle.net/0vau6psp/  This is the minimum code required to replicated the error.  I am assuming it has something to do with position:fixed but I can not figure it out.

The problem is resulting in my header being display directly on top of the main content which is causing the main content to not be seen,  I would like the content to display underneath the header.

Any help would be appreciated! Below Is my code as well for reference:

HTML:

Link

Link

Link

       {{ content_for_layout }}
       Test
       Test Content
       Test Content line 4

CSS:

#header-flow {
    border-bottom: #73b2b2 3px solid;
    z-index: 1000;
    background-color: #fff;
    position: fixed;
    width: 100%;
}
#header-flow li{
display:inline-block;
}
.site-main-content {
    margin-bottom: 0;
    display:block;
}


问:
Availability of snapcraft on AlpineLinux
I was looking for compatibility between snap package management system and alpine linux but could not find any relevant resources. Is there any plan to make it available on alpine linux? Any progress being made in that regard?</p>

答:
To be clear: there are two components here: snapd, which is responsible for running snaps, and Snapcraft, which is responsible for building/creating snaps. You specifically asked about Snapcraft, which unlike snapd, is currently Ubuntu-specific. This is due to the fact that it assumes build- and stage-packages are debs, and tries to use apt (and apt python bindings) to get them.

This is currently changing to be more extensible, with RPM support to probably be added first. Alpine will likely need apk support there.

Another feature coming soon will be to build in lxd containers by default. This may be the easier path, where Snapcraft can run natively on Alpine but then build packages using an Ubuntu container.

If you're curious about snapd, you can see from this table that Alpine does not currently seem to be a target. However, please do log a bug requesting that it be put on the roadmap.