问:
Extend tx_news with 1 field without extension_builder
I try to extend the tx_news extension with the field imageright.

For that I found this tutorial: https://docs.typo3.org/typo3cms/extensions/news/2.2.1/Main/Tutorial/ExtendingNews/Index.html

The first step is to use extension_builder to add the field. As I already have a extension in where I want to implement the extension I do not want to use the extension_builder (also I tried it with a new extension and extend the news-model did not work - I have no clue how to do it right). However this are the steps I did:

In my extension my_template I added the folders and file: Classes/Domain/Model/News.php:

```<code>    class MyTemplate_Domain_Model_News extends Tx_News_Domain_Model_News {

            /**
            * @var bool
            */
            protected $imageright;

            /**
             * Returns the imageright
             *
             * @return bool $imageright
             */
            public function getImageright() {
                    return $this->imageright;
            }

            /**
             * Sets the sort
             *
             * @param bool $imageright
             * @return void
             */
            public function setImageright($imageright)
            {
                $this->imageright = $imageright;
            }

    }

?>
</code>```

/Ressources/Private/extend-news.txt:

```<code>Domain/Model/News
</code>```

Created the field imageright as tinyint in the table tx_news_domain_model_news (and added it to the SQL file)

I knew I have to create a TCA file in /Configuration/TCA/, but I have no clue how this should look like or what name it needs to have. I think this is the last step I need to make this working.

Also note the extension my_template was just a template, so before my changes there where no Classes and no TCA files.

答: Solution is to use this tutorial: http://www.lukasjakob.com/extend-a-typo3-extbase-model-with-custom-field/ </p>

Body:
I try to extend the tx_news extension with the field imageright.

For that I found this tutorial: https://docs.typo3.org/typo3cms/extensions/news/2.2.1/Main/Tutorial/ExtendingNews/Index.html

The first step is to use extension_builder to add the field. As I already have a extension in where I want to implement the extension I do not want to use the extension_builder (also I tried it with a new extension and extend the news-model did not work - I have no clue how to do it right). However this are the steps I did:

In my extension my_template I added the folders and file: Classes/Domain/Model/News.php:

    class MyTemplate_Domain_Model_News extends Tx_News_Domain_Model_News {

            /**
            * @var bool
            */
            protected $imageright;

            /**
             * Returns the imageright
             *
             * @return bool $imageright
             */
            public function getImageright() {
                    return $this->imageright;
            }

            /**
             * Sets the sort
             *
             * @param bool $imageright
             * @return void
             */
            public function setImageright($imageright)
            {
                $this->imageright = $imageright;
            }

    }

?>

/Ressources/Private/extend-news.txt:

Domain/Model/News

Created the field imageright as tinyint in the table tx_news_domain_model_news (and added it to the SQL file)

I knew I have to create a TCA file in /Configuration/TCA/, but I have no clue how this should look like or what name it needs to have. I think this is the last step I need to make this working.

Also note the extension my_template was just a template, so before my changes there where no Classes and no TCA files.


来源: stackexchange

问:
Strange issue with intent startActivity causing my scanner to not work properly
So, after I finish my scanner activity with

```<code>      btn_take_photo.setOnClickListener(new FloatingActionButton.OnClickListener() {
        @Override
        public void onClick(View view) {
            String carde = cardnumberbox.getText().toString().trim();
            if (carde.matches("")) {
                Toast.makeText(getApplicationContext(), getString(R.string.Skan_Udfyld_Kort_Nummer), Toast.LENGTH_SHORT).show();
                cardnumberbox.requestFocus();
                return;
            }
            Intent i = new Intent(ScanActivity.this, CameraActivity.class);
            i.putExtra("EXTRA_SESSION_ID", carde);
            startActivity(i);

        }
    });
</code>```

to go to my cam activity so I can take some pictures and go back with

```<code>    public void btn_aprove2(View view) {
    Intent i = new Intent(CameraActivity.this, ScanActivity.class);
    String counts = count.getText().toString().trim();
    i.putExtra("EXTRA_SESSION_IDs", counts);
    String carde = cardnumberbox2.getText().toString().trim();
    i.putExtra("EXTRA_SESSION_ID", carde);
    startActivity(i);
    finish();
</code>```

to the scanneractivity again. My scanner does not work properly
but if I then press the back button it does go back to the scanneractivity again instead of my menu so it seems like the scanneractivity is running twice and only 1 of them are functional but is here where it confuses me

cause if do not press the btn_aprove2 button and just use the back button instead
i gets the exact same issue but here my scanneractivity is not runned twice as when i press the back button it just takes me back to the menu

a video of the issue

by removing my screen orientation from the manifest (so i can rotate it)
my scanner do now work but only if i first rotate to landscape and rotate it back to potrait

and i see in the log is that it is only calling the oncreate when rotating and only on resume and pause on the button's(startactivity/finnish)

I am totally lost on how to get this to work.

on github with api demo and documentation in the wiki and with thoose classes that are being used

答:
If you just jump to the Camera activity to get some data, I'd recommend you to start the activity for a result (startActivityForResult) without finishing the Scanner activity at all. This would give you a proper working back stack (using back button to go back from Camera to Scanner).

Besides that why are you using         i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);? You are starting a new activity and finishing the old one. I don't see why this flag is really needed. What is your android:launchMode in your manifest and are you sure you know what FLAG_ACTIVITY_NEW_TASK is doing and it is what you want?

Anyways from what you told us it looks like your example really should utilize startActivityForResult() without calling finish():

Press menu button on some activity

Start camera and do something

Press some button to start Scanner

Scan something and finish the scanner with the result (or cancel the scanner by clicking back)

Retrieve the result of the scanner in the camera and do something with it or continue with the previous workflow when scanner was cancelled

Once you are finished with your workflow, finish the camera so you end up in your activity where you started the camera

ContentLicense: CC BY-SA 3.0

Body:
So, after I finish my scanner activity with

      btn_take_photo.setOnClickListener(new FloatingActionButton.OnClickListener() {
        @Override
        public void onClick(View view) {
            String carde = cardnumberbox.getText().toString().trim();
            if (carde.matches("")) {
                Toast.makeText(getApplicationContext(), getString(R.string.Skan_Udfyld_Kort_Nummer), Toast.LENGTH_SHORT).show();
                cardnumberbox.requestFocus();
                return;
            }
            Intent i = new Intent(ScanActivity.this, CameraActivity.class);
            i.putExtra("EXTRA_SESSION_ID", carde);
            startActivity(i);

        }
    });

to go to my cam activity so I can take some pictures and go back with

    public void btn_aprove2(View view) {
    Intent i = new Intent(CameraActivity.this, ScanActivity.class);
    String counts = count.getText().toString().trim();
    i.putExtra("EXTRA_SESSION_IDs", counts);
    String carde = cardnumberbox2.getText().toString().trim();
    i.putExtra("EXTRA_SESSION_ID", carde);
    startActivity(i);
    finish();

to the scanneractivity again. My scanner does not work properly
but if I then press the back button it does go back to the scanneractivity again instead of my menu so it seems like the scanneractivity is running twice and only 1 of them are functional but is here where it confuses me

cause if do not press the btn_aprove2 button and just use the back button instead
i gets the exact same issue but here my scanneractivity is not runned twice as when i press the back button it just takes me back to the menu

a video of the issue

by removing my screen orientation from the manifest (so i can rotate it)
my scanner do now work but only if i first rotate to landscape and rotate it back to potrait

and i see in the log is that it is only calling the oncreate when rotating and only on resume and pause on the button's(startactivity/finnish)

I am totally lost on how to get this to work.

on github with api demo and documentation in the wiki and with thoose classes that are being used


问:
F# WSDL code generation
I'm using VS.NET 2010 integrated shell with F# and I'm trying to consume a soap web service... How do I go about generating F# source? I tried

wsdl l:"C:\Program Files (x86)\FSharpPowerPack-2.0.0.0\bin\FSharp.Compiler.CodeDom.dll" http://localhost/?wsdl

Along with

wsdl /language:"Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider, Microsoft.FSharp.Compiler.CodeDom, Version=1.9.2.9, Culture=neutral, PublicKeyToken=a19089b1c74d0809"

However I can't seem to get the /language switch to work.

EDIT:

taspeotis' answer got me going... This generated F# source for the web service:

```<code>gacutil -i "C:\Program Files (x86)\FSharpPowerPack-2.0.0.0\bin\FSharp.PowerPack.dll"
svcutil /language:"Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider, FSharp.Compiler.CodeDom, Version=2.0.0.0, Culture=neutral, PublicKeyToken=a19089b1c74d0809" http://localhost/?wsdl
</code>```

答:
I would be surprised if the F# Code DOM provider worked with WSDL. I wrote the initial implementation some time ago while at Microsoft and we got it to work with ASP.NET, but unless it has been improved since then, it probably won't work with WSDL or XSD.

Even for ASP.NET, we had to create a separate class that included some ASP.NET specific "hacks". This was partly because the CodeDOM generated by ASP.NET was invalid (in a way) and because the CodeDOM structure is not quite compatible with F#. If you really need to get this to work, you may have to add similar hacks (by modifying the source from CodePlex)

I tink that a safer approach is to include a small C# library project that generates the reference for you or invoking the C# compiler using csc.exe as Brian suggests.

ContentLicense: CC BY-SA 2.5

Title: F# WSDL code generation

Body:
I'm using VS.NET 2010 integrated shell with F# and I'm trying to consume a soap web service... How do I go about generating F# source? I tried

wsdl l:"C:\Program Files (x86)\FSharpPowerPack-2.0.0.0\bin\FSharp.Compiler.CodeDom.dll" http://localhost/?wsdl

Along with

wsdl /language:"Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider, Microsoft.FSharp.Compiler.CodeDom, Version=1.9.2.9, Culture=neutral, PublicKeyToken=a19089b1c74d0809"

However I can't seem to get the /language switch to work.

EDIT:

taspeotis' answer got me going... This generated F# source for the web service:

gacutil -i "C:\Program Files (x86)\FSharpPowerPack-2.0.0.0\bin\FSharp.PowerPack.dll"
svcutil /language:"Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider, FSharp.Compiler.CodeDom, Version=2.0.0.0, Culture=neutral, PublicKeyToken=a19089b1c74d0809" http://localhost/?wsdl


问:
Powershell exit status
what's the powershell equivalent of simply:

```<code>bash test.sh
</code>```

I'd like to call a powershell script (from outside a powershell environment) and be able to get a return value of 0 if it executed successfully, and otherwise a non-zero value if either:

the powershell executable can't be found or executed

the script test.ps1 can't be found or executed (insufficient permissions, ...)

the script test.ps1 can be read and executed but returns a non zero value

And then, how to access this return value, which in linux would be

```<code>echo $?
</code>```

答:
Simply using

```<code>powershell -file foo.ps1
</code>```

should work:

```<code>C:\>set PATH=
C:\>powershell -file Untitled1.ps1
'powershell' is not recognized as an internal or external command,
operable program or batch file.
C:\>echo %errorlevel%
9009

C:\>powershell -File not-there.ps1
The argument 'not-there.ps1' to the -File parameter does not exist. Provide the path to an existing '.ps1' file as an argument to the -File parameter.
Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.
C:\>echo %errorlevel%
-196608

C:\>powershell -file exitcode.ps1
C:\>echo %errorlevel%
1337
</code>```

Title: Powershell exit status

Body:
what's the powershell equivalent of simply:

bash test.sh

I'd like to call a powershell script (from outside a powershell environment) and be able to get a return value of 0 if it executed successfully, and otherwise a non-zero value if either:

the powershell executable can't be found or executed

the script test.ps1 can't be found or executed (insufficient permissions, ...)

the script test.ps1 can be read and executed but returns a non zero value

And then, how to access this return value, which in linux would be

echo $?

Body:
Simply using

powershell -file foo.ps1

should work:

C:\>set PATH=
C:\>powershell -file Untitled1.ps1
'powershell' is not recognized as an internal or external command,
operable program or batch file.
C:\>echo %errorlevel%
9009

C:\>powershell -File not-there.ps1
The argument 'not-there.ps1' to the -File parameter does not exist. Provide the path to an existing '.ps1' file as an argument to the -File parameter.
Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.
C:\>echo %errorlevel%
-196608

C:\>powershell -file exitcode.ps1
C:\>echo %errorlevel%
1337


问:
Accessing data in an array of object for a map in React
```<code>"data": {
 "offset": 0,
 "limit": 20,
 "total": 1,
 "count": 1,
 "results": [
   {
    "id": 1009144,
    "name": "A.I.M.",
    "modified": "2013-10-17T14:41:30-0400",
    "thumbnail": {
      "path": "i.annihil.us/u/prod/marvel/i/mg/6/20/52602f21f29ec",
      "extension": "jpg"
    },
    "resourceURI": "gateway.marvel.com/v1/public/characters/1009144",
    "comics": {
      "available": 33,
      "collectionURI": "gateway.marvel.com/v1/public/characters/1009144/comics",
      "items": [
        {
          "resourceURI": "gateway.marvel.com/v1/public/comics/36763",
          "name": "Ant-Man & the Wasp (2010) #3"
        },
        {
          "resourceURI": "gateway.marvel.com/v1/public/comics/17553",
          "name": "Avengers (1998) #67"
        }
     ]
   }
  }
]
}
</code>```

I  am using axios to fetch datas from an api inside a React component. I would like to access to the key items in my json response in order to setState but I can't.

```<code>export default class Hero extends React.Component {
constructor(props) {
super(props);
this.state = {
    details : [],
    comics :[]
};
}
componentDidMount() {
    axios.get(infoUrl).then((res) => {
    this.setState({details : res.data.data.results,
                    comics : res.data.data.results.results[6].items});
})
}
render() {

     (<div>
      </div>)
}
}
</code>```

I can access to my state details but not the comics one.

答:
items being present in comics is not the 6th item in the result array but the 6th item in the first object of the result array and hence you need to access it like.

```<code>res.data.data.results[0].comics.items
</code>```

Change you componentDidMount function to

```<code>componentDidMount() {
    axios.get(infoUrl).then((res) => {
    this.setState({details : res.data.data.results,
                    comics : res.data.data.results[0].items});
    })
}
</code>```

Body:
"data": {
 "offset": 0,
 "limit": 20,
 "total": 1,
 "count": 1,
 "results": [
   {
    "id": 1009144,
    "name": "A.I.M.",
    "modified": "2013-10-17T14:41:30-0400",
    "thumbnail": {
      "path": "i.annihil.us/u/prod/marvel/i/mg/6/20/52602f21f29ec",
      "extension": "jpg"
    },
    "resourceURI": "gateway.marvel.com/v1/public/characters/1009144",
    "comics": {
      "available": 33,
      "collectionURI": "gateway.marvel.com/v1/public/characters/1009144/comics",
      "items": [
        {
          "resourceURI": "gateway.marvel.com/v1/public/comics/36763",
          "name": "Ant-Man & the Wasp (2010) #3"
        },
        {
          "resourceURI": "gateway.marvel.com/v1/public/comics/17553",
          "name": "Avengers (1998) #67"
        }
     ]
   }
  }
]
}

I  am using axios to fetch datas from an api inside a React component. I would like to access to the key items in my json response in order to setState but I can't.

export default class Hero extends React.Component {
constructor(props) {
super(props);
this.state = {
    details : [],
    comics :[]
};
}
componentDidMount() {
    axios.get(infoUrl).then((res) => {
    this.setState({details : res.data.data.results,
                    comics : res.data.data.results.results[6].items});
})
}
render() {

     (

)
}
}

I can access to my state details but not the comics one.

Body:
items being present in comics is not the 6th item in the result array but the 6th item in the first object of the result array and hence you need to access it like.

res.data.data.results[0].comics.items

Change you componentDidMount function to

componentDidMount() {
    axios.get(infoUrl).then((res) => {
    this.setState({details : res.data.data.results,
                    comics : res.data.data.results[0].items});
    })
}


问:
Access variable in main thread from second thread
I have a function (messageArrived) that call's a function (setAnimation) inside a new thread. How can i access a boolean that is defined inside the messageArrived function and access it in the second thread?

If there is a new message i want to terminate the second thread (setAnimation). I fugured that whit a boolean is the only way to "terminate" a thread.

```<code>#include <thread>

bool start = false;

void setAnimation(std::string msg){
    start = true;
    while(start){
       //do something
    }
    return;
}

int messageArrived(std::string message){
     start = false;
     std::thread t1(setAnimation, message);
     t1.detach();
     return 1;
}
</code>```

Above code is just an example to clarify my question.

答:
When creating your thread, you can pass a variable by reference using std::ref However, you would still need to have your variable outside the function, else it will get out of scope.

```<code>std::thread t1(setAnimation, message, std::ref(myVariable));
</code>```

Body:
I have a function (messageArrived) that call's a function (setAnimation) inside a new thread. How can i access a boolean that is defined inside the messageArrived function and access it in the second thread?

If there is a new message i want to terminate the second thread (setAnimation). I fugured that whit a boolean is the only way to "terminate" a thread.

#include <thread>

bool start = false;

void setAnimation(std::string msg){
    start = true;
    while(start){
       //do something
    }
    return;
}

int messageArrived(std::string message){
     start = false;
     std::thread t1(setAnimation, message);
     t1.detach();
     return 1;
}

Above code is just an example to clarify my question.

Body:
When creating your thread, you can pass a variable by reference using std::ref However, you would still need to have your variable outside the function, else it will get out of scope.

std::thread t1(setAnimation, message, std::ref(myVariable));


问:
Creating objects dynamically using a list of Strings?
I am trying to create objects by using a list of Strings that will populate their fields. For example I have the list of strings, Note that the values repeat after every 3. i.e. id, name , address.

```<code>List<String> myList = "Id1", "name1", "address1", "Id2", "name2", "address2";
</code>```

I would like to dynamically create a number of Person Objects (shown below) using this list

```<code>Person object:

public class Person {

    private String id;
    private String name;
    private String address;

     public Person() {
    }

    public Person(String id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    //standard getters and setters

}
</code>```

What I want to do is have a method that will take the list of strings as an input and then create the objects dynamically. How could I best do this?

I know that I could do the following if I knew that I was definitely populating 2 objects, but the problem is that there may be more or less.

```<code>public List<Person> createObjectsFromStringList(List<String> list){

    List<person> personList = new Arraylist<>();

    Person person1 = new Person(list.get(0), list.get(1), list.get(2));
    Person person2 = new Person(list.get(3), list.get(4), list.get(5));

    personList.add(person1);
    personList.add(person2);

    return personList;

}
</code>```

答:
If you use java 8 you can try something like this:</p>

```<code>  public List<Person> createObjectsFromStringList(List<String> list) {
      //partition by 3 and list.size.
    Map<Integer,List<Integer>> map = IntStream
            .range(0,list.size())
            .boxed()
            .collect(Collectors.groupingBy(e->(e)/3));

    List<Person> personList = new ArrayList<>();

    map.entrySet().forEach(e->{
        List<String> per= e.getValue();
        Person p = new Person(per.get(0),per.get(1),per.get(2));
        personList.add(p);
    });
    return personList;
}
</code>```

Body:
I am trying to create objects by using a list of Strings that will populate their fields. For example I have the list of strings, Note that the values repeat after every 3. i.e. id, name , address.

List<String> myList = "Id1", "name1", "address1", "Id2", "name2", "address2";

I would like to dynamically create a number of Person Objects (shown below) using this list

Person object:

public class Person {

    private String id;
    private String name;
    private String address;

     public Person() {
    }

    public Person(String id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    //standard getters and setters

}

What I want to do is have a method that will take the list of strings as an input and then create the objects dynamically. How could I best do this?

I know that I could do the following if I knew that I was definitely populating 2 objects, but the problem is that there may be more or less.

public List<Person> createObjectsFromStringList(List<String> list){

    List<person> personList = new Arraylist<>();

    Person person1 = new Person(list.get(0), list.get(1), list.get(2));
    Person person2 = new Person(list.get(3), list.get(4), list.get(5));

    personList.add(person1);
    personList.add(person2);

    return personList;

}

Body:
If you use java 8 you can try something like this:

  public List<Person> createObjectsFromStringList(List<String> list) {
      //partition by 3 and list.size.
    Map<Integer,List<Integer>> map = IntStream
            .range(0,list.size())
            .boxed()
            .collect(Collectors.groupingBy(e->(e)/3));

    List<Person> personList = new ArrayList<>();

    map.entrySet().forEach(e->{
        List<String> per= e.getValue();
        Person p = new Person(per.get(0),per.get(1),per.get(2));
        personList.add(p);
    });
    return personList;
}


问:
How to render summary of data item in multiple data.frame?
I intend to render summary data (number of data item in each group) after applying custom threshold value against pos.score. However, I intend to use dplyr functions and pipe operator to make this happen. I looked into SO to accomplish my goal, whereas using summarize functions is suggested. However, I use my own attempt to solve my problem, but can't reach my solution yet. Can anyone point me how to make this happen by using dplyr functions or base R ? Any way to make this happen easily? Any idea?

Here is minimal reproducible data:

```<code>Qualified <- list(
        hotan = data.frame( begin=seq(1, by=6, len=45), end=seq(4, by=6, len=45), pos.score=sample(125, 45)),
        aksu = data.frame( begin=seq(3, by=9, len=36), end=seq(6, by=9, len=36), pos.score=sample(84, 36)),
        korla = data.frame( begin=seq(6, by=8, len=52), end=seq(11, by=8, len=52), pos.score=sample(172, 52))
    )
</code>```

Here is my possible attempt by using dplyr, but can't work:

```<code>bind_rows(Qualified, .id = "id") %>%
    mutate(stringency = ifelse(pos.score >= 23,
                               "Stringent", "Weak")) %>% summarise()
</code>```

In my desired solution, number of data item in each group can be reported nicely. Can anyone give me possible idea? Thanks in advance :)

答:
If you want counts by group, you need to use group_by and then tell summarize what summary information you want on the group (in your case, n()).

```<code>bind_rows(Qualified, .id = "id") %>%
  mutate(stringency = ifelse(pos.score >= 23,
                             "Stringent", "Weak")) %>%
  group_by(id, stringency) %>%
  summarize(n = n())

 #    id stringency     n
 #  aksu  Stringent    25
 #  aksu       Weak    11
 # hotan  Stringent    38
 # hotan       Weak     7
 # korla  Stringent    50
 # korla       Weak     2
</code>```

If you want an actual contingency table, you could assign your mutated data and call table

```<code>df <- bind_rows(Qualified, .id = "id") %>%
  mutate(stringency = ifelse(pos.score >= 23,
                             "Stringent", "Weak"))

table(df$id, df$stringency)

#       Stringent Weak
# aksu         25   11
# hotan        38    7
# korla        50    2
</code>```

Body:
I intend to render summary data (number of data item in each group) after applying custom threshold value against pos.score. However, I intend to use dplyr functions and pipe operator to make this happen. I looked into SO to accomplish my goal, whereas using summarize functions is suggested. However, I use my own attempt to solve my problem, but can't reach my solution yet. Can anyone point me how to make this happen by using dplyr functions or base R ? Any way to make this happen easily? Any idea?

Here is minimal reproducible data:

Qualified <- list(
        hotan = data.frame( begin=seq(1, by=6, len=45), end=seq(4, by=6, len=45), pos.score=sample(125, 45)),
        aksu = data.frame( begin=seq(3, by=9, len=36), end=seq(6, by=9, len=36), pos.score=sample(84, 36)),
        korla = data.frame( begin=seq(6, by=8, len=52), end=seq(11, by=8, len=52), pos.score=sample(172, 52))
    )

Here is my possible attempt by using dplyr, but can't work:

bind_rows(Qualified, .id = "id") %>%
    mutate(stringency = ifelse(pos.score >= 23,
                               "Stringent", "Weak")) %>% summarise()

In my desired solution, number of data item in each group can be reported nicely. Can anyone give me possible idea? Thanks in advance :)

Body:
If you want counts by group, you need to use group_by and then tell summarize what summary information you want on the group (in your case, n()).

bind_rows(Qualified, .id = "id") %>%
  mutate(stringency = ifelse(pos.score >= 23,
                             "Stringent", "Weak")) %>%
  group_by(id, stringency) %>%
  summarize(n = n())

 #    id stringency     n
 #  aksu  Stringent    25
 #  aksu       Weak    11
 # hotan  Stringent    38
 # hotan       Weak     7
 # korla  Stringent    50
 # korla       Weak     2

If you want an actual contingency table, you could assign your mutated data and call table

df <- bind_rows(Qualified, .id = "id") %>%
  mutate(stringency = ifelse(pos.score >= 23,
                             "Stringent", "Weak"))

table(df$id, df$stringency)

#       Stringent Weak
# aksu         25   11
# hotan        38    7
# korla        50    2


问:
ViewGroupOverlay doesn't show view
I'm currently trying to create a puzzle game where I have a grid and each cell should be able to show a visual (and only visual) indication on touch. Therefore, I intent to use the ViewGroupOverlay (with getOverlay()) with a custom view:

In each CellView

```<code> @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View myView = inflater.inflate(R.layout.overlay, null);
            gridView.getOverlay().add(myView);
        }
        if(event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
            gridView.getOverlay().clear();
        }
        return super.onTouchEvent(event);
    }
</code>```

where 'gridView' is the parent (a FrameLayout containing a GridLayout that holds the multiple CellViews (which are RelativeLayout)) ;). But I think that doesn't really matters...

And currently for the overview.xml (Just dummy code)

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#dddd090d">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Test" />

</LinearLayout>
</code>```

Sadly, the overlay view doesn't appear anywhere.

However, if I try it with a drawable and the following code in 'onTouchEvent', it works... But I would need the view and not the drawable to work...

```<code>Drawable myIcon = getResources().getDrawable(R.drawable.overlay);
myIcon.setBounds(0,0,100,100);
gridView.getOverlay().add(myIcon);
</code>```

In general, the Overlay-technique added in API18 seems to be never used. Any experts here?

答:
ViewGroupOverlay doesn't perform the layout pass on Views added to it; that is, as is automatically performed when adding a View to an existing layout, you need to manually perform measure() and layout() on a view in order for it to be correctly displayed on screen.

The reason your code works with the Drawable is because you are performing the layout step with myIcon.setBounds(0,0,100,100);

If you use this code you will get the same effect as your Drawable:

```<code>    View view = inflater.inflate(R.layout.overlay, null);
    view.measure(View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY));
    view.layout(0, 0, 100, 100);
    gridView.getOverlay().add(view);
</code>```

You can read more about measure/layout here: https://developer.android.com/guide/topics/ui/how-android-draws.html

You can use this helper method to display a view as if it has been added to an empty full screen:

```<code>private static void measureAndLayout(Activity activity, View toMeasure, int statusBarHeight) {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

    toMeasure.measure(
            View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, View.MeasureSpec.EXACTLY) ,
            View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels - statusBarHeight, View.MeasureSpec.EXACTLY));

    toMeasure.layout(0, statusBarHeight, displayMetrics.widthPixels, displayMetrics.heightPixels);
}
</code>```

Title: ViewGroupOverlay doesn't show view

Body:
I'm currently trying to create a puzzle game where I have a grid and each cell should be able to show a visual (and only visual) indication on touch. Therefore, I intent to use the ViewGroupOverlay (with getOverlay()) with a custom view:

In each CellView

 @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View myView = inflater.inflate(R.layout.overlay, null);
            gridView.getOverlay().add(myView);
        }
        if(event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
            gridView.getOverlay().clear();
        }
        return super.onTouchEvent(event);
    }

where 'gridView' is the parent (a FrameLayout containing a GridLayout that holds the multiple CellViews (which are RelativeLayout)) ;). But I think that doesn't really matters...

And currently for the overview.xml (Just dummy code)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#dddd090d">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Test" />

</LinearLayout>

Sadly, the overlay view doesn't appear anywhere.

However, if I try it with a drawable and the following code in 'onTouchEvent', it works... But I would need the view and not the drawable to work...

Drawable myIcon = getResources().getDrawable(R.drawable.overlay);
myIcon.setBounds(0,0,100,100);
gridView.getOverlay().add(myIcon);

In general, the Overlay-technique added in API18 seems to be never used. Any experts here?

Body:
ViewGroupOverlay doesn't perform the layout pass on Views added to it; that is, as is automatically performed when adding a View to an existing layout, you need to manually perform measure() and layout() on a view in order for it to be correctly displayed on screen.

The reason your code works with the Drawable is because you are performing the layout step with myIcon.setBounds(0,0,100,100);

If you use this code you will get the same effect as your Drawable:

    View view = inflater.inflate(R.layout.overlay, null);
    view.measure(View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY));
    view.layout(0, 0, 100, 100);
    gridView.getOverlay().add(view);

You can read more about measure/layout here: https://developer.android.com/guide/topics/ui/how-android-draws.html

You can use this helper method to display a view as if it has been added to an empty full screen:

private static void measureAndLayout(Activity activity, View toMeasure, int statusBarHeight) {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

    toMeasure.measure(
            View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, View.MeasureSpec.EXACTLY) ,
            View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels - statusBarHeight, View.MeasureSpec.EXACTLY));

    toMeasure.layout(0, statusBarHeight, displayMetrics.widthPixels, displayMetrics.heightPixels);
}


问:
Thumbnails in the django admin panel using sorl
I am trying to have the pictures I upload in the Django admin panel to show up as thumbnails instead of the path. I have sorl installed and can make thumbnails that show up in my views.

I have found 2 snippets (http://www.djangosnippets.org/snippets/579/ and http://www.djangosnippets.org/snippets/934/) that I have tried to implement, but both attempts have failed because of the meager documentation and my as yet shallow understanding of the Django framework.

Could someone please provide a dumbed-down step-by-step guide of how I can get this to work?

Thanks!

答:
I know this is an old post, but I think I may have found a shorter way than the admin template override method above (though that is a pretty awesome solution - I'll have to use it in another circumstance).  This simply does a call directly to the sorl function to generate the thumbnail.

In myapp/admin.py

```<code>from myapp import models
from sorl.thumbnail import default
ADMIN_THUMBS_SIZE = '60x60'

class MyModelAdmin(admin.ModelAdmin):
    model = models.MyModel
    list_display = ['my_image_thumb', 'my_other_field1', 'my_other_field2', ]

    def my_image_thumb(self, obj):
        if obj.image:
            thumb = default.backend.get_thumbnail(obj.image.file, ADMIN_THUMBS_SIZE)
            return u'<img width="%s" src="%s" />' % (thumb.width, thumb.url)
        else:
            return "No Image"
    my_image_thumb.short_description = 'My Thumbnail'
    my_image_thumb.allow_tags = True
</code>```

I based this off of the following question but added the sorl functionality.

Django admin and showing thumbnail images

Body:
I know this is an old post, but I think I may have found a shorter way than the admin template override method above (though that is a pretty awesome solution - I'll have to use it in another circumstance).  This simply does a call directly to the sorl function to generate the thumbnail.

In myapp/admin.py

from myapp import models
from sorl.thumbnail import default
ADMIN_THUMBS_SIZE = '60x60'

class MyModelAdmin(admin.ModelAdmin):
    model = models.MyModel
    list_display = ['my_image_thumb', 'my_other_field1', 'my_other_field2', ]

    def my_image_thumb(self, obj):
        if obj.image:
            thumb = default.backend.get_thumbnail(obj.image.file, ADMIN_THUMBS_SIZE)
            return u'<img width="%s" src="%s" />' % (thumb.width, thumb.url)
        else:
            return "No Image"
    my_image_thumb.short_description = 'My Thumbnail'
    my_image_thumb.allow_tags = True

I based this off of the following question but added the sorl functionality.

Django admin and showing thumbnail images


问:
How can I run jbehave tests with different parameters
I have a running test project with jbehave which tests a software on an other machine.

So my problem is, I would like to run the same stories for the same software on an other machines.

When I summarize, the web application I'm testing is installed on 20 different hosts and I would like to run the tests for every instance.

The tests are simple smoke-test, where I daily check some installation, application and database issues.

The test project was configured for one instance and works properly, so I want to extend it for n instances.

Can I parameterize the Testrunner oder something like this? Or can I call the tests many time with different parameters?

I'm little bit confused

答:
you could use parameterized scenario to run the same tests with different parameters

see: http://jbehave.org/reference/stable/parametrised-scenarios.html


问:
Angular 2: ReferenceError: require is not defined(…), angular2-polyfills

Edit:

I haven't figure out exactly why it didn't work, but I started from scratch and got a working version. It does not appear necessary to put system.src.js before the angular script tags, pace one of the answers below. See both the working version and the Angular 2 tutorial.

Original question:

I am trying to learn Angular 2 and Express. I am generally following this guide. I am receiving the following error:

```<code>ReferenceError: require is not defined(…) angular2-polyfills.js:1243
Zone.run @ angular2-polyfills.js:1243
zoneBoundFn @ angular2-polyfills.js:1220
lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:468
lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:480
lib$es6$promise$$internal$$publish @ angular2-polyfills.js:451
lib$es6$promise$$internal$$publishRejection @ angular2-polyfills.js:401
(anonymous function) @ angular2-polyfills.js:123
Zone.run @ angular2-polyfills.js:1243
zoneBoundFn @ angular2-polyfills.js:1220
lib$es6$promise$asap$$flush @ angular2-polyfills.js:262
</code>```

Edit: here is the broken version of the project on GitHub.

My project is structured like so:

```<code>application
|__client
   |__app
      |__main.ts
      |__main.js
      |__tsconfig.json
   |__typings/ (...)
   |__index.html
   |__typings.json
|__server
   |__server.ts
   |__server.js
   |__tsconfig.json
   |__typings.json
|__node_modules/ (...)
</code>```

The file server.ts is like this:

```<code>import * as express from "express";
let path = require("path");

let app = express();

let PORT = 8080;

app.use("/node_modules", express.static(__dirname + "/../node_modules"));
app.use("/app", express.static(__dirname + "/../client/app"));

app.get("/", (req, res) => {
  res.sendFile(path.resolve(__dirname, "..", "client", "index.html"));
});

app.listen(PORT, () => { console.log("Listening on port " + PORT)});
</code>```

The main.ts file is like this:

```<code>import {Component} from "angular2/core";
import {bootstrap} from "angular2/platform/browser";

@Component({
  selector: "app",
  template: "<h1>Hello world</h1>"
})
export class AppComponent {}

bootstrap(AppComponent);
</code>```

The index.html file is like this:

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

<head>
  <meta charset="utf-8">
  <title></title>

  <script src="node_modules/systemjs/dist/system.src.js"></script>
  <script src="node_modules/es6-shim/es6-shim.min.js"></script>
  <script src="node_modules/systemjs/dist/system-polyfills.js"></script>

  <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
  <!-- <script src="node_modules/systemjs/dist/system.src.js"></script> -->
  <script src="node_modules/rxjs/bundles/Rx.js"></script>
  <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
  <script>
    System.config({
      packages: {
        app: {
          format: "register",
          defaultExtension: "js"
        }
      }
    });
    System.import("app/main")
      .then(null, console.error.bind(console));
  </script>
</head>

<body>
  <app></app>
</body>

</html>
</code>```

And the tsconfig.json files are both pretty much like this:

```<code>{
    "compilerOptions": {
        "target": "es5",
        "module": "system",
        "moduleResolution": "node",
        "isolatedModules": false,
        "jsx": "react",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "declaration": false,
        "noImplicitAny": true,
        "removeComments": false,
        "noLib": false,
        "preserveConstEnums": true,
        "suppressImplicitAnyIndexErrors": true
    },
    "exclude": [
        "node_modules",
        "typings/browser",
        "typings/browser.d.ts"
    ],
    "compileOnSave": true,
    "buildOnSave": false,
    "atom": {
        "rewriteTsconfig": false
    }
}
</code>```

Thanks.

答:
I just started with angular 4 today (upgraded from angular2).

Just before my injectable auth class, I added this:

```<code>// declare var Auth0Lock: any;
declare let require: any;
let Auth0Lock = require('auth0-lock').default;
</code>```

Body:
Edit:

I haven't figure out exactly why it didn't work, but I started from scratch and got a working version. It does not appear necessary to put system.src.js before the angular script tags, pace one of the answers below. See both the working version and the Angular 2 tutorial.

Original question:

I am trying to learn Angular 2 and Express. I am generally following this guide. I am receiving the following error:

ReferenceError: require is not defined(…) angular2-polyfills.js:1243
Zone.run @ angular2-polyfills.js:1243
zoneBoundFn @ angular2-polyfills.js:1220
lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:468
lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:480
lib$es6$promise$$internal$$publish @ angular2-polyfills.js:451
lib$es6$promise$$internal$$publishRejection @ angular2-polyfills.js:401
(anonymous function) @ angular2-polyfills.js:123
Zone.run @ angular2-polyfills.js:1243
zoneBoundFn @ angular2-polyfills.js:1220
lib$es6$promise$asap$$flush @ angular2-polyfills.js:262

Edit: here is the broken version of the project on GitHub.

My project is structured like so:

application
|__client
   |__app
      |__main.ts
      |__main.js
      |__tsconfig.json
   |__typings/ (...)
   |__index.html
   |__typings.json
|__server
   |__server.ts
   |__server.js
   |__tsconfig.json
   |__typings.json
|__node_modules/ (...)

The file server.ts is like this:

import * as express from "express";
let path = require("path");

let app = express();

let PORT = 8080;

app.use("/node_modules", express.static(__dirname + "/../node_modules"));
app.use("/app", express.static(__dirname + "/../client/app"));

app.get("/", (req, res) => {
  res.sendFile(path.resolve(__dirname, "..", "client", "index.html"));
});

app.listen(PORT, () => { console.log("Listening on port " + PORT)});

The main.ts file is like this:

import {Component} from "angular2/core";
import {bootstrap} from "angular2/platform/browser";

@Component({
  selector: "app",
  template: "
Hello world
"
})
export class AppComponent {}

bootstrap(AppComponent);

The index.html file is like this:

<!DOCTYPE html>

  <meta charset="utf-8">
  <title></title>

  <app></app>

And the tsconfig.json files are both pretty much like this:

{
    "compilerOptions": {
        "target": "es5",
        "module": "system",
        "moduleResolution": "node",
        "isolatedModules": false,
        "jsx": "react",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "declaration": false,
        "noImplicitAny": true,
        "removeComments": false,
        "noLib": false,
        "preserveConstEnums": true,
        "suppressImplicitAnyIndexErrors": true
    },
    "exclude": [
        "node_modules",
        "typings/browser",
        "typings/browser.d.ts"
    ],
    "compileOnSave": true,
    "buildOnSave": false,
    "atom": {
        "rewriteTsconfig": false
    }
}

Thanks.

Body:
I just started with angular 4 today (upgraded from angular2).

Just before my injectable auth class, I added this:

// declare var Auth0Lock: any;
declare let require: any;
let Auth0Lock = require('auth0-lock').default;


问:
Calling sourcefragment's onactivity result when hardware back pressed in target fragment android
I'm trying to call the source fragment onActivityResult() from the target fragment when hardware back button pressed and struck with the below code when used inside the target fragment class. Getting NPE in the code mentioned below.

Please share some suggestion.

```<code>// target fragment
public void backButtonWasPressed() {
    Intent intent = new Intent();
    // NPE occurs in the below line
    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);
    getActivity().getSupportFragmentManager().popBackStack();
}

// main activity
@Override
public void onBackPressed() {
    if (sourceFragment != null) {
            TargetFragment fragment = new TargetFragment();
            fragment.backButtonWasPressed();
    } else {
            super.onBackPressed();
            return;
    }
}
</code>```

答:
getTargetFragment() is a non-static method of Fragment. See here. You need to get a reference to an instantiation of the fragment from which you are returning. The easiest way may be to pass the fragment as an argument, i.e.,

```<code>public static void backButtonWasPressed(Fragment frag)
</code>```

then call

```<code>frag.getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);
</code>```

Body:
I'm trying to call the source fragment onActivityResult() from the target fragment when hardware back button pressed and struck with the below code when used inside the target fragment class. Getting NPE in the code mentioned below.

Please share some suggestion.

// target fragment
public void backButtonWasPressed() {
    Intent intent = new Intent();
    // NPE occurs in the below line
    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);
    getActivity().getSupportFragmentManager().popBackStack();
}

// main activity
@Override
public void onBackPressed() {
    if (sourceFragment != null) {
            TargetFragment fragment = new TargetFragment();
            fragment.backButtonWasPressed();
    } else {
            super.onBackPressed();
            return;
    }
}

Body:
getTargetFragment() is a non-static method of Fragment. See here. You need to get a reference to an instantiation of the fragment from which you are returning. The easiest way may be to pass the fragment as an argument, i.e.,

public static void backButtonWasPressed(Fragment frag)

then call

frag.getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);


问:
Combine two formula in one cell using SumIF and IF functions?
This is the code I'm using</p>

```<code>=SUMIF(OR(Entries!$A:$A,F$5&$B6,Entries!I:I)),IF(F6=0,"-")
</code>```

答:
I think you are misunderstanding how the SUMIF() function works. Per the Microsoft Excel Help Database: syntax is SUMIF(range, criteria, (optional sum range)). If you want to sum everything in your listed ranges that doesn't equal zero, you could write:

```<code>    =SUMIF(NAMED_RANGE,"<>0")
</code>```

You will want to select the range you want to SUM and then name it. See this Microsoft Office Help Page. Your formula is not working because you are missing the last parenthesis and you cannot put an IF() function instead of the required conditional statement.

If this is still confusing, you can always just create an array formula using both SUM() and IF() functions.

```<code>    =SUM(IF(NAMED_RANGE<>0,SUM_RANGE,0))
</code>```

You will need to press CTRL+SHIFT+ENTER after writing this formula or it will not work.

OR you could just SUM() everything normally, since zeros don't add anything to the sum. You're adding a lot of work to just not add zeros.

Body:
This is the code I'm using

=SUMIF(OR(Entries!$A:$A,F$5&$B6,Entries!I:I)),IF(F6=0,"-")

Body:
I think you are misunderstanding how the SUMIF() function works. Per the Microsoft Excel Help Database: syntax is SUMIF(range, criteria, (optional sum range)). If you want to sum everything in your listed ranges that doesn't equal zero, you could write:

    =SUMIF(NAMED_RANGE,"<>0")

You will want to select the range you want to SUM and then name it. See this Microsoft Office Help Page. Your formula is not working because you are missing the last parenthesis and you cannot put an IF() function instead of the required conditional statement.

If this is still confusing, you can always just create an array formula using both SUM() and IF() functions.

    =SUM(IF(NAMED_RANGE<>0,SUM_RANGE,0))

You will need to press CTRL+SHIFT+ENTER after writing this formula or it will not work.

OR you could just SUM() everything normally, since zeros don't add anything to the sum. You're adding a lot of work to just not add zeros.


问:
SpringBoot - Deactivate security completely to enable digest forwarding
We are building an app based on SpringBoot that shall work like a proxy. It accepts requests and sends them to another endpoint. This includes the digest authentication.

Client --> Proxy (Spring) --> Resource

The client and resource use digest authentication, which works fine without the proxy.

How can I completely disable any security, but especially springs default handling of digest authentication, to plainly forward the request (no need to discuss potential security issues, this is intended).

We tried .authorizeRequests().antMatchers("/**").permitAll(), security.ignored=/**, management.security.enabled=false and

```<code>@EnableAutoConfiguration(exclude = {
    org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class})
</code>```

I tested that digest forwarding is technically on a NodeJS/Express stack.

答:
You have to ignore any request. Also, you have to remove, if exists, the servlet's filters over digest.</p>

```<code>@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/**");
}
</code>```

Body:
We are building an app based on SpringBoot that shall work like a proxy. It accepts requests and sends them to another endpoint. This includes the digest authentication.

Client --> Proxy (Spring) --> Resource

The client and resource use digest authentication, which works fine without the proxy.

How can I completely disable any security, but especially springs default handling of digest authentication, to plainly forward the request (no need to discuss potential security issues, this is intended).

We tried .authorizeRequests().antMatchers("/**").permitAll(), security.ignored=/**, management.security.enabled=false and

@EnableAutoConfiguration(exclude = {
    org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class})

I tested that digest forwarding is technically on a NodeJS/Express stack.

Body:
You have to ignore any request. Also, you have to remove, if exists, the servlet's filters over digest.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/**");
}


问:
extract only one part from xpath scrapy
I want to extract from a web page information with xpath, but I'm getting the wrong information. In this code below I want to get 100 :

```<code><div class="pricing">
 <p class="pricePerUnit">
  <p class="pricePerMeasure">
  £0.64
  <abbr title="per">/</abbr>
  100
</code>```

I want to only get 100, I tried this but it returns £0.64 100.  But,  I just want to retrieve the 100 :

```<code>`prices_mesure3 = `response.xpath('//p[@class="pricePerMeasure"]/text()').extract()`
</code>```

Any help please ?

答:
Couldn't you just split the result and then take the last element?</p>

```<code>prices_mesure3 = response.xpath('//p[@class="pricePerMeasure"]/text()').extract()[0].split()[-1]
</code>```

Title: extract only one part from xpath scrapy

Body:
I want to extract from a web page information with xpath, but I'm getting the wrong information. In this code below I want to get 100 :

  £0.64
  /
  100

I want to only get 100, I tried this but it returns £0.64 100.  But,  I just want to retrieve the 100 :

`prices_mesure3 = `response.xpath('//p[@class="pricePerMeasure"]/text()').extract()`

Any help please ?

Body:
Couldn't you just split the result and then take the last element?

prices_mesure3 = response.xpath('//p[@class="pricePerMeasure"]/text()').extract()[0].split()[-1]


问:
How to animate svg path on reaching certain point in page?
I want to replicate the effect in : Animating svg path but I want the svg's furthur down the page and when the user scrolls to that section the effect will be triggered and not on click of any link. On scrolling back up it will again morph back. I think it can be done using GSAP but till now I am not able to get it to work. And also if anyone can explain what's going on with :

```<code>[].forEach.call(links, function (el, i, els) {
el.addEventListener("click", function (event) {
    var animateTo = this.getAttribute("href").substring(1);

    [].forEach.call(els, function (el) {
        if (el !== this) {
            el.classList.remove("active");
        } else {
            this.classList.add("active");
        }
    }, this);

    event.preventDefault();
    this.classList.add("active");
    getPaths(animateTo);
});
});
</code>```

I don't understand what is the (el, i, els) passed as the function parameter. I would appreciate any help :)

答: You are looking for this. scrollmagic</p>

Body:
I want to replicate the effect in : Animating svg path but I want the svg's furthur down the page and when the user scrolls to that section the effect will be triggered and not on click of any link. On scrolling back up it will again morph back. I think it can be done using GSAP but till now I am not able to get it to work. And also if anyone can explain what's going on with :

[].forEach.call(links, function (el, i, els) {
el.addEventListener("click", function (event) {
    var animateTo = this.getAttribute("href").substring(1);

    [].forEach.call(els, function (el) {
        if (el !== this) {
            el.classList.remove("active");
        } else {
            this.classList.add("active");
        }
    }, this);

    event.preventDefault();
    this.classList.add("active");
    getPaths(animateTo);
});
});

I don't understand what is the (el, i, els) passed as the function parameter. I would appreciate any help :)

Body: You are looking for this. scrollmagic


问:
Why i cant see this image button on IE8 with this CSS?
So, this is the html code for the button

```<code><input type="submit" name="logueo" value="log" id="sendbu"/>
</code>```

And this is the css style

```<code>#sendbu     { width: 50px; height: 34px; font-family: Verdana, Geneva, Tahoma, sans-serif; font-size: 12px; background: transparent url(lock.png) no-repeat center top; border: 0;   text-indent: -1000em; cursor: pointer; cursor: hand; }
</code>```

All this works on Chrome and Firefox, but in IE the button seams to dont exist. Thanks for the help.

答: font-size: 0; works sometimes.  I'm sure there are sites that use negative indent that work in IE.

Body:
So, this is the html code for the button

<input type="submit" name="logueo" value="log" id="sendbu"/>

And this is the css style

#sendbu     { width: 50px; height: 34px; font-family: Verdana, Geneva, Tahoma, sans-serif; font-size: 12px; background: transparent url(lock.png) no-repeat center top; border: 0;   text-indent: -1000em; cursor: pointer; cursor: hand; }

All this works on Chrome and Firefox, but in IE the button seams to dont exist. Thanks for the help.


问:
Python 2.7 passing variable into subprocess command line
I want to use a variable and pass it on to shell command line. Problem is. I don't know how. Need help.

```<code> def gauti():
    imti=tekstas.get("1.0", "end-1c")
    subprocess.call("grep -i 'imti' /var/log/syslog > logas.txt", shell=True)
</code>```

Instead of 'imti' I need a variable that would be delivered in python program to be searched in syslog file.

答:
Use string formatting

```<code>subprocess.call("grep -i '{imti}' /var/log/syslog > logas.txt".format(imti=imti),
                shell=True)
</code>```

or pass array to call method with all required parts

```<code>logas = open('logas.txt', 'a+')
subprocess.call(['grep', '-i', imti, '/var/log/syslog'], stdout=logas)
</code>```

Body:
I want to use a variable and pass it on to shell command line. Problem is. I don't know how. Need help.

 def gauti():
    imti=tekstas.get("1.0", "end-1c")
    subprocess.call("grep -i 'imti' /var/log/syslog > logas.txt", shell=True)

Instead of 'imti' I need a variable that would be delivered in python program to be searched in syslog file.

Body:
Use string formatting

subprocess.call("grep -i '{imti}' /var/log/syslog > logas.txt".format(imti=imti),
                shell=True)

or pass array to call method with all required parts

logas = open('logas.txt', 'a+')
subprocess.call(['grep', '-i', imti, '/var/log/syslog'], stdout=logas)


问:
Script to watch for file changes & if detected, backup the original first.
As per the title I'm looking for a way to backup files (SQL queries to be specific) when they are saved over/replaced.

This is to prevent accidental saving without a decent fall back.

I think that using a combination of Powershell and .NET FileSystemWatcher might be a good combo and instead of an alert I could take the original and append datetime to it in another location.

(https://gallery.technet.microsoft.com/scriptcenter/Powershell-FileSystemWatche-dfd7084b)

So my question is, how to interrupt that save process within Windows and copy the file out before it's saved over?

I'm thinking it might not be possible without calling the PS when a save is initiated on that specific directory.

I have access to PS, VBS and elevated cmd.

TIA for any pointers or further reading.

答:
There's no way to backup/save the previous before a newer version overwrites it as there are no OnBeforeX events in the FileSystemWatcher.

Changed: Occurs when a file or directory in the specified Path is changed.

Created: Occurs when a file or directory in the specified Path is created.

Deleted: Occurs when a file or directory in the specified Path is deleted.

Disposed: Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)

Error: Occurs when the instance of FileSystemWatcher is unable to continue monitoring changes or when the internal buffer overflows.

Renamed: Occurs when a file or directory in the specified Path is renamed.

The only way to do this would be to perform an initial back up of all the files. Then backup, with a timestamp pre/suffix, after each Changed event.


问:
How to make nested Div wrap instead of overlap?
I'm using Bootstrap's grid system. I have 3 divs inside a "row", and inside each of those divs are nested controls.

When I horizontally decrease the browser size, the 2nd and 3rd div in the row are overlapping the 1st div. I want them to wrap, not overlap.

How can I achieve this?

Here is my code:

      <select style="min-width: 215px; max-width: 300px;" class="col-xs-4 form-control" data-bind="value: selectedSAPIValue, options: saorpi, optionsText: 'Name', optionsValue: 'CmeTypeId', optionsCaption: 'Select SA or PI'"></select>

      <select style="max-width: 300px;" class="specialties-class form-control" name="Name" id="SpecialtyId"></select>

      <button id="btnDropDownsSearch" class="btn btn-search collapsed" type="button">

       </button>

    OR

    Activity Search

      <input id="txtFreeformSearch" class="form-control" type="search" style="min-width:175px;" />

        <button id="btnFreeformSearch" class="btn btn-search collapsed" type="button">

        </button>

```

答:
When you say, you nesting controls to div; Do you mean somethink like this?

.row > div {
    background: lightgrey;
    border: 1px solid grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
    <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">.col-md-4</div>
    <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">.col-md-4</div>
    <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">.col-md-4</div>
</div>
<div class="row">
    <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">.col-md-4</div>
    <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">.col-md-4</div>
    <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">.col-md-4</div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
When you say, you nesting controls to div; Do you mean somethink like this?

.row > div {
    background: lightgrey;
    border: 1px solid grey;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
    <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">.col-md-4</div>
    <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">.col-md-4</div>
    <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">.col-md-4</div>
</div>
<div class="row">
    <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">.col-md-4</div>
    <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">.col-md-4</div>
    <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">.col-md-4</div>
</div>


问:
Select parsed int, if string was parseable to int
So I have an IEnumerable<string> which can contain values that can be parsed as int, as well as values that cannot be.

As you know, Int32.Parse throws an exception if a string cannot be changed to an int, while Int32.TryParse can be used to check and see if the conversion was possible without dealing with the exception.

So I want to use a LINQ query to one-liner parse those strings which can be parsed as int, without throwing an exception along the way. I have a solution, but would like advice from the community about whether this is the best approach.

Here's what I have:

```<code>int asInt = 0;
var ints = from str in strings
           where Int32.TryParse(str, out asInt)
           select Int32.Parse(str);
</code>```

So as you can see, I'm using asInt as a scratch space for the call to TryParse, just to determine if TryParse would succeed (return bool). Then, in the projection, I'm actually performing the parse. That feels ugly.

Is this the best way to filter the parseable values in one-line using LINQ?

答:
Inspired by Carl Walsh's answer, I took it one step further to allow parsing of properties:

```<code>public static IEnumerable<TResult> SelectTry<TSource, TValue, TResult>(
     this IEnumerable<TSource> source,
     Func<TSource, TValue> selector,
     TryFunc<TValue, TResult> executor)
{
    foreach (TSource s in source)
    {
        TResult r;
        if (executor(selector(s), out r))
            yield return r;
    }
}
</code>```

Here's an example which also can be found in this fiddle:

```<code>public class Program
{
    public static void Main()
    {
        IEnumerable<MyClass> myClassItems = new List<MyClass>() {new MyClass("1"), new MyClass("2"), new MyClass("InvalidValue"), new MyClass("3")};

        foreach (int integer in myClassItems.SelectTry<MyClass, string, int>(x => x.MyIntegerAsString, int.TryParse))
        {
            Console.WriteLine(integer);
        }
    }
}

public static class LinqUtilities
{
    public delegate bool TryFunc<in TSource, TResult>(TSource arg, out TResult result);

    public static IEnumerable<TResult> SelectTry<TSource, TValue, TResult>(
        this IEnumerable<TSource> source,
        Func<TSource, TValue> selector,
        TryFunc<TValue, TResult> executor)
    {
        foreach (TSource s in source)
        {
            TResult r;
            if (executor(selector(s), out r))
                yield return r;
        }
    }
}

public class MyClass
{
    public MyClass(string integerAsString)
    {
        this.MyIntegerAsString = integerAsString;
    }

     public string MyIntegerAsString{get;set;}
}
</code>```

Output of this program:

1

2

3

Body:
So I have an IEnumerable<string> which can contain values that can be parsed as int, as well as values that cannot be.

As you know, Int32.Parse throws an exception if a string cannot be changed to an int, while Int32.TryParse can be used to check and see if the conversion was possible without dealing with the exception.

So I want to use a LINQ query to one-liner parse those strings which can be parsed as int, without throwing an exception along the way. I have a solution, but would like advice from the community about whether this is the best approach.

Here's what I have:

int asInt = 0;
var ints = from str in strings
           where Int32.TryParse(str, out asInt)
           select Int32.Parse(str);

So as you can see, I'm using asInt as a scratch space for the call to TryParse, just to determine if TryParse would succeed (return bool). Then, in the projection, I'm actually performing the parse. That feels ugly.

Is this the best way to filter the parseable values in one-line using LINQ?

Body:
Inspired by Carl Walsh's answer, I took it one step further to allow parsing of properties:

public static IEnumerable<TResult> SelectTry<TSource, TValue, TResult>(
     this IEnumerable<TSource> source,
     Func<TSource, TValue> selector,
     TryFunc<TValue, TResult> executor)
{
    foreach (TSource s in source)
    {
        TResult r;
        if (executor(selector(s), out r))
            yield return r;
    }
}

Here's an example which also can be found in this fiddle:

public class Program
{
    public static void Main()
    {
        IEnumerable<MyClass> myClassItems = new List<MyClass>() {new MyClass("1"), new MyClass("2"), new MyClass("InvalidValue"), new MyClass("3")};

        foreach (int integer in myClassItems.SelectTry<MyClass, string, int>(x => x.MyIntegerAsString, int.TryParse))
        {
            Console.WriteLine(integer);
        }
    }
}

public static class LinqUtilities
{
    public delegate bool TryFunc<in TSource, TResult>(TSource arg, out TResult result);

    public static IEnumerable<TResult> SelectTry<TSource, TValue, TResult>(
        this IEnumerable<TSource> source,
        Func<TSource, TValue> selector,
        TryFunc<TValue, TResult> executor)
    {
        foreach (TSource s in source)
        {
            TResult r;
            if (executor(selector(s), out r))
                yield return r;
        }
    }
}

public class MyClass
{
    public MyClass(string integerAsString)
    {
        this.MyIntegerAsString = integerAsString;
    }

     public string MyIntegerAsString{get;set;}
}

Output of this program:

1

2

3


问:
WMI + Bitlocker + C# Get encrypted Volumes produces timeout
i want to create a wrapper class for specific WMI functions that affect Bitlocker functionality. The first step is to get all the Bitlocker volumes of a machine so I created a Console Application and did this:

```<code>private static ManagementClass management;
    private static ManagementObjectCollection Volumes = null;

    static void Main(string[] args)
    {

        ManagementPath path = new ManagementPath();
        path.Server = "";
        path.NamespacePath = "\\ROOT\\CIMV2\\Security\\MicrosoftVolumeEncryption";
        path.ClassName = "Win32_EncryptableVolume";

        ConnectionOptions options = new ConnectionOptions();
        options.Authentication = AuthenticationLevel.PacketPrivacy;
        options.Impersonation = ImpersonationLevel.Impersonate;

        ManagementScope scope = new ManagementScope(path, options);
        ObjectGetOptions getOptions = new ObjectGetOptions();

        management = new ManagementClass(scope, path, getOptions);
        management.Get();
        Volumes = management.GetInstances();

    }
</code>```

When I run this on a non-Bitlocker machine the Volumes Collection gets initialized OK, only that it has a Count of 0 of course. Now I copied the code over to a WinForms App and when I click a button to run this code it steps through OK but when I try to expand the collection during debugging the App hangs and I get a "Function evaluation timed out". It's the same code just in another Application. What could be the reason for this?

答:
I just had a similar issue, I will post my code for you hopefully it helps.

```<code>ManagementObjectSearcher Encryption = new ManagementObjectSearcher(@"root\cimv2\Security\MicrosoftVolumeEncryption", "SELECT * FROM Win32_EncryptableVolume");

        foreach (ManagementObject QueryObj in Encryption.Get())
        {
            string EncryptionStatus = QueryObj.GetPropertyValue("ProtectionStatus").ToString();

            if (EncryptionStatus == "0")
            {
                EncryptionDialog.Text = "Unencrypted";
            }
            else if (EncryptionStatus == "1")
            {
                EncryptionDialog.Text = "Encrypted - SysPrep will not complete";
            }
            else if (EncryptionStatus == "2")
            {
                EncryptionDialog.Text = "Cannot Determine Encryption";
            }
        }
</code>```

I'm using this to display the status for a sysprep tool i'm creating so the "EncryptionDialog.Text = ..." can be replaced with any other calls you may need. you also need to remember "which caused me issues at least" if you are using visual studio you will need to add a file to your project labeled "Application Manifest File" in the "Add New File" Dialog. The reason for this is that the application will need to be opened in Administrator mode(Just an FYI in case you haven't made it that far)

Body:
i want to create a wrapper class for specific WMI functions that affect Bitlocker functionality. The first step is to get all the Bitlocker volumes of a machine so I created a Console Application and did this:

private static ManagementClass management;
    private static ManagementObjectCollection Volumes = null;

    static void Main(string[] args)
    {

        ManagementPath path = new ManagementPath();
        path.Server = "";
        path.NamespacePath = "\\ROOT\\CIMV2\\Security\\MicrosoftVolumeEncryption";
        path.ClassName = "Win32_EncryptableVolume";

        ConnectionOptions options = new ConnectionOptions();
        options.Authentication = AuthenticationLevel.PacketPrivacy;
        options.Impersonation = ImpersonationLevel.Impersonate;

        ManagementScope scope = new ManagementScope(path, options);
        ObjectGetOptions getOptions = new ObjectGetOptions();

        management = new ManagementClass(scope, path, getOptions);
        management.Get();
        Volumes = management.GetInstances();

    }

When I run this on a non-Bitlocker machine the Volumes Collection gets initialized OK, only that it has a Count of 0 of course. Now I copied the code over to a WinForms App and when I click a button to run this code it steps through OK but when I try to expand the collection during debugging the App hangs and I get a "Function evaluation timed out". It's the same code just in another Application. What could be the reason for this?

Body:
I just had a similar issue, I will post my code for you hopefully it helps.

ManagementObjectSearcher Encryption = new ManagementObjectSearcher(@"root\cimv2\Security\MicrosoftVolumeEncryption", "SELECT * FROM Win32_EncryptableVolume");

        foreach (ManagementObject QueryObj in Encryption.Get())
        {
            string EncryptionStatus = QueryObj.GetPropertyValue("ProtectionStatus").ToString();

            if (EncryptionStatus == "0")
            {
                EncryptionDialog.Text = "Unencrypted";
            }
            else if (EncryptionStatus == "1")
            {
                EncryptionDialog.Text = "Encrypted - SysPrep will not complete";
            }
            else if (EncryptionStatus == "2")
            {
                EncryptionDialog.Text = "Cannot Determine Encryption";
            }
        }

I'm using this to display the status for a sysprep tool i'm creating so the "EncryptionDialog.Text = ..." can be replaced with any other calls you may need. you also need to remember "which caused me issues at least" if you are using visual studio you will need to add a file to your project labeled "Application Manifest File" in the "Add New File" Dialog. The reason for this is that the application will need to be opened in Administrator mode(Just an FYI in case you haven't made it that far)


问:
EF 6 with a dnx project
I have a new ASP.net 5 dnx class library I am using for entity framework.  I need to target EF 6 because some features I need are not in EF 7.

First the EF tools (like enable-migration) were not there.  I added an old style class library and installed EF 6 and now the commands are there.

When I run enable migrations I get this error:

PM> Enable-Migrations

Exception calling "SetData" with "2" argument(s): "Type
  'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject'
  in assembly  'Microsoft.VisualStudio.ProjectSystem.VS.Implementation,
  Version=14.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is
  not  marked as serializable." At
  D:\Projects\Rebus\FMS\Code\Current\FMSSupport\FMSSupport\packages\EntityFramework.6.1.3\tools\EntityFramework.psm1:720
  char:5
  +     $domain.SetData('startUpProject', $startUpProject)
  +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : SerializationException   System.NullReferenceException: Object reference not set to an instance
  of an object.    at
  System.Data.Entity.Migrations.Extensions.ProjectExtensions.GetProjectTypes(Project
  project, Int32 shellVersion)    at
  System.Data.Entity.Migrations.Extensions.ProjectExtensions.IsWebProject(Project
  project)    at
  System.Data.Entity.Migrations.MigrationsDomainCommand.GetFacade(String
  configurationTypeName, Boolean useContextWorkingDirectory)    at
  System.Data.Entity.Migrations.EnableMigrationsCommand.FindContextToEnable(String
  contextTypeName)    at
  System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
  at
  System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action
  command) Object reference not set to an instance of an object.

I have tried different options for enable-migration such as specifying a startup project or the contextTypeName.

Any ideas?

答:
I had the same issue.  Just setting the start project from ASP.NET Core to my .NET Framework Lib does the trick for me =) Now i can do EF6 migrations as usual "Add-Migration" command...

P.S. Sorry for my eng.

Title: EF 6 with a dnx project


问:
What are the best wiki engine with good authorization features?
What is the best wiki engine with good authorization features?</p>

答: We use atlassian confluence it has authorization features like restricting viewing or editing of pages for groups or users. But it's a commercial product (not free)</p>

OwnerDisplayName: LiorH


问:
jquery - find center part of image you are looking at on the screen
I am trying to add a graphic indicator on top of an image that I am looking at. I would basically put the DIV containing object with higher z-index on top of image I am looking at. The main image can be ANY SIZE.

So any ideas on how when I click "Add indicator", the indicator graphic would always be popped into view on top of the main image container (and not outside it) and viewable by me?

Another case is if image is very high (like 3000px height, it would require scrolling). So I might be viewing the bottom part of the image.

Any suggestions welcomed!

答:
well you use css absolute positioning and zindex to get it ontop? and use percent to positioning it in the center

edit:
if you showed some html I could be a little bit more helpfull

example

```<code><div style="position:relative;">
<div style="position:absolute; margin-left:50%; margin-top:50%;"></div>
<img src="image.jpg"/>
</div>
</code>```

Body:
well you use css absolute positioning and zindex to get it ontop? and use percent to positioning it in the center

edit:
if you showed some html I could be a little bit more helpfull

example

<div style="position:relative;">
<div style="position:absolute; margin-left:50%; margin-top:50%;"></div>
<img src="image.jpg"/>
</div>


问:
AttributeError: 'NoneType' object has no attribute 'replace' (python)

http://cs1.ucc.ie/~adc2/cgi-bin/lab7/index.html
You can check out the error for yourself by just inputting anything into anyone of the boxes , doesnt have to be all, any help would be great
, I will send on the code after this

```<code>from cgitb import enable
enable()

from cgi import FieldStorage,escape

print('Content-Type: text/html')
print()

actor=''

genre=''

theyear=''

director=''

mood=''

result=''

form_data= FieldStorage()
if len(form_data) != 0:

    try:
        actor=escape(form_data.getfirst('actor'))
        genre=escape(form_data.getfirst('genre'))
        theyear=escape(form_data.getfirst('theyear'))
        director=escape(form_data.getfirst('director'))
        mood= escape(form_data.getfirst('mood'))
        connection = db.connect('####', '###', '####', '###')
        cursor = connection.cursor(db.cursors.DictCursor)
        cursor.execute("""SELECT title
                          FROM films
                          WHERE (actor = '%s')
                          OR (actor='%s' AND genre='%s')
                          OR (actor='%s' AND genre='%s' AND theyear='%i')
                          OR (actor='%s' AND genre='%s' AND theyear='%i' AND director='%s')
                          OR (actor='%s' AND genre='%s' AND theyear='%i' AND director='%s' AND mood='%s') % (actor, actor,genre, actor,genre,theyear, actor,genre,theyear,director,actor,genre,theyear,director,mood))
                          """)
        result = """<table>
                    <tr><th>Your movie!</th></tr>
                    <tr><th></th></tr>"""
        for row in cursor.fetchall():
            result+= '<tr><td>%s</td></tr>' ,(row['title'])
        result+= '</table>'
        cursor.close()
        connection.close()

    except db.Error:
        result = '<p>Sorry! We are currently experiencing technical difficulties.</p>'
</code>```

答:
According to the error code:

```<code>/users/2020/adc2/public_html/cgi-bin/lab7/index.py in ()
     24     try:
     25         actor=escape(form_data.getfirst('actor'))
=>   26         genre=escape(form_data.getfirst('genre'))
     27         theyear=escape(form_data.getfirst('theyear'))
     28         director=escape(form_data.getfirst('director'))
genre = '', escape = <function escape>, form_data = FieldStorage(None, None, [MiniFieldStorage('actor', 'i')]), form_data.getfirst = <bound method FieldStorage.getfirst of FieldStorage(None, None, [MiniFieldStorage('actor', 'i')])>
 /usr/local/lib/python3.4/cgi.py in escape(s=None, quote=None)
   1038     warn("cgi.escape is deprecated, use html.escape instead",
   1039          DeprecationWarning, stacklevel=2)
=> 1040     s = s.replace("&", "&") # Must be done first!
   1041     s = s.replace("<", "<")
   1042     s = s.replace(">", ">")
s = None, s.replace undefined
</code>```

escape() seems to get None as an argument. Escape() uses replace() directly internally, according to the given code snippet.. So the quick fix would be to make sure that you do not give None into the escape method but maybe an empty string instead.

```<code>my_non_none_value = form_data.getfirst('actor') if form_data.getfirst('actor') else ""
bla = escape(my_non_none_value)
</code>```

long version:

```<code>my_non_none_value = form_data.getfirst('actor')
if my_non_none_value is None:
    my_non_none_value = ""
bla = escape(my_non_none_value)
</code>```

Side note: escape() in cgi is deprecated, use html.escape() instead.

Body:
http://cs1.ucc.ie/~adc2/cgi-bin/lab7/index.html
You can check out the error for yourself by just inputting anything into anyone of the boxes , doesnt have to be all, any help would be great
, I will send on the code after this

from cgitb import enable
enable()

from cgi import FieldStorage,escape

print('Content-Type: text/html')
print()

actor=''

genre=''

theyear=''

director=''

mood=''

result=''

form_data= FieldStorage()
if len(form_data) != 0:

    try:
        actor=escape(form_data.getfirst('actor'))
        genre=escape(form_data.getfirst('genre'))
        theyear=escape(form_data.getfirst('theyear'))
        director=escape(form_data.getfirst('director'))
        mood= escape(form_data.getfirst('mood'))
        connection = db.connect('####', '###', '####', '###')
        cursor = connection.cursor(db.cursors.DictCursor)
        cursor.execute("""SELECT title
                          FROM films
                          WHERE (actor = '%s')
                          OR (actor='%s' AND genre='%s')
                          OR (actor='%s' AND genre='%s' AND theyear='%i')
                          OR (actor='%s' AND genre='%s' AND theyear='%i' AND director='%s')
                          OR (actor='%s' AND genre='%s' AND theyear='%i' AND director='%s' AND mood='%s') % (actor, actor,genre, actor,genre,theyear, actor,genre,theyear,director,actor,genre,theyear,director,mood))
                          """)
        result = """

Your movie!

"""
        for row in cursor.fetchall():
            result+= '
%s
' ,(row['title'])
        result+= '
'
        cursor.close()
        connection.close()

    except db.Error:
        result = '
Sorry! We are currently experiencing technical difficulties.
'

Body:
According to the error code:

/users/2020/adc2/public_html/cgi-bin/lab7/index.py in ()
     24     try:
     25         actor=escape(form_data.getfirst('actor'))
=>   26         genre=escape(form_data.getfirst('genre'))
     27         theyear=escape(form_data.getfirst('theyear'))
     28         director=escape(form_data.getfirst('director'))
genre = '', escape = <function escape>, form_data = FieldStorage(None, None, [MiniFieldStorage('actor', 'i')]), form_data.getfirst = <bound method FieldStorage.getfirst of FieldStorage(None, None, [MiniFieldStorage('actor', 'i')])>
 /usr/local/lib/python3.4/cgi.py in escape(s=None, quote=None)
   1038     warn("cgi.escape is deprecated, use html.escape instead",
   1039          DeprecationWarning, stacklevel=2)
=> 1040     s = s.replace("&", "&amp;") # Must be done first!
   1041     s = s.replace("<", "&lt;")
   1042     s = s.replace(">", "&gt;")
s = None, s.replace undefined

escape() seems to get None as an argument. Escape() uses replace() directly internally, according to the given code snippet.. So the quick fix would be to make sure that you do not give None into the escape method but maybe an empty string instead.

my_non_none_value = form_data.getfirst('actor') if form_data.getfirst('actor') else ""
bla = escape(my_non_none_value)

long version:

my_non_none_value = form_data.getfirst('actor')
if my_non_none_value is None:
    my_non_none_value = ""
bla = escape(my_non_none_value)

Side note: escape() in cgi is deprecated, use html.escape() instead.


问:
How to get name of a landmark image (e.g. image of Eiffel Tower)?
I want to provide an image of a place (e.g. image of Eiffel Tower) and want Google to give me back that it contains "Eiffel Tower". I need this only for famous landmarks. What API should I use? I tried to look into Google Places API, but I am not sure if it will do what I am looking for. In the EXIF data of images, I do not have GPS co-ordinates (otherwise I could have done reverse geo-location lookup).</p>

答:
More or less I encountered me with the same issue in the sense that I want to get back the place name giving the image as a parameter. So far I have two possible solutions:

1) The use of the Google Cloud Vision API for landmark recognition. (Not completely free: https://cloud.google.com/vision/docs/pricing

2) In my case I am also taking into account to have the user coordinates (and possible if the device allows me, the direction). Hence, my approach will be to get places in the nearby getting their images. Make image comparison with respect to my input image (giving as well some priority to the closest place), returning the name of the image which is more similar to my input.

Hope that this sketch of the idea helps. I would be glad to here which approach did you use if you were able to resolve the problem. Greetings.


问:
OpenCV: Replace ilLoadImage with cv::imread
I'm using hessgpu for efficiently compute hessian-affine SIFT descriptors using GPUs.

In this project, Devil is used for reading images: if SiftGPU::RunSIFT(const char *imgpath) is called (implemented here), then ilLoadImage is used in GLTexImage.cpp for reading images (as RGB images).

However, in my project I use cv::imread to read images. The project provides SiftGPU::RunSIFT(int width, int height, const void * data, unsigned int gl_format, unsigned int gl_type) to compute descriptors from data provided directly from the user.

So I tried:

```<code>cv::Mat img = cv::imread("image.jpg", cv::IMREAD_GRAYSCALE);
sift.RunSIFT(img.cols, img.rows, img.data, GL_LUMINANCE, GL_UNSIGNED_BYTE);
</code>```

But this produce slightly less keypoints than sift.RunSIFT("image.jpg");. I tried to use:

```<code>cv::Mat img = cv::imread("image.jpg");
sift.RunSIFT(img.cols, img.rows, img.data, GL_RGB, GL_UNSIGNED_BYTE);
</code>```

But this produces 0 keypoints, so something very wrong happens. I think:

iLoadImage uses RGB image, while the only working method that I found up to now using cv::imread works only with grayscale images.

It's possible that devil use a different process to read images than OpenCV, espcecially for RGB images (since using the second approach produced 0 keypoints).

How can I do the equivalent of ilLoadimage using cv::imread?

答:
Changing the runSift line to:

```<code>sift.RunSIFT(img.cols, img.rows, img.data, GL_BGR, GL_UNSIGNED_BYTE);
</code>```

Solved the problem and produced the exact amount of descriptors.

Body:
I'm using hessgpu for efficiently compute hessian-affine SIFT descriptors using GPUs.

In this project, Devil is used for reading images: if SiftGPU::RunSIFT(const char *imgpath) is called (implemented here), then ilLoadImage is used in GLTexImage.cpp for reading images (as RGB images).

However, in my project I use cv::imread to read images. The project provides SiftGPU::RunSIFT(int width, int height, const void * data, unsigned int gl_format, unsigned int gl_type) to compute descriptors from data provided directly from the user.

So I tried:

cv::Mat img = cv::imread("image.jpg", cv::IMREAD_GRAYSCALE);
sift.RunSIFT(img.cols, img.rows, img.data, GL_LUMINANCE, GL_UNSIGNED_BYTE);

But this produce slightly less keypoints than sift.RunSIFT("image.jpg");. I tried to use:

cv::Mat img = cv::imread("image.jpg");
sift.RunSIFT(img.cols, img.rows, img.data, GL_RGB, GL_UNSIGNED_BYTE);

But this produces 0 keypoints, so something very wrong happens. I think:

iLoadImage uses RGB image, while the only working method that I found up to now using cv::imread works only with grayscale images.

It's possible that devil use a different process to read images than OpenCV, espcecially for RGB images (since using the second approach produced 0 keypoints).

How can I do the equivalent of ilLoadimage using cv::imread?

Body:
Changing the runSift line to:

sift.RunSIFT(img.cols, img.rows, img.data, GL_BGR, GL_UNSIGNED_BYTE);

Solved the problem and produced the exact amount of descriptors.


问:
How to integrate Apache Spark with MySQL for reading database tables as a spark dataframe?
I want to run my existing application with Apache Spark and MySQL.</p>

答:
For Java, this worked for me:

```<code>@Bean
public SparkConf sparkConf() {
    SparkConf sparkConf = new SparkConf()
            .setAppName(appName)
            .setSparkHome(sparkHome)
            .setMaster(masterUri);

    return sparkConf;
}

@Bean
public JavaSparkContext javaSparkContext() {
    return new JavaSparkContext(sparkConf());
}

@Bean
public SparkSession sparkSession() {
    return SparkSession
            .builder()
            .sparkContext(javaSparkContext().sc())
            .appName("Java Spark SQL basic example")
            .getOrCreate();
}
</code>```

```<code>Properties properties = new Properties();
        properties.put("user", "root");
        properties.put("password", "root");
        properties.put("driver", "com.mysql.cj.jdbc.Driver");
        sparkSession.read()
                    .jdbc("jdbc:mysql://localhost:3306/books?useSSL=false", "(SELECT books.BOOK_ID as BOOK_ID, books.BOOK_TITLE as BOOK_TITLE, books.BOOK_AUTHOR as BOOK_AUTHOR, borrowers.BORR_NAME as BORR_NAME FROM books LEFT OUTER JOIN borrowers ON books.BOOK_ID = borrowers.BOOK_ID) as t", properties) // join example
                    .show();
</code>```

of course, for MySQL, I needed the connector:

```<code>    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
    </dependency>
</code>```

And I get

```<code>+-------+------------------+--------------+---------------+
|BOOK_ID|        BOOK_TITLE|   BOOK_AUTHOR|      BORR_NAME|
+-------+------------------+--------------+---------------+
|      1|        Gyűrű kúra|J.R.K. Tolkien|   Sára Sarolta|
|      2|     Kecske-eledel|     Mekk Elek|Maláta Melchior|
|      3|      Répás tészta| Vegán Eleazár|           null|
|      4|Krumpli és pityóka| Farmer Emília|           null|
+-------+------------------+--------------+---------------+
</code>```

Body:
For Java, this worked for me:

@Bean
public SparkConf sparkConf() {
    SparkConf sparkConf = new SparkConf()
            .setAppName(appName)
            .setSparkHome(sparkHome)
            .setMaster(masterUri);

    return sparkConf;
}

@Bean
public JavaSparkContext javaSparkContext() {
    return new JavaSparkContext(sparkConf());
}

@Bean
public SparkSession sparkSession() {
    return SparkSession
            .builder()
            .sparkContext(javaSparkContext().sc())
            .appName("Java Spark SQL basic example")
            .getOrCreate();
}

Properties properties = new Properties();
        properties.put("user", "root");
        properties.put("password", "root");
        properties.put("driver", "com.mysql.cj.jdbc.Driver");
        sparkSession.read()
                    .jdbc("jdbc:mysql://localhost:3306/books?useSSL=false", "(SELECT books.BOOK_ID as BOOK_ID, books.BOOK_TITLE as BOOK_TITLE, books.BOOK_AUTHOR as BOOK_AUTHOR, borrowers.BORR_NAME as BORR_NAME FROM books LEFT OUTER JOIN borrowers ON books.BOOK_ID = borrowers.BOOK_ID) as t", properties) // join example
                    .show();

of course, for MySQL, I needed the connector:

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
    </dependency>

And I get

+-------+------------------+--------------+---------------+
|BOOK_ID|        BOOK_TITLE|   BOOK_AUTHOR|      BORR_NAME|
+-------+------------------+--------------+---------------+
|      1|        Gyűrű kúra|J.R.K. Tolkien|   Sára Sarolta|
|      2|     Kecske-eledel|     Mekk Elek|Maláta Melchior|
|      3|      Répás tészta| Vegán Eleazár|           null|
|      4|Krumpli és pityóka| Farmer Emília|           null|
+-------+------------------+--------------+---------------+


问:
"Master" associative table?
Consider a model for matching clients and sevices. Clients may be both providers of and consumers of services at various times. Clients may be individuals or groups (companies), the latter having multiple contacts. Contacts may have multiple addresses, phones, e-mails. Some of these relationships will be one-to-one (e.g., service to provider), but most will be one-to-many or many-to-many (multiple contacts at a company would have the same address).

In this model several associative tables would typically exist, e.g., client_contact, contract_addr, contact_phone, contact_email, service_provider, service_consumer, etc.

Say you issue a simple query for contact information for consumers of a given service. In addition to the six entity tables containing the data, the joins would reference five associative tables. Nothing particularly interesting about about this kind of query, of course - we do it every day.

It occurred to me though: why not have a single "master" associative table holding all associations? It would require this master table to have an "association type" in addition to the two PKs, and for all PKs to be of the same type (ints, GUIDs, etc.).

On the one hand, queries would become more complicated because each join would need to specifiy the type and PK. On the other hand, all joins would access the same table, and with appropriate indexng and caching performance could improve dramatically.

I assumed there might be a pattern (or anti-pattern) describing this approach, but haven't found anything on-line. Has anyone tried it? If so, does it scale?

Any references you can provide would be appreciated.

答:
What you're describing reminds me of fact tables from data warehousing.  My understanding is that you start with a typical transactional schema with a table to model every many-to-many relationship.  Then, to restructure the data for easier dimensional analysis, you can aggregate some / all the relationships in your schema into one wide table where each column is a key.  This effectively performs all possible joins ahead of time and dumps them into a table, inverting the purpose of query joins from relationship following to getting to the properties of your entities.

Anyway, my understanding of this stuff is hazy and my experience effectively nil, but maybe your idea is a fact table by another name, making them useful to investigate.

Title: "Master" associative table?