问:
Pytest AttributeError: 'function' object has no attribute 'test_func'
I'm trying to test python function using pytest but get this error.

```<code>import pytest

class Example:

    def __init__(self):
        pass

    @staticmethod
    def test_func(list_arg):
        return len(list_arg)

@pytest.fixture()
def example_instance():
    return Example()

def test_util_fun():
    empty_val = []

    assert example_instance.test_func(empty_val) == 2
</code>```

error :

```<code>AttributeError: 'function' object has no attribute 'test_func'
</code>```

pytest and python versions

```<code>python 3.7
pytest 4.5.0
</code>```

答:
You need to pass example_instance as an argument to test_util_fun; it doesn't magically appear just because it's a fixture:

```<code>def test_util_fun(example_instance):
    empty_val = []

    assert example_instance.test_func(empty_val) == 2
</code>```

The rules for pytest fixtures are a bit different. If you leave it out, then example_instance will bind to the function object itself.

However, if you specify it as an argument, pytest will automatically instantiate the fixture when required, according to the specified scope, and pass it to the test function.

Body:
I'm trying to test python function using pytest but get this error.

import pytest

class Example:

    def __init__(self):
        pass

    @staticmethod
    def test_func(list_arg):
        return len(list_arg)

@pytest.fixture()
def example_instance():
    return Example()

def test_util_fun():
    empty_val = []

    assert example_instance.test_func(empty_val) == 2

error :

AttributeError: 'function' object has no attribute 'test_func'

pytest and python versions

python 3.7
pytest 4.5.0

Body:
You need to pass example_instance as an argument to test_util_fun; it doesn't magically appear just because it's a fixture:

def test_util_fun(example_instance):
    empty_val = []

    assert example_instance.test_func(empty_val) == 2

The rules for pytest fixtures are a bit different. If you leave it out, then example_instance will bind to the function object itself.

However, if you specify it as an argument, pytest will automatically instantiate the fixture when required, according to the specified scope, and pass it to the test function.


来源: stackexchange

问:
How to automatically average every column in Google Sheets in their own seperate cells?
I have 2 sheets in one file, I want to take the average of the columns in the 2nd sheet sequentially (columns A, B, C, D, E, F, etc.). It would take me a very long time to type out manually because there are a lot of columns. Is there any way to do this automatically and place them in cells top to bottom left to right like my image shows?

What my sheet looks like:

答:
create a new spreadsheet and call it A

delete all rows except the first one

add columns so you end up with a range A1:IZ1

paste this formula into G1 cell: =IFERROR(AVERAGEA(Data!D5:D100))

select G1 cell

press CTRL + SHIFT + RIGHT ARROW

press CTRL + ENTER

go to your Stats sheet and delete all your AVERAGEA formulas eg. row 5, 7, 9, etc.

paste this into Stats!A5 cell:

```<code>=ARRAYFORMULA(ARRAY_CONSTRAIN(SUBSTITUTE(SPLIT(TEXTJOIN("♦", 1,
 REPT(FILTER(A!A1:BR1, NOT(MOD(COLUMN(A!A1:BR1), 7)))&"♦♠", 6)), "♦"), "♠", ), 1, 70))</code>```

paste this into Stats!A7 cell:

```<code>=ARRAYFORMULA(ARRAY_CONSTRAIN(SUBSTITUTE(SPLIT(TEXTJOIN("♦", 1,
 REPT(FILTER(A!B1:BS1, NOT(MOD(COLUMN(A!A1:BR1), 7)))&"♦♠", 6)), "♦"), "♠", ), 1, 70))</code>```

paste this into Stats!A9 cell:

```<code>=ARRAYFORMULA(ARRAY_CONSTRAIN(SUBSTITUTE(SPLIT(TEXTJOIN("♦", 1,
 REPT(FILTER(A!C1:BT1, NOT(MOD(COLUMN(A!A1:BR1), 7)))&"♦♠", 6)), "♦"), "♠", ), 1, 70))</code>```

paste this into Stats!A11 cell:

```<code>=ARRAYFORMULA(ARRAY_CONSTRAIN(SUBSTITUTE(SPLIT(TEXTJOIN("♦", 1,
 REPT(FILTER(A!D1:BU1, NOT(MOD(COLUMN(A!A1:BR1), 7)))&"♦♠", 6)), "♦"), "♠", ), 1, 70))</code>```

paste this into Stats!A13 cell:

```<code>=ARRAYFORMULA(ARRAY_CONSTRAIN(SUBSTITUTE(SPLIT(TEXTJOIN("♦", 1,
 REPT(FILTER(A!E1:BV1, NOT(MOD(COLUMN(A!A1:BR1), 7)))&"♦♠", 6)), "♦"), "♠", ), 1, 70))</code>```

etc. (the only thing whats changing is range after FILTER by 1 later)

a 70 at the end is the number of the last column of a purple set ending at BR column (BR = 70) green set ends on CF so that's the 84th column etc...

7 represents the jump eg. to get every 7th value of A!A1:1

6 represents a fix for offset because you merged 7 columns (A5:G5, H5:N5, etc.)

ContentLicense: CC BY-SA 4.0

Body:
create a new spreadsheet and call it A

delete all rows except the first one

add columns so you end up with a range A1:IZ1

paste this formula into G1 cell: =IFERROR(AVERAGEA(Data!D5:D100))

select G1 cell

press CTRL + SHIFT + RIGHT ARROW

press CTRL + ENTER

go to your Stats sheet and delete all your AVERAGEA formulas eg. row 5, 7, 9, etc.

paste this into Stats!A5 cell:

=ARRAYFORMULA(ARRAY_CONSTRAIN(SUBSTITUTE(SPLIT(TEXTJOIN("♦", 1,
 REPT(FILTER(A!A1:BR1, NOT(MOD(COLUMN(A!A1:BR1), 7)))&"♦♠", 6)), "♦"), "♠", ), 1, 70))

paste this into Stats!A7 cell:

=ARRAYFORMULA(ARRAY_CONSTRAIN(SUBSTITUTE(SPLIT(TEXTJOIN("♦", 1,
 REPT(FILTER(A!B1:BS1, NOT(MOD(COLUMN(A!A1:BR1), 7)))&"♦♠", 6)), "♦"), "♠", ), 1, 70))

paste this into Stats!A9 cell:

=ARRAYFORMULA(ARRAY_CONSTRAIN(SUBSTITUTE(SPLIT(TEXTJOIN("♦", 1,
 REPT(FILTER(A!C1:BT1, NOT(MOD(COLUMN(A!A1:BR1), 7)))&"♦♠", 6)), "♦"), "♠", ), 1, 70))

paste this into Stats!A11 cell:

=ARRAYFORMULA(ARRAY_CONSTRAIN(SUBSTITUTE(SPLIT(TEXTJOIN("♦", 1,
 REPT(FILTER(A!D1:BU1, NOT(MOD(COLUMN(A!A1:BR1), 7)))&"♦♠", 6)), "♦"), "♠", ), 1, 70))

paste this into Stats!A13 cell:

=ARRAYFORMULA(ARRAY_CONSTRAIN(SUBSTITUTE(SPLIT(TEXTJOIN("♦", 1,
 REPT(FILTER(A!E1:BV1, NOT(MOD(COLUMN(A!A1:BR1), 7)))&"♦♠", 6)), "♦"), "♠", ), 1, 70))

etc. (the only thing whats changing is range after FILTER by 1 later)

a 70 at the end is the number of the last column of a purple set ending at BR column (BR = 70) green set ends on CF so that's the 84th column etc...

7 represents the jump eg. to get every 7th value of A!A1:1

6 represents a fix for offset because you merged 7 columns (A5:G5, H5:N5, etc.)


问:
How to send Notification in iOS when using firebase cloud functions?
I have been looking around many different places for how to implement notification sending using cloud functions. And the best I have found is the following: Push notifications using Firebase Cloud Function iOS

But I believe it would benefit many people as well as me, if this fragmentation were fixed with one set of instructions from start to finish.

Thus I ask: How can I implement notification sending when a user creates something at a certain spot in firebase realtime DB?

From start to finish, a very clear explanation for someone doing this for the FIRST TIME.

答: This is in the documentation for Firebase. This is a specific part of the documentation that uses Node.js as an example to send a message. </p>


问:
MDB protocol (multidrop bus) - C# serialport communication
I am in the process of developing a MDB software in C# as a payment reader media that communicates with a vending machine through MDB protocol. Currently everything works OK and i am able to communicate with the vending machine. The communication is like expected after reading the MDB protocol but i am having trouble understanding some commands/respones...

I just have one question regarding a response i should send back to the vending machine that may be really stupid, but i really don't understand how it should be sent.

As shown in the MDB protocol, when i get a POLL from the MDB machine and the state of the reader (my computer) is "Session Idle", i can then send a "Begin Session" command to the vending machine. The commands are sent in bytes over serial port and are shown as HEX or Binary in the MDB protocoll. The BEGIN SESSION command should contain the following:

Z1 Begin Session
Z2-Z3 Funds Available
Z4-Z7 Payment media ID
Z8 Payment Type
Z9-Z10 Payment Data

I understand Z1-Z7 because of good examples in the MDB protocol, but i am having trouble understanding Z8-Z10 (payment type and payment data).. The examples are not self explained in my head..

```
The MDB protocol says the following:
""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Z8 : Type of payment:
00xxxxxxb = normal vend card (refer EVA-DTS Standard, Appendix     A.1.1 Definitions)
x1xxxxxxb = test media
1xxxxxxxb = free vend card
xx000000b -0 VMC default prices
xx000001b -1 User Group                (Z9   = EVA-DTS Element DA701)
             Price list number          (Z10 = EVA-DTS Element LA101)*
xx000010b
           -2 User Group               (Z9   = EVA-DTS Element DA701)
            Discount group index        (Z10 = EVA-DTS Element MA403)
xx000011b
           -3 Discount percentage factor (Z9=00, Z10 = 0 to 100**,
            report as positive value in EVA-DTS Element MA404)
xx000100b
           -4 Surcharge percentage factor (Z9=00, Z10 = 0 to 100**,
            report as negative value in EVA-DTS Element MA404)

* User Group is a segmentation of all authorized users.
It allows selective cost allocation.
A User Group usually has no direct relation to a price list.
Price Lists are tables of prices.
Each Price List contains an individual price for each product.
Discount Group indicates the Price List on which the Percentage Factor will be applied.
If the User Group, the Price List or Discount Group is unknown by the VMC,
the normal prices are used (Z8 is defaulted to 00h).
Minimum value for Z9 and Z10 is 0.

** Percentages are expressed in binary (00 to 64h)

Note:  These functions may NOT be supported by all VMCs.

Z9-Z10 : Payment data as defined above
""""""""""""""""""""""""""""""""""""""""""""""""""""""""
```

Can somebody please tell me how Z8 and Z9-Z10 should be sent to the vending machine. Now i have been sending (in hex): "0x02 (Z8), 0x10 (Z9) and 0x10 (Z10)" which is just a wild guess and it is working. Don't really know why but its probably not correct.

How should Z8 and Z9-Z10 be sent?

答:
The EVA-DTS standard is its own separate standard.

MDB-ICP is a communication protocol.

EVA-DTS is a data format standard.

MDB optionally (keyword optionally) uses/integrates EVA-DTS data, which is what its asking for here.

EVA-DTS data is human readable values in ascii text/numbers separated by asterixes in a defined order and length.  Each unit of data between an asterisk, is called a data element.

Z9 in options 1&2, refers to data element DA701, where if you look in Appendix A of the EVA-DTS-6.2.2 standard, the DA701 has the element name "Cashless1 user group number", which is of data type N0 meaning a number without any implied decimal  points, a minimum length of 1 digit and a maximum of 13.  In MDB, isn't sent as an ASCII string of characters like "15", instead, you use hexadeximal numerical representations, so usergroup 15 would be 0x0F.  The usergroup if not using it,you can just put 0x01 for everyone.  Its used to group people, with different price tables, giving different prices to different people.  Not sure if thats a MDB feature, but any VMC could implement it if not.  All optional.

Z9 you can look up yourself

Z8, First two Most Significant bits are used to indicate if it was a vend card paying (as in credit card, or any real form of cashless payment).  the rest of the digits it depends on the vend.  you use one of the 4 options (read appendix A section 1.1 of the DTS standard to get definitions of what they mean and which ones are appropriate in that situations.  Depending on the option used (1, 2, 3, or 4) that decides what Z9 & Z10 are, like option 3 says z9 would be 0x00 and Z10 would become a percentage (since z8 would describe a percentage discount given), while if u pick option one, Z10 instead contains the value of DTS element LA101.

Hope that's not too wordy or incoherent.  good luck too, we're competitors.

ContentLicense: CC BY-SA 3.0

Body:
I am in the process of developing a MDB software in C# as a payment reader media that communicates with a vending machine through MDB protocol. Currently everything works OK and i am able to communicate with the vending machine. The communication is like expected after reading the MDB protocol but i am having trouble understanding some commands/respones...

I just have one question regarding a response i should send back to the vending machine that may be really stupid, but i really don't understand how it should be sent.

As shown in the MDB protocol, when i get a POLL from the MDB machine and the state of the reader (my computer) is "Session Idle", i can then send a "Begin Session" command to the vending machine. The commands are sent in bytes over serial port and are shown as HEX or Binary in the MDB protocoll. The BEGIN SESSION command should contain the following:

Z1 Begin Session
Z2-Z3 Funds Available
Z4-Z7 Payment media ID
Z8 Payment Type
Z9-Z10 Payment Data

I understand Z1-Z7 because of good examples in the MDB protocol, but i am having trouble understanding Z8-Z10 (payment type and payment data).. The examples are not self explained in my head..

The MDB protocol says the following:
""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Z8 : Type of payment:
00xxxxxxb = normal vend card (refer EVA-DTS Standard, Appendix     A.1.1 Definitions)
x1xxxxxxb = test media
1xxxxxxxb = free vend card
xx000000b -0 VMC default prices
xx000001b -1 User Group                (Z9   = EVA-DTS Element DA701)
             Price list number          (Z10 = EVA-DTS Element LA101)*
xx000010b
           -2 User Group               (Z9   = EVA-DTS Element DA701)
            Discount group index        (Z10 = EVA-DTS Element MA403)
xx000011b
           -3 Discount percentage factor (Z9=00, Z10 = 0 to 100**,
            report as positive value in EVA-DTS Element MA404)
xx000100b
           -4 Surcharge percentage factor (Z9=00, Z10 = 0 to 100**,
            report as negative value in EVA-DTS Element MA404)

* User Group is a segmentation of all authorized users.
It allows selective cost allocation.
A User Group usually has no direct relation to a price list.
Price Lists are tables of prices.
Each Price List contains an individual price for each product.
Discount Group indicates the Price List on which the Percentage Factor will be applied.
If the User Group, the Price List or Discount Group is unknown by the VMC,
the normal prices are used (Z8 is defaulted to 00h).
Minimum value for Z9 and Z10 is 0.

** Percentages are expressed in binary (00 to 64h)

Note:  These functions may NOT be supported by all VMCs.

Z9-Z10 : Payment data as defined above
""""""""""""""""""""""""""""""""""""""""""""""""""""""""

Can somebody please tell me how Z8 and Z9-Z10 should be sent to the vending machine. Now i have been sending (in hex): "0x02 (Z8), 0x10 (Z9) and 0x10 (Z10)" which is just a wild guess and it is working. Don't really know why but its probably not correct.

How should Z8 and Z9-Z10 be sent?


问:
Is it possible to start counting from a specific div in Python using XPATH and Selenium?
I have 80 divs, each div (in our case, class 24, 27, 30) contains 2 children.

Is it possible to start counting from let's say, the 24rd row (EXCLUDING CHILDREN), then keep counting the rows under it? (using XPATH only, not CSS selectors ;) )

```<code><div class="container">
    ... # dots signify the divs before it
    <div class="24">
        <div class="25"></div>
        <div class="26"></div>
    </div>
    <div class="27">
        <div class="28"></div>
        <div class="29"></div>
    </div>
    <div class="30">
        <div class="31"></div>
        <div class="32"></div>
    </div>
    ... # divs after it
</div>
</code>```

Is there something like:

Let's say:

x = 0
all_the_divs = driver.find_elements_by_xpath("//div/*")
while x < len(all_the_divs):
    # do something
    pass
    if x == 24:
        # catch all the divs under 24 (excluding 24)
        # something like:
        divs_under_x = len(driver.find_elements_by_xpath("//div/div[" + str(x) + "]::"))
       # or
       divs_under_x = len(driver.find_elements_by_xpath("//div/following-sibling::div[" + str(x) + "]*"))
        break
    x += 1
```

OUTPUT: The length should be 2 (class 27 and 30 without their children)
Many thanks.

答:
Here goes:

```<code>from lxml import etree

data = [your data above]

tree = lxml.etree.fromstring(data, parser=lxml.etree.HTMLParser())
targets = tree.xpath("*//div[(position()=2 or position()=3) and descendant::div]")
for i in targets:
    for child in i.getchildren():
        child.getparent().remove(child)
    print(etree.tostring(i).decode().replace('\n','').strip())
</code>```

Output:

```<code><div class="27">        </div>
<div class="30">         </div>
</code>```

Hopefully this is at least in the general direction of what you're looking for...

Body:
I have 80 divs, each div (in our case, class 24, 27, 30) contains 2 children.

Is it possible to start counting from let's say, the 24rd row (EXCLUDING CHILDREN), then keep counting the rows under it? (using XPATH only, not CSS selectors ;) )

    ... # dots signify the divs before it

    ... # divs after it

Is there something like:

Let's say:

x = 0
all_the_divs = driver.find_elements_by_xpath("//div/*")
while x < len(all_the_divs):
    # do something
    pass
    if x == 24:
        # catch all the divs under 24 (excluding 24)
        # something like:
        divs_under_x = len(driver.find_elements_by_xpath("//div/div[" + str(x) + "]::"))
       # or
       divs_under_x = len(driver.find_elements_by_xpath("//div/following-sibling::div[" + str(x) + "]*"))
        break
    x += 1

OUTPUT: The length should be 2 (class 27 and 30 without their children)
Many thanks.

Body:
Here goes:

from lxml import etree

data = [your data above]

tree = lxml.etree.fromstring(data, parser=lxml.etree.HTMLParser())
targets = tree.xpath("*//div[(position()=2 or position()=3) and descendant::div]")
for i in targets:
    for child in i.getchildren():
        child.getparent().remove(child)
    print(etree.tostring(i).decode().replace('\n','').strip())

Output:

<div class="27">        </div>
<div class="30">         </div>

Hopefully this is at least in the general direction of what you're looking for...


问:
How to find the car speed on iPhone?
I want to find the car speed on my iPhone when driving so what should I use and how?
Core Motion or Core Location? Is there any documentation or sample code?</p>

答:
CoreMotion would not help you much, because it is an abstraction of the device's accelerometer and the gyroscope. You could measure acceleration and deceleration and computing the speed from basic physics, but I would not do so.

I would use the CoreLocation frameworkd and rely on GPS positioning. There is a ton of sample code out there and a WWDC10 video as well, so go ahead and look it up.

Title: How to find the car speed on iPhone?


问:
How do you build the directory structure of a self-contained java program from scratch?
I'm programming my first 2D game in java. I'm writing the code in Atom. I compile and run the code from the terminal on my Mac. The game works great so far! But I fear I am structuring my project incorrectly and will not be able to deploy it when it comes time. I want to know the proper way to build a directory structure for a project like a 2D java-based game, ideally, doing it from scratch.

I put the game making on hold to figure out structuring.
I tried using LibGDX as a means of packaging my project, and then importing it as a Gradle project into Eclipse. I suddenly found myself with a huge and unclear directory structure surrounding my once-simple project. I felt the task was no simpler than structuring the project myself from scratch. In addition, I could not get any simple java code to run from within this auto-generated directory structure provided by LibGDX, now inside Eclipse. I would prefer to write all code in Atom, and compile and test the code from the terminal, creating appropriate JARs when necessary, again from the terminal.

I decided to simplify the task at hand and return to the Oracle docs, and I determined that what I'm trying to build is a self-contained java application. Sweet! But the Oracle docs don't seem to go too into depth on the logic behind the necessary directory structure needed for such a project. They tell you the two main components you need are the resources for your application (so the .java files, images and audio, etc.) and a copy of the JRE so that the user has everything they need to play the game when they execute the program. I just don't feel confident with how to set up this directory structure with the information provided.

I would like to overcome this "how should this all be structured?" problem so I can return to developing the game. Thanks in advance for reading and providing feedback.

答:
The industry standard for structuring Java projects is to use a tool like Maven or Gradle. Both of these tools automatically handle wrangling all of your source code, resource files, etc. and have systems to make it easy to export jar files (from an IDE or command line). In essence, they allow you to specify anything that you want for how your Java project is built (Gradle can also do C++ projects), and then they provide an abstracted command line interface to build the project.

It is important to note that your preference of working with Java without an IDE is not shared by many developers. While this isn't in and of itself a problem, it becomes one when you want to work with others who will be using an IDE. Gradle and Maven both make this easy as almost all IDEs will work well with Gradle and Maven projects. For this reason, most FOSS Java projects use one of these systems (usually Gradle) to allow different developers to use their preferred IDE.

You also expressed a desire to fully understand the set of files that make up your project. For this, Gradle is probably your best bet as its tutorials do a very good job of explaining this. It is more complex than a plain Java project, but it is worth it to most developers as you get very easy and expressive tools (eg. 3 lines of Gradle configuration can create a jar export) along with the ability to use many development stacks (eg. an IDE, command line, and continuous integration) at the cost of a minor learning curve. Gradle is also the current most popular non-IDE-dependent Java build tool. Maven acts a bit more like a black box, but still has many of the advantages of Gradle. If you want to learn Gradle, their getting started guides are a great place to start.


问:
Database Connection Pooling in Java Servlets
I'm creating a web application for Employee Management System, using: Apache Tomcat as HTTP Server, Oracle as the database, Applets for the client side programming and Servlets for server side programming. I also want to use DBCP to manage connections to the database.

I would like the servlet performing queries to use the username and password entered by the client for the connection. But so far I've seen that the username and password for the connection pool must be set when configuring the resource in context.xml.

Is there any way to achieve this and still use DBCP? Or will I have to open connections in doGet() and doPost() for every request?

答:
DataSource::getConnection(String username, String password)

The DataSource interface has a method expressly for your purpose: Varying the name and password for each connection while using the all the other previously set options for connecting: DataSource::getConnection(String username, String password)

The java.sql.ConnectionPoolDataSource interface carries the same kind of method, getPooledConnection(String user, String password). So your particular connection pooling implementation may support this.

```<code>public javax.sql.DataSource obtainDataSource() {
    org.postgresql.ds.PGSimpleDataSource dataSource = new PGSimpleDataSource() ;
    dataSource("AcmeInvoices database data source") ;
    source.setServerName( "localhost" ) ;
    source.setDatabaseName( "invoicing" ) ;
    // source.setUser( "Scott" ) ;
    // source.setPassword( "tiger" ) ;
    return dataSource ;  // Returning a reference to the object of this concrete class `PGSimpleDataSource` as an object of the interface `DataSource`.
}
</code>```

When doing some database work:

```<code>Connection conn = myDataSource.getConnection( "Scott" , "tiger" ) ;
… run SQL
conn.close() ;  // Or better yet: Use try-with-resources syntax to automatically close the connection.
</code>```

For more discussion, see an Answer of mine on a related Question.

See Oracle Tutorial on DataSource.

Body:
DataSource::getConnection(String username, String password)

The DataSource interface has a method expressly for your purpose: Varying the name and password for each connection while using the all the other previously set options for connecting: DataSource::getConnection(String username, String password)

The java.sql.ConnectionPoolDataSource interface carries the same kind of method, getPooledConnection(String user, String password). So your particular connection pooling implementation may support this.

public javax.sql.DataSource obtainDataSource() {
    org.postgresql.ds.PGSimpleDataSource dataSource = new PGSimpleDataSource() ;
    dataSource("AcmeInvoices database data source") ;
    source.setServerName( "localhost" ) ;
    source.setDatabaseName( "invoicing" ) ;
    // source.setUser( "Scott" ) ;
    // source.setPassword( "tiger" ) ;
    return dataSource ;  // Returning a reference to the object of this concrete class `PGSimpleDataSource` as an object of the interface `DataSource`.
}

When doing some database work:

Connection conn = myDataSource.getConnection( "Scott" , "tiger" ) ;
… run SQL
conn.close() ;  // Or better yet: Use try-with-resources syntax to automatically close the connection.

For more discussion, see an Answer of mine on a related Question.

See Oracle Tutorial on DataSource.


问:
How to find a group using musonza/groups package
Im trying to use musonza/groups so i can build a group system on my app
any idea how can i find a group so I can use request function that we have in the package?
I tryed this but it's not working code:

```<code>use Groups;
use Auth;
public function makerequest($id){

        $userId=Auth::User()->id;

        $group->request($userId);

        return redirect()->back()->withMessage('request done!');

    }
</code>```

I get Undefined variable: group error because I don't know what is the function to find my group using the facade
nb: I get $id from the form

答:
To find the group use
group($groupId)</p>

Body:
Im trying to use musonza/groups so i can build a group system on my app
any idea how can i find a group so I can use request function that we have in the package?
I tryed this but it's not working code:

use Groups;
use Auth;
public function makerequest($id){

        $userId=Auth::User()->id;

        $group->request($userId);

        return redirect()->back()->withMessage('request done!');

    }

I get Undefined variable: group error because I don't know what is the function to find my group using the facade
nb: I get $id from the form

Body:
To find the group use
group($groupId)


问:
Tensorflow.js consecutive predictions much slower than single prediction
I have an application in which I want to continuously make and process predictions. I have a function that makes a prediction and does something with the result:

```<code>makeProcessPrediction(){
    return new Promise(resolve => {
      let prediction : any = this.model.predict(this.input_tensor);
      prediction.data().then((data_array) => {
              //... do something with prediction here
          }
      prediction.dispose();
      resolve('resolved');
      });
    });
}
</code>```

Now if I make a single call to makeProcessPrediction, the prediction takes about 80 ms. But if I call it in a loop like this:

```<code>while(condition){
    await this.makeProcessPrediction();
}
</code>```

Suddenly, the predictions take a lot longer, up to 140 ms. If I stop the loop and make another 'single' prediction, takes again around 80 ms.

I was hoping someone can explain me why this happens and perhaps what I can do to speed up the predictions.

Thanks a lot!

答:
Try moving the GPU load.  Actively calling the prediction data into JavaScript using data() allows you to pile up some promises, and likely clog your GPU pipe.

Moving to the synchronous method dataSync() will properly process the GPU memory in the main thread.  While this will block your UI interaction, the speed should just as quick.

Body:
I have an application in which I want to continuously make and process predictions. I have a function that makes a prediction and does something with the result:

makeProcessPrediction(){
    return new Promise(resolve => {
      let prediction : any = this.model.predict(this.input_tensor);
      prediction.data().then((data_array) => {
              //... do something with prediction here
          }
      prediction.dispose();
      resolve('resolved');
      });
    });
}

Now if I make a single call to makeProcessPrediction, the prediction takes about 80 ms. But if I call it in a loop like this:

while(condition){
    await this.makeProcessPrediction();
}

Suddenly, the predictions take a lot longer, up to 140 ms. If I stop the loop and make another 'single' prediction, takes again around 80 ms.

I was hoping someone can explain me why this happens and perhaps what I can do to speed up the predictions.

Thanks a lot!


问:
How do I manipulate strings to store parts of them as variables?
I have a txt file that contains a bunch of information that my program needs to read from eg.

Port: 1337

IP: "IP"

Directory: " "

I need to be able to store everything past the ": " from each line and save the part of the string as a variable eg. int port = 1337, something like that???

What functions should I use and how do I format this in order for it to work with as little code as possible.

答: Take a look at fscanf(). So long as the input is always properly formatted, it'll fill in the variables for you.


问:
Is it possible to run multiple animations with an overall rate_func?
The following is my current code:

from manimlib.imports import *

class ClockOrganization(VGroup):
  CONFIG = {
    "numbers" : 4,
    "radius" : 3.1,
    "color" : WHITE
  }

  def __init__(self, **kwargs):
    digest_config(self, kwargs, locals())
    self.generate_nodes()
    VGroup.__init__(self, *self.node_list,**kwargs)

  def generate_nodes(self):
    self.node_list = []
    for i in range(self.numbers):
      mobject = VMobject()
      number = TexMobject(str(i+1))
      circle = Circle(radius=0.4,color=self.color)
      mobject.add(number)
      mobject.add(circle)
      mobject.move_to(
        self.radius * np.cos((-TAU / self.numbers) * i + 17*TAU / 84) * RIGHT
        + self.radius * np.sin((-TAU / self.numbers) * i + 17*TAU / 84) * UP
      )
      self.node_list.append(mobject)

  def select_node(self, node):
    selected_node = self.node_list[node]
    selected_node.scale(1.2)
    selected_node.set_color(RED)

  def deselect_node(self, selected_node):
    node = self.node_list[selected_node]
    node.scale(0.8)
    node.set_color(self.color)

class Testing3(Scene):
  def construct(self):
    test = ClockOrganization(numbers=21)
    self.play(Write(test), run_time=1.5)
    animation_steps=[]
    for i in range(10):
      thing = test.deepcopy()
      thing.select_node((19+i)%test.numbers-1)
      animation_steps.append(thing)
    self.play(Transform(test, animation_steps[0]))
    self.wait(2)
    for i in range(1,10):
      self.play(Transform(test, animation_steps[i]),run_time=0.3)
    self.wait()
```

<p>If you run it currently, it highlights 19, then revolves to 7 at a uniform pace. Is it possible to set a <code>rate_func</code> for this overall process, so it starts revolving slowly, speeds up halfway, then slows its way to 7, like the smooth <code>rate_func</code> but applied over the entire thing?</p>

<p>I have tried changing the above Scene class to</p>

<pre class="lang-py prettyprint-override"><code>class Testing3(Scene):
  def construct(self):
    test = ClockOrganization(numbers=21)
    self.play(Write(test), run_time=1.5)
    animation_steps=[]
    for i in range(10):
      thing = test.deepcopy()
      thing.select_node((19+i)%test.numbers-1)
      animation_steps.append(thing)
    self.play(Transform(test, animation_steps[0]))
    self.wait(2)
    for i in range(1,10):
      if i in range(1,6):
        time_to_run=(sigmoid(10*(-i/4+.75))-sigmoid(-5))/(1-2*sigmoid(-5)+3)+.1
      if i in range(6,10):
        time_to_run=(sigmoid(10*(i/4-1.75))-sigmoid(-5))/(1-2*sigmoid(-5)+3)+.1
      self.play(Transform(test, animation_steps[i]),run_time=time_to_run)
    self.wait()
</code>```

and it comes close to what I'm going for, but the Transforms seem rather choppy.

答:
Or this, start slow, then increase and then slow again</p>

```<code>class Testing4(Scene):
  def construct(self):
    test = ClockOrganization(numbers=21)
    self.play(Write(test), run_time=1.5)
    animation_steps=[]
    #animation_steps.append(test)
    num_circ=15
    for i in range(num_circ):
      thing = test.deepcopy()
      thing.select_node((19+i)%test.numbers-1)
      animation_steps.append(thing)
    test_normal=test.copy()
    test.save_state()
    self.play(Transform(test, animation_steps[0]))
    self.wait(2)
    self.play(Restore(test))
    anims=[]
    theta=180*DEGREES/num_circ
    lag_constant=5
    for i in range(1,num_circ):
        test.node_list[(19+i)%test.numbers-1].generate_target()
        test.node_list[(19+i)%test.numbers-1].target.scale(1.2)
        test.node_list[(19+i)%test.numbers-1].target.set_color(RED)
        stop_smooth=lag_constant*np.sin(i*theta)
        anims.append(MoveToTarget(test.node_list[(19+i)%test.numbers-1],rate_func=there_and_back))
        anims.append(Animation(Mobject(),run_time=stop_smooth))
    self.play(
        AnimationGroup(*anims,lag_ratio=0.1)
        )
    self.wait()
</code>```

Body:
The following is my current code:

from manimlib.imports import *

class ClockOrganization(VGroup):
  CONFIG = {
    "numbers" : 4,
    "radius" : 3.1,
    "color" : WHITE
  }

  def __init__(self, **kwargs):
    digest_config(self, kwargs, locals())
    self.generate_nodes()
    VGroup.__init__(self, *self.node_list,**kwargs)

  def generate_nodes(self):
    self.node_list = []
    for i in range(self.numbers):
      mobject = VMobject()
      number = TexMobject(str(i+1))
      circle = Circle(radius=0.4,color=self.color)
      mobject.add(number)
      mobject.add(circle)
      mobject.move_to(
        self.radius * np.cos((-TAU / self.numbers) * i + 17*TAU / 84) * RIGHT
        + self.radius * np.sin((-TAU / self.numbers) * i + 17*TAU / 84) * UP
      )
      self.node_list.append(mobject)

  def select_node(self, node):
    selected_node = self.node_list[node]
    selected_node.scale(1.2)
    selected_node.set_color(RED)

  def deselect_node(self, selected_node):
    node = self.node_list[selected_node]
    node.scale(0.8)
    node.set_color(self.color)

class Testing3(Scene):
  def construct(self):
    test = ClockOrganization(numbers=21)
    self.play(Write(test), run_time=1.5)
    animation_steps=[]
    for i in range(10):
      thing = test.deepcopy()
      thing.select_node((19+i)%test.numbers-1)
      animation_steps.append(thing)
    self.play(Transform(test, animation_steps[0]))
    self.wait(2)
    for i in range(1,10):
      self.play(Transform(test, animation_steps[i]),run_time=0.3)
    self.wait()

If you run it currently, it highlights 19, then revolves to 7 at a uniform pace. Is it possible to set a rate_func for this overall process, so it starts revolving slowly, speeds up halfway, then slows its way to 7, like the smooth rate_func but applied over the entire thing?

I have tried changing the above Scene class to

class Testing3(Scene):
  def construct(self):
    test = ClockOrganization(numbers=21)
    self.play(Write(test), run_time=1.5)
    animation_steps=[]
    for i in range(10):
      thing = test.deepcopy()
      thing.select_node((19+i)%test.numbers-1)
      animation_steps.append(thing)
    self.play(Transform(test, animation_steps[0]))
    self.wait(2)
    for i in range(1,10):
      if i in range(1,6):
        time_to_run=(sigmoid(10*(-i/4+.75))-sigmoid(-5))/(1-2*sigmoid(-5)+3)+.1
      if i in range(6,10):
        time_to_run=(sigmoid(10*(i/4-1.75))-sigmoid(-5))/(1-2*sigmoid(-5)+3)+.1
      self.play(Transform(test, animation_steps[i]),run_time=time_to_run)
    self.wait()

and it comes close to what I'm going for, but the Transforms seem rather choppy.

Body:
Or this, start slow, then increase and then slow again

class Testing4(Scene):
  def construct(self):
    test = ClockOrganization(numbers=21)
    self.play(Write(test), run_time=1.5)
    animation_steps=[]
    #animation_steps.append(test)
    num_circ=15
    for i in range(num_circ):
      thing = test.deepcopy()
      thing.select_node((19+i)%test.numbers-1)
      animation_steps.append(thing)
    test_normal=test.copy()
    test.save_state()
    self.play(Transform(test, animation_steps[0]))
    self.wait(2)
    self.play(Restore(test))
    anims=[]
    theta=180*DEGREES/num_circ
    lag_constant=5
    for i in range(1,num_circ):
        test.node_list[(19+i)%test.numbers-1].generate_target()
        test.node_list[(19+i)%test.numbers-1].target.scale(1.2)
        test.node_list[(19+i)%test.numbers-1].target.set_color(RED)
        stop_smooth=lag_constant*np.sin(i*theta)
        anims.append(MoveToTarget(test.node_list[(19+i)%test.numbers-1],rate_func=there_and_back))
        anims.append(Animation(Mobject(),run_time=stop_smooth))
    self.play(
        AnimationGroup(*anims,lag_ratio=0.1)
        )
    self.wait()


问:
trying to building on OSX but got "No rule to make target antlr4_static" error
trying to build on OSX, got the following antlr error. Need to install antlr-runtime?</p>

```<code>[ 43%] Built target antlr4_runtime
[ 43%] Built target csv_infer
[ 45%] Performing build_static step for 'antlr4_runtime'
make[4]: *** No rule to make target `antlr4_static'.  Stop.
make[3]: *** [antlr4_runtime/src/antlr4_runtime-stamp/antlr4_runtime-build_static] Error 2
make[2]: *** [CMakeFiles/antlr4_runtime-build_static.dir/all] Error 2
make[1]: *** [all] Error 2
make: *** [dev] Error 2
</code>```

答:
This has now been fixed.

CMake 3.14 changed where the ExternalProject module builds the source. It was unable to find ANTLR's own CMake files, necessitating a change to the WORKING_DIRECTORY.

Body:
trying to build on OSX, got the following antlr error. Need to install antlr-runtime?

[ 43%] Built target antlr4_runtime
[ 43%] Built target csv_infer
[ 45%] Performing build_static step for 'antlr4_runtime'
make[4]: *** No rule to make target `antlr4_static'.  Stop.
make[3]: *** [antlr4_runtime/src/antlr4_runtime-stamp/antlr4_runtime-build_static] Error 2
make[2]: *** [CMakeFiles/antlr4_runtime-build_static.dir/all] Error 2
make[1]: *** [all] Error 2
make: *** [dev] Error 2


问:
How to replace file content which has special character, with dynamic value in JMeter
Can I replace a file content with dynamic content even if the file has special characters.

This is what I get when I try to do that.

and this is how my file looks like

```<code>[{"someName": "M`o\c\k","someNumber": "${randomNumber}"}]
</code>```

and I have a variable configured for ${randomNumber}.

答:
I was able to solve my scenario by adding a json library to my JMeter, JSON.Simple. I added the jar to my jmeter classpath. Then I was able to a BeanShell PreProcessor.

The Json simple object will not escape the special characters and its much easier to manipulate. So that was great for my use case.

Body:
Can I replace a file content with dynamic content even if the file has special characters.

This is what I get when I try to do that.

and this is how my file looks like

[{"someName": "M`o\c\k","someNumber": "${randomNumber}"}]

and I have a variable configured for ${randomNumber}.


问:
Hostgator update PHP version to 7.1?
Hostgator customer support is absolutely useless. I have been trying for 3 days to update my PHP version so I can install Laravel 5.6. I tried the PHP Selector plugin in cPanel which appears to be the only means of updating the PHP version.

Even after updating every directory to 7.1 in the PHP Selector plugin it still is not working. I called tech support 3 days ago and talked to 3 different representatives and each in a roundabout way told me there was nothing they could do about it and awkwardly apologized.

Then I requested they reset my server and they said I had to wait for email confirmation which took 2 days to arrive. Reset my server to default settings and default files. Tried the PHP Selector again with no luck. Called customer support, the lady told me she updated it herself and to wait to see it on my end. "It should happen any minute." No change.

I'm checking my PHP version with my SSH and the php -v command. It always says I have PHP 5.4 and when trying to use composer create-project --prefer-dist laravel/laravel=5.6 it returns an error that my PHP version is 5.4 and incompatible.

I'm not ranting, I just want to explain the full extent of everything I've tried and how customer support isn't much of an option at this point.

Does anyone have any personal experience updating PHP on Hostgator? I have a shared account. Thanks.

答: I found this post with the same problem and it was because I didn't click the 'public_html' folder in the PHP selector then I updated it to 7.1. Jasper from live chat support via HostGator was able to help and solve my problem. It seemed obvious after he told me but I totally spaced on it and was stuck so if anyone else is reading this like I did - maybe this will help you too haha </p>

Title: Hostgator update PHP version to 7.1?


问:
Custom binary tree object in Python
I'm trying to write a custom binary tree class. I already have the node:

```<code>class Node:

def __init__(self, value, **kwargs):
    self.value = value
    self.kwargs = kwargs

    for key, value in kwargs.items():
        setattr(self, key, value)

def __str__(self):
    main_str = '{value: ' + str(self.value)
    for key, value in self.kwargs.items():
        main_str += ', ' + str(key) + ': ' + str(value)
    main_str += '}'

    return main_str
</code>```

The node uses kwargs because i'm using it also for other things. The problem i'm having is in the tree class:

```<code>from models.node import Node
class BinarySearchTree:

    def __init__(self):
        self.root = None

    def add_element(self, value):
        node = Node(value, left=None, right=None)

        if not self.root:
            self.root = node

        else:
            self.__add_element_recursive(self.root, value)

    def __add_element_recursive(self, parent, value):

        if not parent:
            node = Node(value, left=None, right=None)
            parent = node

        elif value > parent.value:
            self.__add_element_recursive(parent.right, value)

        else:
            self.__add_element_recursive(parent.left, value)
</code>```

This clearly doesn't work because the parameters in python don't get passed as references but as new instances. For example, I know this would work in C++ because I can just pass pointers to the methods.

How do I create the method to add a value to the tree? I think I might be missing something really obvious here.

答:
You need to attach the created node to a branch of the tree.

try this:

```<code>def __add_element_recursive(self, parent, value):
    if value > parent.value:
        if parent.right: # there's a right node: lets go there
            self.__add_element_recursive(parent.right, value)
        else: # No node: we have found our spot
            parent.right = Node(value, left=None, right=None)
    elif parent.left: # There's a left node...lets go there
        self.__add_element_recursive(parent.left, value)
    else: # No node: we have found our spot
        parent.left = Node(value, left=None, right=None)
</code>```

Title: Custom binary tree object in Python

Body:
I'm trying to write a custom binary tree class. I already have the node:

class Node:

def __init__(self, value, **kwargs):
    self.value = value
    self.kwargs = kwargs

    for key, value in kwargs.items():
        setattr(self, key, value)

def __str__(self):
    main_str = '{value: ' + str(self.value)
    for key, value in self.kwargs.items():
        main_str += ', ' + str(key) + ': ' + str(value)
    main_str += '}'

    return main_str

The node uses kwargs because i'm using it also for other things. The problem i'm having is in the tree class:

from models.node import Node
class BinarySearchTree:

    def __init__(self):
        self.root = None

    def add_element(self, value):
        node = Node(value, left=None, right=None)

        if not self.root:
            self.root = node

        else:
            self.__add_element_recursive(self.root, value)

    def __add_element_recursive(self, parent, value):

        if not parent:
            node = Node(value, left=None, right=None)
            parent = node

        elif value > parent.value:
            self.__add_element_recursive(parent.right, value)

        else:
            self.__add_element_recursive(parent.left, value)

This clearly doesn't work because the parameters in python don't get passed as references but as new instances. For example, I know this would work in C++ because I can just pass pointers to the methods.

How do I create the method to add a value to the tree? I think I might be missing something really obvious here.

Body:
You need to attach the created node to a branch of the tree.

try this:

def __add_element_recursive(self, parent, value):
    if value > parent.value:
        if parent.right: # there's a right node: lets go there
            self.__add_element_recursive(parent.right, value)
        else: # No node: we have found our spot
            parent.right = Node(value, left=None, right=None)
    elif parent.left: # There's a left node...lets go there
        self.__add_element_recursive(parent.left, value)
    else: # No node: we have found our spot
        parent.left = Node(value, left=None, right=None)


问:
How to get the myshopify_domain from a ShopifyApp::Authenticated controller without an API call
I am trying to reduce unnecessary calls to the Shopify API from a controller that inherits from ShopifyApp::AuthenticatedController, for example to get the myshopify_domain:

myshopify_domain = ShopifyAPI::Shop.current.myshopify_domain

Is there some method in ShopifyApp::SessionRepository or somewhere else in the ShopifyApp that I can call to retrieve Shop.current.myshopify_domain without making an actual call to the Shopify API webservice?  If not, can I store the myshopify_domain, once retrieved, in the ShopifyApp::SessionRepository?

答:
Your question is confusing. At the point where you are doing calls to the API, you clearly already know the myshopify_domain, as you cannot do API calls with that the shops name and token.

So now we're past that point, and you are asking how you can somehow have the myshopify_domain be more convenient for you to use? Just make yourself a little helper so that when you open a session, you have access to shop_name or whatever you want.

Shopify always sends you shop name in their requests, so you're covered there as it's a param, and your own interface code and calls will also be setting up the shop name too, so you're really now into some pretty esoteric territory to need anything else.

Seem like you're caught in a classic "the dog chasing its own tail", but why?


问:
Is HTTPServerUtility.Transfer is more userful  than Response.Redirect in performance of website in asp.net?
Right now I am reading about .net website performance and scalability.

I read many blog posts and microsoft book about performance and scalability.

In last blog, linked here.

In this blog poing no.6 talking about
 "Use HTTPServerUtility.Transfer instead of Response.Redirect"..

Is it more useful in performance of website and to the point as in the blog that,

"They should only be used when you are transferring people to another physical web server.  For any transfers within your server, use .transfer!  You will save a lot of needless HTTP requests."

Anyone help me how it is more useful in performance than response.redirect?

答:
Server.Transfer is NOT more useful in performance. The better performance is depent from what actuall run in the page and where you call the transfer or the redirect, but the diferent are so small that you need to focus what actuall transfer vs redirect do.

Transfer adds a lot of problems that
add to your navigation from page to
page, eg user see the same page name, but the content is diferent.

Transfer also can not handle
post back asp.net functions.

When you use the transfer you always need to know on each post back what page you show next because you always load the same code page.

If you use a lot the Transfer, then server for every page need to load and run 2 different page code for the same result.

Redirect from the other hand is a method to navigate and show results to the processing of user input. Its clean, code on the second page work with out problems, postback and all that work the same.

I suggest to anyone to rare use the Server.Transfer.

Here is an example that Transfer make thinks complicate and slower. If you have a work to do, and then show result, and lets say that this work makes some seconds, if you make Transfer, on every post back, or reload the work must be run again !.

```<code>protected void Page_Load(object sender, EventArgs e)
{
    // function works
    Thread.Sleep(10000);
    Server.Transfer("Page2.aspx");
}
</code>```

Second Case with redirect, the work will be done one time and not called again, user moves to the result page.

```<code>protected void Page_Load(object sender, EventArgs e)
{
    // function works
    Thread.Sleep(10000);
    Response.Redirect("Page2.aspx");
}
</code>```

I think, that there is no need for too many talks, if you practice them a little you can see many thinks and different in real pages.

Body:
Server.Transfer is NOT more useful in performance. The better performance is depent from what actuall run in the page and where you call the transfer or the redirect, but the diferent are so small that you need to focus what actuall transfer vs redirect do.

Transfer adds a lot of problems that
add to your navigation from page to
page, eg user see the same page name, but the content is diferent.

Transfer also can not handle
post back asp.net functions.

When you use the transfer you always need to know on each post back what page you show next because you always load the same code page.

If you use a lot the Transfer, then server for every page need to load and run 2 different page code for the same result.

Redirect from the other hand is a method to navigate and show results to the processing of user input. Its clean, code on the second page work with out problems, postback and all that work the same.

I suggest to anyone to rare use the Server.Transfer.

Here is an example that Transfer make thinks complicate and slower. If you have a work to do, and then show result, and lets say that this work makes some seconds, if you make Transfer, on every post back, or reload the work must be run again !.

protected void Page_Load(object sender, EventArgs e)
{
    // function works
    Thread.Sleep(10000);
    Server.Transfer("Page2.aspx");
}

Second Case with redirect, the work will be done one time and not called again, user moves to the result page.

protected void Page_Load(object sender, EventArgs e)
{
    // function works
    Thread.Sleep(10000);
    Response.Redirect("Page2.aspx");
}

I think, that there is no need for too many talks, if you practice them a little you can see many thinks and different in real pages.


问:
Reading from stream failed - mysql_native_password error
I have been facing the following error intermittently.

Authentication to host '127.0.0.1' for user 'root' using method 'mysql_native_password' failed with message: Reading from the stream has failed.

It shots up any time and I am at my wits end. I also posted a bug on MySQL bugs and solutions are not proving to be effective in any way.I hope you guys can help me out.

Here is the link to MySQL Bug for details: Never seems to go away!

Some more detail: I have a client-server system but this bug occurs on the server system(where MySQL database is installed) when a local running app on the server system tries to run a query.

I had already opened a question here but since has been dead. Just a caveat I thought that skip-name-resolve solved the issue but it seems to just have lowered the frequency. Hope someone would help me out this time around.

EDIT: The MySQL guys say that in a client server setup server may close a connection if it is unused for a long time. However, this is not what I am facing as I create a new connection everytime I want to execute a query. I made this point clear in the last comment on the MySQL Bugs.

答:
Guys I tried this: "SslMode=None" in the connection string, but if you need SSL then read this:
http://www.voidcn.com/article/p-phfoefri-bpr.html

here is a sample connection string that works:

```<code>connectionString="Server=192.168.10.5;Database=mydata;Uid=root;Pwd=****;SslMode=None"
</code>```

Hope this helps

Body:
Guys I tried this: "SslMode=None" in the connection string, but if you need SSL then read this:
http://www.voidcn.com/article/p-phfoefri-bpr.html

here is a sample connection string that works:

connectionString="Server=192.168.10.5;Database=mydata;Uid=root;Pwd=****;SslMode=None"

Hope this helps


答:
You can use the strtok and strtol functions for this (if you're reading from strings):

```<code>int port = 0;
char *tmp_str;
strtok(port_str, ": ");
tmp_str = strtok(NULL, ": ");
port = strtol(tmp_str, NULL, 10);
</code>```

etcetera.

Otherwise, use fscanf formatted input:

```<code>fscanf(file_pointer, "%*s%d", &port);
fscanf(file_pointer, "%*s%s", ip_str);
fscanf(file_pointer, "%*s%s", dir_str);
</code>```

The *s in the format specifiers tell fscanf to ignore the string read ("Port", "IP", "Directory", etc.) and then the : (colon + space) tells fscanf to ignore the colon and any whitespace after it. Then fscanf reads an integer or a string (%d or %s, respectively) into the parameter passed to fscanf.

Title: How do I manipulate strings to store parts of them as variables?

Body:
I have a txt file that contains a bunch of information that my program needs to read from eg.

Port: 1337

IP: "IP"

Directory: " "

I need to be able to store everything past the ": " from each line and save the part of the string as a variable eg. int port = 1337, something like that???

What functions should I use and how do I format this in order for it to work with as little code as possible.

Body:
You can use the strtok and strtol functions for this (if you're reading from strings):

int port = 0;
char *tmp_str;
strtok(port_str, ": ");
tmp_str = strtok(NULL, ": ");
port = strtol(tmp_str, NULL, 10);

etcetera.

Otherwise, use fscanf formatted input:

fscanf(file_pointer, "%*s%d", &port);
fscanf(file_pointer, "%*s%s", ip_str);
fscanf(file_pointer, "%*s%s", dir_str);

The *s in the format specifiers tell fscanf to ignore the string read ("Port", "IP", "Directory", etc.) and then the : (colon + space) tells fscanf to ignore the colon and any whitespace after it. Then fscanf reads an integer or a string (%d or %s, respectively) into the parameter passed to fscanf.


问:
C Networking: Sendto() returning Errno 22, EINVAL
I'm attempting to generate a packet from scratch with Layer 2, 3, and 4 components (namely Ethernet, IP, and UDP). My socket is configured to use SOCK_RAW as the type and IPPROTO_RAW as the protocol, so that my program can be used to send different protocols at a later date. I've strictly abided by the sendto(2) man page (https://linux.die.net/man/2/sendto), however, I still seem to be having troubles transmitting a packet over local host. The error returned by my program is 22, or EINVAL, indicating that I've passed an incorrect argument.

I've already used Sockets sendto() returning EINVAL and Socket programming: sendto always fails with errno 22 (EINVAL) in attempt to resolve my problem. I've even switched the socket to use SOCK_DGRAM as the type and IPPROTO_UDP as the protocol to see if it was something to do with the socket (though I don't believe this would have prompted an incorrect argument response).

My code is as follows:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/ip.h>
#include <netinet/ether.h>
#include <netinet/udp.h>
#include <sys/socket.h>
#include <errno.h>

#define BUFFER 1024

int main(int argc, char *argv[]) {

        /* Socket Creation */
    int sockfd;

    if ((sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW)) == -1) {
            perror("Socket");
            exit(EXIT_FAILURE);
    }

    // This will hold all of the packet's contents
    char sendbuf[BUFFER];

    /* Address Stuff */

    // Specify Address
    in_addr_t address = inet_addr("127.0.0.1");

    // Specifying Address for Sendto()
    struct sockaddr_in sendto_addr;
    memset(&sendto_addr, 0, sizeof(sendto_addr));
    sendto_addr.sin_family = AF_INET;
    sendto_addr.sin_port = htons(9623);  // Make sure the port isn't contested
    sendto_addr.sin_addr.s_addr = address;

    // Size of whole packet
    size_t total_len = 0;

    /* LAYER 2 */
    // Ethernet Header Configuration
    struct ether_header *ether = (struct ether_header *)sendbuf;
    int i;
    for (i = 0; i < 6; ++i) {
        ether -> ether_dhost[i] = 0x00; // Temporary data fill
        ether -> ether_shost[i] = 0x00; // Temporary data fill
    }
    ether -> ether_type = ETHERTYPE_IP;

    total_len += sizeof(struct ether_header);

    /* LAYER 3 */
    // IP Header Configuration
    struct ip *ip = (struct ip *)(sendbuf + sizeof(struct ether_header));

    ip -> ip_hl = 5;
    ip -> ip_v = 4;
    ip -> ip_tos = 0;
    ip -> ip_p = 17;
    ip -> ip_ttl = 255;
    ip -> ip_src.s_addr = address;
    ip -> ip_dst.s_addr = address;

    total_len += sizeof(struct ip);

    /* LAYER 4 */
    // UDP Header Configuration
    struct udphdr *udp = (struct udphdr *)(sendbuf + sizeof(struct ether_header) + \
                                           sizeof(struct ip));

    udp -> source = 123; // Gibberish to fill in later
    udp -> dest = 321;   // Gibberish to fill in later
    udp -> check = 0;

    total_len += sizeof(struct udphdr);

    /* Giberrish Packet Data */
    sendbuf[total_len++] = 0x00;
    sendbuf[total_len++] = 0x00;
    sendbuf[total_len++] = 0x00;
    sendbuf[total_len++] = 0x00;

    /* Fill in Rest of Headers */
    udp -> len = htons(total_len - sizeof(struct ether_header) - sizeof(struct ip));
    ip -> ip_len = htons(total_len - sizeof(struct ether_header));

    /* Send Packet */  // ERROR OCCURS HERE
    printf("Sockfd is %d\n", sockfd);
    printf("Total length is %d\n", total_len);
    if (sendto(sockfd, sendbuf, total_len, 0, (const struct sockaddr*)&sendto_addr, \
        sizeof(sendto_addr)) < 0) {
            printf("Error sending packet: Error %d.\n", errno);
            perror("sendto Error");
            exit(EXIT_FAILURE);
    }

    close(sockfd);

}
</code>```

The precise console message states:

Sockfd is 3

      Total length is 46

      Error sending packet: Error 22.

      sendto Error: Invalid argument

答:
Eureka! It was actually this line:

```<code>if ((sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW)) == -1) {
        perror("Socket");
        exit(EXIT_FAILURE);
}
</code>```

Which should have been

```<code>if ((sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
        perror("Socket");
        exit(EXIT_FAILURE);
}
</code>```

Why this fixed the problem? Great question, would love to see someone's response on the subject :P

Body:
I'm attempting to generate a packet from scratch with Layer 2, 3, and 4 components (namely Ethernet, IP, and UDP). My socket is configured to use SOCK_RAW as the type and IPPROTO_RAW as the protocol, so that my program can be used to send different protocols at a later date. I've strictly abided by the sendto(2) man page (https://linux.die.net/man/2/sendto), however, I still seem to be having troubles transmitting a packet over local host. The error returned by my program is 22, or EINVAL, indicating that I've passed an incorrect argument.

I've already used Sockets sendto() returning EINVAL and Socket programming: sendto always fails with errno 22 (EINVAL) in attempt to resolve my problem. I've even switched the socket to use SOCK_DGRAM as the type and IPPROTO_UDP as the protocol to see if it was something to do with the socket (though I don't believe this would have prompted an incorrect argument response).

My code is as follows:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/ip.h>
#include <netinet/ether.h>
#include <netinet/udp.h>
#include <sys/socket.h>
#include <errno.h>

#define BUFFER 1024

int main(int argc, char *argv[]) {

        /* Socket Creation */
    int sockfd;

    if ((sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW)) == -1) {
            perror("Socket");
            exit(EXIT_FAILURE);
    }

    // This will hold all of the packet's contents
    char sendbuf[BUFFER];

    /* Address Stuff */

    // Specify Address
    in_addr_t address = inet_addr("127.0.0.1");

    // Specifying Address for Sendto()
    struct sockaddr_in sendto_addr;
    memset(&sendto_addr, 0, sizeof(sendto_addr));
    sendto_addr.sin_family = AF_INET;
    sendto_addr.sin_port = htons(9623);  // Make sure the port isn't contested
    sendto_addr.sin_addr.s_addr = address;

    // Size of whole packet
    size_t total_len = 0;

    /* LAYER 2 */
    // Ethernet Header Configuration
    struct ether_header *ether = (struct ether_header *)sendbuf;
    int i;
    for (i = 0; i < 6; ++i) {
        ether -> ether_dhost[i] = 0x00; // Temporary data fill
        ether -> ether_shost[i] = 0x00; // Temporary data fill
    }
    ether -> ether_type = ETHERTYPE_IP;

    total_len += sizeof(struct ether_header);

    /* LAYER 3 */
    // IP Header Configuration
    struct ip *ip = (struct ip *)(sendbuf + sizeof(struct ether_header));

    ip -> ip_hl = 5;
    ip -> ip_v = 4;
    ip -> ip_tos = 0;
    ip -> ip_p = 17;
    ip -> ip_ttl = 255;
    ip -> ip_src.s_addr = address;
    ip -> ip_dst.s_addr = address;

    total_len += sizeof(struct ip);

    /* LAYER 4 */
    // UDP Header Configuration
    struct udphdr *udp = (struct udphdr *)(sendbuf + sizeof(struct ether_header) + \
                                           sizeof(struct ip));

    udp -> source = 123; // Gibberish to fill in later
    udp -> dest = 321;   // Gibberish to fill in later
    udp -> check = 0;

    total_len += sizeof(struct udphdr);

    /* Giberrish Packet Data */
    sendbuf[total_len++] = 0x00;
    sendbuf[total_len++] = 0x00;
    sendbuf[total_len++] = 0x00;
    sendbuf[total_len++] = 0x00;

    /* Fill in Rest of Headers */
    udp -> len = htons(total_len - sizeof(struct ether_header) - sizeof(struct ip));
    ip -> ip_len = htons(total_len - sizeof(struct ether_header));

    /* Send Packet */  // ERROR OCCURS HERE
    printf("Sockfd is %d\n", sockfd);
    printf("Total length is %d\n", total_len);
    if (sendto(sockfd, sendbuf, total_len, 0, (const struct sockaddr*)&sendto_addr, \
        sizeof(sendto_addr)) < 0) {
            printf("Error sending packet: Error %d.\n", errno);
            perror("sendto Error");
            exit(EXIT_FAILURE);
    }

    close(sockfd);

}

The precise console message states:

Sockfd is 3

      Total length is 46

      Error sending packet: Error 22.

      sendto Error: Invalid argument

Body:
Eureka! It was actually this line:

if ((sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW)) == -1) {
        perror("Socket");
        exit(EXIT_FAILURE);
}

Which should have been

if ((sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
        perror("Socket");
        exit(EXIT_FAILURE);
}

Why this fixed the problem? Great question, would love to see someone's response on the subject :P


问:
What is the benefit of wrapping fetch in a promise?
I see people wrapping the fetch method in a promise. I can't seem to understand the benefit of doing so? Fetch itself returns a promise and you can extract what you need from that.

```<code>let url = 'https://jsonplaceholder.typicode.com/users';

fetch(url)
 .then(function(response){
   //console.log(response.json());
   return response.json();

 })

 .then(function(data){
   console.log(JSON.stringify(data));
 })

 .catch(function(err){
 //console.log(err);
 err = 'this is an error';
 console.log(err);
 })
</code>```

compared to this

```<code>return new Promise((resolve, reject) => {
  fetch(url)
  .then(res => res.json())
  .then(data => resolve(data))
  .catch(err => reject(err));
});
</code>```

答:
"It returns a Promise that resolves to the Response to that request, whether it is successful or not."

Source

There is no point. It's just something people are doing who are probably used to working with things like jQuery Deferreds which don't have a proper A+ Promise implementation. If you wanted, you could do this if you were using something like Bluebird I guess but it's more or less pointless.

Body:
I see people wrapping the fetch method in a promise. I can't seem to understand the benefit of doing so? Fetch itself returns a promise and you can extract what you need from that.

let url = 'https://jsonplaceholder.typicode.com/users';

fetch(url)
 .then(function(response){
   //console.log(response.json());
   return response.json();

 })

 .then(function(data){
   console.log(JSON.stringify(data));
 })

 .catch(function(err){
 //console.log(err);
 err = 'this is an error';
 console.log(err);
 })

compared to this

return new Promise((resolve, reject) => {
  fetch(url)
  .then(res => res.json())
  .then(data => resolve(data))
  .catch(err => reject(err));
});


问:
How to align 2 forms in the same line?
I'm trying to make the login view of a web page, this login view have two forms (one for register and another for login) and I want to align them and put them in the same line.

At first I've tried to use a table in order to achieve this, but this was unsuccessful, so I used some bootstrap form groups (rows and cols) but I was unsuccessful as well, in the end I managed to put them in the same line using the float attribute, but the result that I got it wasn't good enough.

            Inicio
            Nuevas Adiciones

                <button class="dropbtn">Categoría

                </button>

                    Punk
                    Rock
                    Emo

                <button class="dropbtn">Tipo de Material

                </button>

                    Vinilos
                    Discos Compactos
                    Casetes

                    Iniciar Sesión

    <form class="bord" style="float: left;">
        <legend>Crear Cuenta</legend>

            Example label
            <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">

            Another label
            <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">

    </form>

    <form class="bord" style="float: right;">
        <legend>Registrarse</legend>

            Example label
            <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">

            Another label
            <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">

    </form>

Contacto

Email: pedidos@vinilos.pe

Teléfono: 3291177

Vinilos.Pe © 2019 Derechos Reservados

```

<pre class="lang-css prettyprint-override"><code>
/* THIS IS MY CSS */

.bord {
    display: block;
    margin-top: 15px;
    padding-top: 0.35em;
    padding-bottom: 0.625em;
    padding-left: 0.75em;
    padding-right: 0.75em;
    border-style: solid;
    border-width: 2.5px;
    text-align: center;
  }
</code>```

I was trying to achieve the look of this mockup, but instead for some reason the footer comes up and it looks like this.

答:
You can try this:

Your HTML:

```<code><div class="formWrapper">
    <form>First Form</form>
    <form>Second Form</form>
</div>
</code>```

Your CSS:

```<code>.formWrapper{
    display: flex;
}
</code>```

The forms will be inline... you'll just need to put some extra style to size and position your forms.

Title: How to align 2 forms in the same line?

Body:
I'm trying to make the login view of a web page, this login view have two forms (one for register and another for login) and I want to align them and put them in the same line.

At first I've tried to use a table in order to achieve this, but this was unsuccessful, so I used some bootstrap form groups (rows and cols) but I was unsuccessful as well, in the end I managed to put them in the same line using the float attribute, but the result that I got it wasn't good enough.

            Inicio
            Nuevas Adiciones

                <button class="dropbtn">Categoría

                </button>

                    Punk
                    Rock
                    Emo

                <button class="dropbtn">Tipo de Material

                </button>

                    Vinilos
                    Discos Compactos
                    Casetes

                    Iniciar Sesión

    <form class="bord" style="float: left;">
        <legend>Crear Cuenta</legend>

            Example label
            <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">

            Another label
            <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">

    </form>

    <form class="bord" style="float: right;">
        <legend>Registrarse</legend>

            Example label
            <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">

            Another label
            <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">

    </form>

Contacto

Email: pedidos@vinilos.pe

Teléfono: 3291177

Vinilos.Pe © 2019 Derechos Reservados

/* THIS IS MY CSS */

.bord {
    display: block;
    margin-top: 15px;
    padding-top: 0.35em;
    padding-bottom: 0.625em;
    padding-left: 0.75em;
    padding-right: 0.75em;
    border-style: solid;
    border-width: 2.5px;
    text-align: center;
  }

I was trying to achieve the look of this mockup, but instead for some reason the footer comes up and it looks like this.

Body:
You can try this:

Your HTML:

<div class="formWrapper">
    <form>First Form</form>
    <form>Second Form</form>
</div>

Your CSS:

.formWrapper{
    display: flex;
}

The forms will be inline... you'll just need to put some extra style to size and position your forms.


问:
Android: ExpandableListViews and Checkboxes
I have being playing around with expandable list views recently.

I am trying to get a list view that has a checkbox as one of the elements of the child view.

I found this tutorial, http://mylifewithandroid.blogspot.com/2010/02/expandable-lists-and-check-boxes.html,  and it seemed perfect. However when I compiled it and started playing with it I realised its very buggy. Checking a box in one group can cause a random box from another group to check or uncheck.,

This is the only tutorial I can find on this, It seems like a thing that would be used in a lot of apps, so I was wondering, is there any other good tutorial or resource out there that deals with this?

Or even better, would anyone care to show their own code having gotten this to work...

Thanks

Kev

答:
I had the same problem when developing a nagios client to android, and i found, that is crucial that you assign new value to the convertView parameter in both the

public View getGroupView(int
groupPosition, boolean isExpanded,
View convertView, ViewGroup parent)
and

public View getChildView(int
groupPosition, int childPosition,
boolean isLastChild, View
convertView, ViewGroup parent)

methods in your BaseExpandableListAdapter extension.

Otherwise the parent/child renderers will be built up from cache, and they won't show you the right things.

I need the checkbox for showing whether the user needs any kind of alert whether something goes wrong with the watched service.

Here is my way of achieving this:

```<code>//hosts: the list of data used to build up the hierarchy shown by this adapter's parent list.
private class MyExpandableListAdapter extends BaseExpandableListAdapter
{
    private LayoutInflater inflater;

    public MyExpandableListAdapter()
    {
        inflater = LayoutInflater.from(Binding.this);
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
    {
        final Host host = hosts.get(groupPosition);
        final boolean needsLargeView = isExpanded && (host.getTitle() != null) && (host.getTitle().length() > 0);
        if (needsLargeView)
            convertView = inflater.inflate(R.layout.grouprow_expanded, parent, false);
        else
            convertView = inflater.inflate(R.layout.grouprow, parent, false);
        convertView.setBackgroundResource(host.getBackgroundResource(isExpanded));
        [...]
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
    {
        final Host host = hosts.get(groupPosition);
        final NagService service = host.getServices().get(childPosition);
        convertView = inflater.inflate(R.layout.childrow, parent, false);
        convertView.setBackgroundResource(host.getChildBackgroundResource());
        convertView.findViewById(R.id.servicename_status).setBackgroundResource(service.getStatusBackground());
        [...]
        CheckBox alertChb = (CheckBox) convertView.findViewById(R.id.alert);
        alertChb.setChecked(service.isNeedsAlert());
        alertChb.setOnCheckedChangeListener(new YourCheckChangedListener(service));
        return convertView;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition)
    {
        return hosts.get(groupPosition).getServices().get(childPosition);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition)
    {
        return childPosition;
    }

    @Override
    public int getChildrenCount(int groupPosition)
    {
        return hosts.get(groupPosition).getServices().size();
    }

    @Override
    public Object getGroup(int groupPosition)
    {
        return hosts.get(groupPosition);
    }

    @Override
    public int getGroupCount()
    {
        return hosts.size();
    }

    @Override
    public long getGroupId(int groupPosition)
    {
        return groupPosition;
    }

    @Override
    public void notifyDataSetChanged()
    {
        super.notifyDataSetChanged();
    }

    @Override
    public boolean isEmpty()
    {
        return ((hosts == null) || hosts.isEmpty());
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition)
    {
        return true;
    }

    @Override
    public boolean hasStableIds()
    {
        return true;
    }

    @Override
    public boolean areAllItemsEnabled()
    {
        return true;
    }
}
</code>```

The childrow.xml among the layouts used is the one that contains the checkbox.

Inside the CheckedChanhedListener you should save the new state on the affected instance (in my case, the service).

I hope this helps you

ContentLicense: CC BY-SA 2.5

Body:
I had the same problem when developing a nagios client to android, and i found, that is crucial that you assign new value to the convertView parameter in both the

public View getGroupView(int
groupPosition, boolean isExpanded,
View convertView, ViewGroup parent)
and

public View getChildView(int
groupPosition, int childPosition,
boolean isLastChild, View
convertView, ViewGroup parent)

methods in your BaseExpandableListAdapter extension.

Otherwise the parent/child renderers will be built up from cache, and they won't show you the right things.

I need the checkbox for showing whether the user needs any kind of alert whether something goes wrong with the watched service.

Here is my way of achieving this:

//hosts: the list of data used to build up the hierarchy shown by this adapter's parent list.
private class MyExpandableListAdapter extends BaseExpandableListAdapter
{
    private LayoutInflater inflater;

    public MyExpandableListAdapter()
    {
        inflater = LayoutInflater.from(Binding.this);
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
    {
        final Host host = hosts.get(groupPosition);
        final boolean needsLargeView = isExpanded && (host.getTitle() != null) && (host.getTitle().length() > 0);
        if (needsLargeView)
            convertView = inflater.inflate(R.layout.grouprow_expanded, parent, false);
        else
            convertView = inflater.inflate(R.layout.grouprow, parent, false);
        convertView.setBackgroundResource(host.getBackgroundResource(isExpanded));
        [...]
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
    {
        final Host host = hosts.get(groupPosition);
        final NagService service = host.getServices().get(childPosition);
        convertView = inflater.inflate(R.layout.childrow, parent, false);
        convertView.setBackgroundResource(host.getChildBackgroundResource());
        convertView.findViewById(R.id.servicename_status).setBackgroundResource(service.getStatusBackground());
        [...]
        CheckBox alertChb = (CheckBox) convertView.findViewById(R.id.alert);
        alertChb.setChecked(service.isNeedsAlert());
        alertChb.setOnCheckedChangeListener(new YourCheckChangedListener(service));
        return convertView;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition)
    {
        return hosts.get(groupPosition).getServices().get(childPosition);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition)
    {
        return childPosition;
    }

    @Override
    public int getChildrenCount(int groupPosition)
    {
        return hosts.get(groupPosition).getServices().size();
    }

    @Override
    public Object getGroup(int groupPosition)
    {
        return hosts.get(groupPosition);
    }

    @Override
    public int getGroupCount()
    {
        return hosts.size();
    }

    @Override
    public long getGroupId(int groupPosition)
    {
        return groupPosition;
    }

    @Override
    public void notifyDataSetChanged()
    {
        super.notifyDataSetChanged();
    }

    @Override
    public boolean isEmpty()
    {
        return ((hosts == null) || hosts.isEmpty());
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition)
    {
        return true;
    }

    @Override
    public boolean hasStableIds()
    {
        return true;
    }

    @Override
    public boolean areAllItemsEnabled()
    {
        return true;
    }
}

The childrow.xml among the layouts used is the one that contains the checkbox.

Inside the CheckedChanhedListener you should save the new state on the affected instance (in my case, the service).

I hope this helps you


问:
Modify string using Unix CLI in all scss files
I would like to get rid of all @include rem() statements in my sass files and I want to replace them for specified declarations and values, examples:

@include rem(font-size, 11px); has to be font-size: 11px; instead

@include rem(height, 200px); has to be height: 200px; and so on ...

Is it possible to replace it via Unix CLI (sed maybe)?

答:
Please try the following:

```<code>find . -type f -name '*.sass' -print0 | xargs -0 sed -i 's/@include rem(\([^,]\{1,\}\), *\([^)]\{1,\}\))/\1: \2/g'
</code>```

If you are working on MacOS, please try instead:

```<code>find . -type f -name '*.sass' -print0 | xargs -0 sed -i '' 's/@include rem(\([^,]\{1,\}\), *\([^)]\{1,\}\))/\1: \2/g'
</code>```

Body:
Please try the following:

find . -type f -name '*.sass' -print0 | xargs -0 sed -i 's/@include rem(\([^,]\{1,\}\), *\([^)]\{1,\}\))/\1: \2/g'

If you are working on MacOS, please try instead:

find . -type f -name '*.sass' -print0 | xargs -0 sed -i '' 's/@include rem(\([^,]\{1,\}\), *\([^)]\{1,\}\))/\1: \2/g'


问:
Finding all possible paths in a dataset using sas
I want to compare two columns in the dataset shown below

```<code>Pid       cid
1          2
2          3
2          5
3          6
4          8
8          9
9          4
</code>```

Then produce a result like below

```<code>1 2 3 6
1 2 5
2 3 6
2 5
3 6
4 8 9 4
8 9 4
9 4
</code>```

First we print the first two values 1 and 2, search for 2 in first column, if its present print its corresponding value from column 2, which is 3. Search for 3 in column 1, if present print the corresponding value from column 2 which is 6

How can this be done using SAS?

答:
```<code>proc ds2;
data _null_;
    declare int t1[7];
    declare int t2[7];
    declare varchar(100) lst;

    method f2(int i, int Y);
        do while (y ^= t1[i] and i < dim(t1));
            i+1;
        end;
        if y = t1[i] then do;
           lst = cat(lst,t2[i]);
           f2(i, t2[i]);
        end;
    end;

    method f1(int n, int x, int y);
        dcl int i;
        dcl int match;
        match=0;
        do i = n to dim(t1);
            lst = cat(x,y);
            if (y = t1[i]) then do;
               f2(i,y);
               put lst=;
               match = 1;
            end;
        end;
        if ^match then put lst=;
    end;

    method init();
    dcl int i;
        t1 := (1 2 2 3 4 8 9);
        t2 := (2 3 5 6 8 9 4);
        do i = 1 to dim(t1);
           f1(i, t1[i], t2[i]);
        end;
    end;
enddata;
run;
quit;`enter code here`
</code>```

Body:
I want to compare two columns in the dataset shown below

Pid       cid
1          2
2          3
2          5
3          6
4          8
8          9
9          4

Then produce a result like below

1 2 3 6
1 2 5
2 3 6
2 5
3 6
4 8 9 4
8 9 4
9 4

First we print the first two values 1 and 2, search for 2 in first column, if its present print its corresponding value from column 2, which is 3. Search for 3 in column 1, if present print the corresponding value from column 2 which is 6

How can this be done using SAS?


问:
DLL error when importing tensorflow in anaconda environment
I have installed tensorflow in the anaconda environment. I have installed the latest anaconda and tensorflow by "conda install tensorflow-gpu". When I try to import tensorflow it works in the jupyter notebook. But the same code does run when I try to run from python terminal or when I run by "start debugging" from vs code. This is the error I am getting:

```<code>    Traceback (most recent call last):
  File "c:\Users\Admin\.vscode\extensions\ms-python.python-2019.4.12954\pythonFiles\ptvsd_launcher.py", line 43, in <module>
    main(ptvsdArgs)
  File "c:\Users\Admin\.vscode\extensions\ms-python.python-2019.4.12954\pythonFiles\lib\python\ptvsd\__main__.py", line 410, in main
    run()
  File "c:\Users\Admin\.vscode\extensions\ms-python.python-2019.4.12954\pythonFiles\lib\python\ptvsd\__main__.py", line 291, in run_file
    runpy.run_path(target, run_name='__main__')
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "d:\Projects\SASRec\SASRec Pytorch\main.py", line 7, in <module>
    import tensorflow as tf
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.
</code>```

Can anyone kindly give me a solution and make my life easier. Thanks!

答:
So, after a lot of installing, uninstalling and reinstalling and scraping various similar issues in github and stackoverflow, I got a pretty simple solution. In my system, I only have Anaconda installed and c++ build tools from Microsoft (2019), and nothing else. Then I installed tensorflow as follows: </p>

```<code>conda install tensorflow-gpu=1.10
</code>```

<p>Apparently, this older version is compatible with the DLL and everything seems to work. </p>

Body:
I have installed tensorflow in the anaconda environment. I have installed the latest anaconda and tensorflow by "conda install tensorflow-gpu". When I try to import tensorflow it works in the jupyter notebook. But the same code does run when I try to run from python terminal or when I run by "start debugging" from vs code. This is the error I am getting:

    Traceback (most recent call last):
  File "c:\Users\Admin\.vscode\extensions\ms-python.python-2019.4.12954\pythonFiles\ptvsd_launcher.py", line 43, in <module>
    main(ptvsdArgs)
  File "c:\Users\Admin\.vscode\extensions\ms-python.python-2019.4.12954\pythonFiles\lib\python\ptvsd\__main__.py", line 410, in main
    run()
  File "c:\Users\Admin\.vscode\extensions\ms-python.python-2019.4.12954\pythonFiles\lib\python\ptvsd\__main__.py", line 291, in run_file
    runpy.run_path(target, run_name='__main__')
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "d:\Projects\SASRec\SASRec Pytorch\main.py", line 7, in <module>
    import tensorflow as tf
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\Admin\Anaconda3\envs\tf-gpu\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.

Can anyone kindly give me a solution and make my life easier. Thanks!

Body:
So, after a lot of installing, uninstalling and reinstalling and scraping various similar issues in github and stackoverflow, I got a pretty simple solution. In my system, I only have Anaconda installed and c++ build tools from Microsoft (2019), and nothing else. Then I installed tensorflow as follows:

conda install tensorflow-gpu=1.10

Apparently, this older version is compatible with the DLL and everything seems to work.


问:
Error 1004 when attempting to save as PDF via macro in Excel on network drive
Apologies in advance, as I am very new to this and finding this a very steep learning curve!

I have an Excel document that is used by myself and colleagues, and have a macro button to save this as a PDF document. The PDF needs to be saved in a folder on a network drive, in a year folder then a month folder.

I have some code which works great for me. I creates a new year folder if it doesn't exist, creates a month folder if it doesn't exist, then saves the PDF in this folder.

However, this only works for me.

When a colleague attempts to do this on their computer, Excel creates the folders but does not save the PDF, giving a run-time error 1004.

I have attempted to change bits and pieces in the code, and nothing seems to work, so I am in a bit of a position really.

Here is the code I have at the moment:

```<code>    Sub Save_ActSht_as_Pdf()
    ' Saves active sheet as PDF file.
    Const basePath = "I:\folder path\"
    If Dir(basePath & Year(Date), vbDirectory) = "" Then MkDir basePath & Year(Date)
    If Dir(basePath & Format(Date, "yyyy\\mmmm yy"), vbDirectory) = "" Then MkDir basePath & Format(Date, "yyyy\\mmmm yy")
    ActiveSheet.ExportAsFixedFormat xlTypePDF, Format(Now, "yyyy\\mmmm yy\\ddd MMMM d yyyy AM/PM"), Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub
</code>```

(I have substituted the actual folder path for 'folder path' for ease)

The line that is highlighted during a debug is the one starting with ActiveSheet

Thank you in advance for any help with this problem.

答:
This works for me.

```<code>Option Explicit

   Sub Save_ActSht_as_Pdf()
    ' Saves active sheet as PDF file.
    Const basePath = "C:\folder path\"
    Dim fn As String
    If Dir(basePath & Year(Date), vbDirectory) = "" Then MkDir basePath & Year(Date)
    If Dir(basePath & Format(Date, "yyyy\\mmmm yy"), vbDirectory) = "" Then MkDir basePath & Format(Date, "yyyy\\mmmm yy")
    fn = basePath & Format(Now, "yyyy\\mmmm yy\\ddd MMMM d yyyy AM/PM") & ".pdf"
    ActiveSheet.ExportAsFixedFormat xlTypePDF, Filename:=fn, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True

End Sub
</code>```

I had to create "folder path" folder manually as MkDir can only create one folder level at once.

Also if the ActiveSheet is empty then runtime error 1004 happens as nothing to print

Body:
Apologies in advance, as I am very new to this and finding this a very steep learning curve!

I have an Excel document that is used by myself and colleagues, and have a macro button to save this as a PDF document. The PDF needs to be saved in a folder on a network drive, in a year folder then a month folder.

I have some code which works great for me. I creates a new year folder if it doesn't exist, creates a month folder if it doesn't exist, then saves the PDF in this folder.

However, this only works for me.

When a colleague attempts to do this on their computer, Excel creates the folders but does not save the PDF, giving a run-time error 1004.

I have attempted to change bits and pieces in the code, and nothing seems to work, so I am in a bit of a position really.

Here is the code I have at the moment:

    Sub Save_ActSht_as_Pdf()
    ' Saves active sheet as PDF file.
    Const basePath = "I:\folder path\"
    If Dir(basePath & Year(Date), vbDirectory) = "" Then MkDir basePath & Year(Date)
    If Dir(basePath & Format(Date, "yyyy\\mmmm yy"), vbDirectory) = "" Then MkDir basePath & Format(Date, "yyyy\\mmmm yy")
    ActiveSheet.ExportAsFixedFormat xlTypePDF, Format(Now, "yyyy\\mmmm yy\\ddd MMMM d yyyy AM/PM"), Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub

(I have substituted the actual folder path for 'folder path' for ease)

The line that is highlighted during a debug is the one starting with ActiveSheet

Thank you in advance for any help with this problem.

Body:
This works for me.

Option Explicit

   Sub Save_ActSht_as_Pdf()
    ' Saves active sheet as PDF file.
    Const basePath = "C:\folder path\"
    Dim fn As String
    If Dir(basePath & Year(Date), vbDirectory) = "" Then MkDir basePath & Year(Date)
    If Dir(basePath & Format(Date, "yyyy\\mmmm yy"), vbDirectory) = "" Then MkDir basePath & Format(Date, "yyyy\\mmmm yy")
    fn = basePath & Format(Now, "yyyy\\mmmm yy\\ddd MMMM d yyyy AM/PM") & ".pdf"
    ActiveSheet.ExportAsFixedFormat xlTypePDF, Filename:=fn, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True

End Sub

I had to create "folder path" folder manually as MkDir can only create one folder level at once.

Also if the ActiveSheet is empty then runtime error 1004 happens as nothing to print