答:
This should work correctly, works on rubular.com tested:

```<code>$id = "tt0944557";
</code>```

Regex is as follows:
/^ to start matching from beginning of your string

tt match the first two characters must be tt

[0-9] only match if next characters are 0,1,2,3,4,5,6,7,8 or 9

{7} must be exactly 7 of these previous characters, so 1111111, 2232321, but not 123 or 332. {0,7} would say it may be 0, 1, 2, 3, 4,5,6 or 7 long

$/ stop matching here

```<code>if( preg_match( "/^tt[0-9]{7}$/", $id ) ) {
    echo "match";
} else {
    echo "no match";
}
</code>```

Title: preg_match always returns true/1

Body:
Sorry if this is a stupid question but I'm new to regex. For some reason no matter what I set $id to it always returns true.

$id = "tt0944557";

if( preg_match( "/tt\\d{7}/", $id ) ) {
    echo "match";
} else {
    echo "no match";
}

$id will always start with "tt" then 7 numbers

Body:
This should work correctly, works on rubular.com tested:

$id = "tt0944557";

Regex is as follows:
/^ to start matching from beginning of your string

tt match the first two characters must be tt

[0-9] only match if next characters are 0,1,2,3,4,5,6,7,8 or 9

{7} must be exactly 7 of these previous characters, so 1111111, 2232321, but not 123 or 332. {0,7} would say it may be 0, 1, 2, 3, 4,5,6 or 7 long

$/ stop matching here

if( preg_match( "/^tt[0-9]{7}$/", $id ) ) {
    echo "match";
} else {
    echo "no match";
}


来源: stackexchange

问:
Any pitfalls with this regex that matches ampersands not already encoded
In PHP, I want to encode ampersands that have not already been encoded. I came up with this regex

```<code>/&(?=[^a])/
</code>```

It seems to work good so far, but seeing as how I'm not much of a regex expert, I am asking if any potential pitfalls can be seen in this regex?

Essentially it needs to convert & to & but leave the & in & as is (so as not to get &)

Thanks

Update

Thanks for the answers. It seems I wasn't thinking broadly enough to cover all bases. This seems like a common pitfall of regexs themselves (having to think of all possibilities which may make your regex get false positives). It sure does beat my original one str_replace(' & ', ' & ', $string);  :)

答:
In Perl that would be:

```<code>$content =~ s/&(?!\w+;)/&/g;
</code>```

It uses a negative lookahead of 1 or more word chars, meaning "an ampersand that is not followed by one or more word chars and immediately followed  a semicolon. Though the use os the shortcut \w is not as safe as a specific char range for this particular case. A better option would be:

```<code>$content =~ s/&(?![a-z]+;)/&/g;
</code>```

And just case you have some uppercase animal in your data:

```<code>$content =~ s/&(?![a-zA-Z]+;)/&/g;
</code>```

OwnerDisplayName: alex

ContentLicense: CC BY-SA 2.5

Body:
In PHP, I want to encode ampersands that have not already been encoded. I came up with this regex

/&(?=[^a])/

It seems to work good so far, but seeing as how I'm not much of a regex expert, I am asking if any potential pitfalls can be seen in this regex?

Essentially it needs to convert & to & but leave the & in & as is (so as not to get &amp;)

Thanks

Update

Thanks for the answers. It seems I wasn't thinking broadly enough to cover all bases. This seems like a common pitfall of regexs themselves (having to think of all possibilities which may make your regex get false positives). It sure does beat my original one str_replace(' & ', ' & ', $string);  :)

LastEditorDisplayName: alex

Body:
In Perl that would be:

$content =~ s/&(?!\w+;)/&amp;/g;

It uses a negative lookahead of 1 or more word chars, meaning "an ampersand that is not followed by one or more word chars and immediately followed  a semicolon. Though the use os the shortcut \w is not as safe as a specific char range for this particular case. A better option would be:

$content =~ s/&(?![a-z]+;)/&amp;/g;

And just case you have some uppercase animal in your data:

$content =~ s/&(?![a-zA-Z]+;)/&amp;/g;

ContentLicense: CC BY-SA 3.0


问:
Collection select items on aggregate unique values
is there a way to select from a collection items on unique values?

For example:

```<code>    {
        "identifier": 1,
        "name": "Robert",
        "lastname": "Brown",
        "age": "30"
    },
    {
        "identifier": 2,
        "name": "Robert",
        "lastname": "Brown",
        "age": "30"
    }
</code>```

In this collection I would like to get only one of the two items because they have same name,lastname and age.

答:
There is nice method available in laravel

```<code>  $unique = $collection->unique('name');

  $unique->values()->all();
</code>```

official laravel docs

Body:
is there a way to select from a collection items on unique values?

For example:

    {
        "identifier": 1,
        "name": "Robert",
        "lastname": "Brown",
        "age": "30"
    },
    {
        "identifier": 2,
        "name": "Robert",
        "lastname": "Brown",
        "age": "30"
    }

In this collection I would like to get only one of the two items because they have same name,lastname and age.

Body:
There is nice method available in laravel

  $unique = $collection->unique('name');

  $unique->values()->all();

official laravel docs


问:
PHP is overwriting itself when imploding an array
so I have the weirdest problem that I've ever seen.

So, some background, I have a class that contains trades, with wants, haves, and the user who wants to trade. I also have a print method, that shows it as a node in the form of (Want | have1, have2, etc..), but when I implode the haves array, it overwrites it.

Here's an example:

```<code>array(5) {
  [0]=>
" string(14) "Draconnection
  [1]=>
" string(19) "Cyber Angel Idaten
  [2]=>
" string(12) "Hitodenchak
  [3]=>
" string(13) "Bujingi Warg
  [4]=>
" string(10) "Rai Rider
}
-Rai RiderargIdaten
</code>```

And Here's my class code

```<code>class trade{
    protected $have;
    protected $want;
    protected $user;
    function __construct($want,$have){
        if (is_array($have)){
            $this->have = $have; // have is an array of strings
        }else{
            $this->have = [$have];
        }
        $this->want = $want;
    }
    function getHave(){
        return $this->have;
    }
    function getWant(){
        return $this->want;
    }
    function __toString(){
        // return "(".$this->want." | ".implode(",", $this->have).")\r\n";
        // var_dump($this);
        $out=implode("-",$this->have);
        var_dump($this->have);
        return $out;
    }
}
</code>```

Thanks for your help

答:
You have rogue metacharacters at the end of all of those strings, probably bare \rs. The string data is all there, but the thing that's printing it keeps getting a command to return to the beginning of the line before printing more data overtop of the previous.

If you've got a shell handy run php yourscript.php | hexdump -C to see the raw output where 0d not followed by 0a is a bare \r not followed by a \n.

Body:
so I have the weirdest problem that I've ever seen.

So, some background, I have a class that contains trades, with wants, haves, and the user who wants to trade. I also have a print method, that shows it as a node in the form of (Want | have1, have2, etc..), but when I implode the haves array, it overwrites it.

Here's an example:

array(5) {
  [0]=>
" string(14) "Draconnection
  [1]=>
" string(19) "Cyber Angel Idaten
  [2]=>
" string(12) "Hitodenchak
  [3]=>
" string(13) "Bujingi Warg
  [4]=>
" string(10) "Rai Rider
}
-Rai RiderargIdaten

And Here's my class code

class trade{
    protected $have;
    protected $want;
    protected $user;
    function __construct($want,$have){
        if (is_array($have)){
            $this->have = $have; // have is an array of strings
        }else{
            $this->have = [$have];
        }
        $this->want = $want;
    }
    function getHave(){
        return $this->have;
    }
    function getWant(){
        return $this->want;
    }
    function __toString(){
        // return "(".$this->want." | ".implode(",", $this->have).")\r\n";
        // var_dump($this);
        $out=implode("-",$this->have);
        var_dump($this->have);
        return $out;
    }
}

Thanks for your help


问:
React router v4 - Login router Home Page
I'm working with react-router v4 and I haven't been able to redirect from the login component to the main page (index), this is an example of my code with a button to redirect direct.

Login.js

```<code>constructor(props)
{
    super(props);
    this.handleClick = this.handleClick.bind(this);
}

handleClick(e) {
    e.preventDefault();
    this.context.router.history.push('/home');
}

<button onClick={(e) => this.handleClick(e)}>
    Navigate
</button>
</code>```

Index.js

```<code>ReactDOM.render((
<Provider store={store}>
    <Router history={hashHistory}>
            <MuiThemeProvider>
                <div>
                    <Login>
                        <div>
                            <SearchBar/>
                            <MainMenu/>
                        </div>
                         <Switch>
                            <Route path="/home" component={Home}/>
                            <Route path="/calendar" component={Calendar}/>
                            <Route path="/about" component={About}/>
                         </Switch>
                         <Footer/>
                    </Login>
                </div>
            </MuiThemeProvider>
    </Router>
</Provider>
),document.getElementById('content'));
</code>```

答:
Solution 1: Using Link

For a simple solution, you can use Link component from react-router-dom, instead of button in your Login.js. There are ways to change the route in JS, but this seems easier one.

You need to import Login first:

```<code>import {Link} from 'react-router-dom';
</code>```

and then replace your <button> and handleClick() with this:

```<code><span className="someclass">
  <Link to="/home" />Navigate</Link>
</span>
</code>```

Solution 2: Using Redirect

```<code><Redirect exact from='/' to='/home' />
</code>```

P.S. In your current code setup you could also try using this.props.history.push('/home') in your handleClick() instead of this.context.router.history.push('/home').

Body:
I'm working with react-router v4 and I haven't been able to redirect from the login component to the main page (index), this is an example of my code with a button to redirect direct.

Login.js

constructor(props)
{
    super(props);
    this.handleClick = this.handleClick.bind(this);
}

handleClick(e) {
    e.preventDefault();
    this.context.router.history.push('/home');
}

<button onClick={(e) => this.handleClick(e)}>
    Navigate
</button>

Index.js

ReactDOM.render((
<Provider store={store}>
    <Router history={hashHistory}>
            <MuiThemeProvider>

                    <Login>

                            <SearchBar/>
                            <MainMenu/>

                         <Switch>
                            <Route path="/home" component={Home}/>
                            <Route path="/calendar" component={Calendar}/>
                            <Route path="/about" component={About}/>
                         </Switch>

                    </Login>

            </MuiThemeProvider>
    </Router>
</Provider>
),document.getElementById('content'));

Body:
Solution 1: Using Link

For a simple solution, you can use Link component from react-router-dom, instead of button in your Login.js. There are ways to change the route in JS, but this seems easier one.

You need to import Login first:

import {Link} from 'react-router-dom';

and then replace your <button> and handleClick() with this:

<span className="someclass">
  <Link to="/home" />Navigate</Link>
</span>

Solution 2: Using Redirect

<Redirect exact from='/' to='/home' />

P.S. In your current code setup you could also try using this.props.history.push('/home') in your handleClick() instead of this.context.router.history.push('/home').


问:
Memory Usage Concern with Controlled Components
I'm using controlled components in my React forms. My concern is those input fields where the user can type in text that can be long.

Because I'm using Redux for state management, state is immutable. So, in a description field, if I were to type, "Some description!", the state values that are kept in my redux store are:

```<code>S
So
Som
Some
Some
Some d
Some de
[and so on]
</code>```

In the life time of a user's session, memory usage can get a bit heavy just storing all the previous states of these form fields. This is especially concerning on mobile devices with limited system resources.

What's a good strategy to manage memory consumption of my redux store? Is there a way to flush out some parts of the store? I wouldn't want to wipe out everything but it would be beneficial if some parts could be flushed out in a controlled way.

答:
You're misunderstanding how Redux works, and how immutable data updates work.  Redux does not keep around previous versions of the state tree or actions by default.  The Redux DevTools do track a specific number of previous actions and resulting state trees, but only in development.  Any objects that are no longer referenced will be cleaned up by the JS garbage collector.

See http://redux.js.org/docs/faq/Performance.html#performance-state-memory, Is there any way to "commit" the state in Redux to free memory? , and ngredux state with big data collection, memory concerns for more information.

Body:
I'm using controlled components in my React forms. My concern is those input fields where the user can type in text that can be long.

Because I'm using Redux for state management, state is immutable. So, in a description field, if I were to type, "Some description!", the state values that are kept in my redux store are:

S
So
Som
Some
Some
Some d
Some de
[and so on]

In the life time of a user's session, memory usage can get a bit heavy just storing all the previous states of these form fields. This is especially concerning on mobile devices with limited system resources.

What's a good strategy to manage memory consumption of my redux store? Is there a way to flush out some parts of the store? I wouldn't want to wipe out everything but it would be beneficial if some parts could be flushed out in a controlled way.


问:
Portable SQL upsert (insert+update) solution needed
I need to perform a very simple operation on the database - put some values into the table by key, if the row exists - update it, if not - create a new one. The problem is that I need to do it in a portable way - i.e. the same query must work on MySQL, SQL Server, Oracle and preferably also DB2, Postgres, etc. So while I could use REPLACE or INSERT ... ON DUPLICATE KEY UPDATE in MySQL, I'm not sure that these would support such syntax. And I really want to avoid if's by database type, because this would be unmaintainable. I also don't want to actually query the value before updating, because I suspect it would slow down the process significantly (I need to do it multiple times).

So far the best I came up with is just doing:

```<code>  UPDATE table SET data='data' WHERE key='key';
  INSERT INTO table(key, data) VALUES ('key', 'data');
</code>```

one of those would always succeed and another fail, but I don't care that one of the queries fails. It looks kind of inelegant though. Any suggestions how to make it better?

答:
MERGE and WHEN NOT MATCHED are part of ANSI SQL 2003. Except of course its not uniformly supported.

Your solution while clever is dangerous because its not clear what the client should do. Ignore all errors? If so what happens if when they both fail.

Instead don't try to make this portable. Use stored procedures and/or a DAL to deal with differences between backends, since this undoubtedly won't be your only problem in any case.

Body:
I need to perform a very simple operation on the database - put some values into the table by key, if the row exists - update it, if not - create a new one. The problem is that I need to do it in a portable way - i.e. the same query must work on MySQL, SQL Server, Oracle and preferably also DB2, Postgres, etc. So while I could use REPLACE or INSERT ... ON DUPLICATE KEY UPDATE in MySQL, I'm not sure that these would support such syntax. And I really want to avoid if's by database type, because this would be unmaintainable. I also don't want to actually query the value before updating, because I suspect it would slow down the process significantly (I need to do it multiple times).

So far the best I came up with is just doing:

  UPDATE table SET data='data' WHERE key='key';
  INSERT INTO table(key, data) VALUES ('key', 'data');

one of those would always succeed and another fail, but I don't care that one of the queries fails. It looks kind of inelegant though. Any suggestions how to make it better?


问:
Check if Assembly Exists by name before loading it
I want to take this:

```<code>try
{
    Assembly assembly = Assembly.Load("This.Is.My.Assembly.Name");
}
catch (Exception)
{
}
</code>```

And do something similar, but instead never have it throw an exception. Perhaps do something that gets null back instead of an exception, checking if the assembly exists before even attempting to load it. What's the most elegant way to accomplish this?

答:
You can Check assembly like this:</p>

```<code>bool IsAssemblyExists(string assemblyName)
{
    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
    {
       if (assembly.FullName.StartsWith(assemblyName))
          return true;
    }
    return false;
}
</code>```

Body:
I want to take this:

try
{
    Assembly assembly = Assembly.Load("This.Is.My.Assembly.Name");
}
catch (Exception)
{
}

And do something similar, but instead never have it throw an exception. Perhaps do something that gets null back instead of an exception, checking if the assembly exists before even attempting to load it. What's the most elegant way to accomplish this?

Body:
You can Check assembly like this:

bool IsAssemblyExists(string assemblyName)
{
    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
    {
       if (assembly.FullName.StartsWith(assemblyName))
          return true;
    }
    return false;
}


问:
Upload of APK to Google Play fails because of different package names
I have a problem uploading my APK to the Google Play store because of different package names.

What I've done is the following:

I uploaded the APK without any problems.

The app is not published yet; the state is announced with "design".

Now I renamed the Java packages.

I changed the "package" attribute in AndroidManifest.xml to the new name.

I changed the android:versionCode from 1 to 2.

Then I built the APK and tried to upload to Google Dev Console but it fails with the message that the package names are different.

Is there a way to solve this conflict? I know I could "reset" my Java project to the old name but I want to keep the new package name and publish this one to Google Play for all future versions.

答: If you haven't publish the app, just go ahead and create a new application under the new package.</p>


问:
what's preventing additions to the current set of R reserved words/symbols?
Is there a historical precedent of internal changes to the R parser, adding new reserved words or symbols?

If I remember correctly data.table uses a serendipitous := that was once defined but left unused in R internals, but I'm not aware of others. However, as the language evolves, it would sometimes seem useful to define new symbols.

An obvious case could be made for magrittr's pipe %>% which has become ubiquitous for many, but remains a pain to type (sure, there are keyboard tricks, but still). Similarly, dplyr/rlang introduce/repurpose notations for "tidy evaluation" (!!, !!!, :=, ~, etc.).

Another case I'm seeing is the verbosity of lambda functions. Would it be possible, theoretically, to define internally something like f = λ(x) x+1 instead of f = function(x) x+1, or are there character restrictions on top of other reasons?

答:
Why add an ergonomics feature if you risk breaking a runtime that hosts a huge ecosystem? Also, once you add one feature, you are on a slippery slope and are staring straight in the face of feature bloat.

And if you say that we can be smart and judicious about what features we add, how do we structure that decision process? R does not have a "benevolent dictator" having a final word in decisions like this so you are left with design by committee with all that it entails.

The big thing with R has always been the package ecosystem, in which if you want a feature you write it yourself -- as in your magrittr example. The language itself has remained close to its S roots and has successfully served as a stable platform for all the development that has been happening.


问:
Zend_Auth using Zend_Session instead of default storage?
I was reading through this tutorial, and at one point in the code, the user info is retrieved from the database and a session is created for the user:

```<code>// the default storage is a session with namespace Zend_Auth
$authStorage = $auth->getStorage();
$authStorage->write($userInfo);
</code>```

I tried this, but this session expires once the browser is closed. So my question is how do I combine this with Zend_Session to create a cookie that lasts for 20 days or something? I can't figure it out through the Zend_Session documentation..

Any help is appreciated!
Thanks

答:
Don't mix 2 different tasks. One task you have is "authentication", another is "remember me feature".

So don't try to solve them in one shot.

For remember me store another cookie with some random hash and keep a table that assotiates each random hash with particular user_id.

Also, it is a lot of discussions about "remember me" implementations here at SO: http://www.google.ru/search?q=site%3Astackoverflow.com+remember+me&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:ru:official&client=firefox

Body:
I was reading through this tutorial, and at one point in the code, the user info is retrieved from the database and a session is created for the user:

// the default storage is a session with namespace Zend_Auth
$authStorage = $auth->getStorage();
$authStorage->write($userInfo);

I tried this, but this session expires once the browser is closed. So my question is how do I combine this with Zend_Session to create a cookie that lasts for 20 days or something? I can't figure it out through the Zend_Session documentation..

Any help is appreciated!
Thanks


问:
Can Google apps script be used to randomize page order on Google forms?
Update #2: Okay, I'm pretty sure my error in update #1 was because of indexing out of bounds over the array (I'm still not used to JS indexing at 0). But here is the new problem... if I write out the different combinations of the loop manually, setting the page index to 1 in moveItem() like so:

```<code>newForm.moveItem(itemsArray[0][0], 1);
newForm.moveItem(itemsArray[0][1], 1);
newForm.moveItem(itemsArray[0][2], 1);
newForm.moveItem(itemsArray[1][0], 1);
newForm.moveItem(itemsArray[1][1], 1);
newForm.moveItem(itemsArray[1][2], 1);
newForm.moveItem(itemsArray[2][0], 1);
...
</code>```

...I don't get any errors but the items end up on different pages! What is going on?

Update #1:: Using Sandy Good's answer as well as a script I found at this WordPress blog, I have managed to get closer to what I needed. I believe Sandy Good misinterpreted what I wanted to do because I wasn't specific enough in my question.

I would like to:

Get all items from a page (section header, images, question etc)

Put them into an array

Do this for all pages, adding these arrays to an array (i.e: [[all items from page 1][all items from page 2][all items from page 3]...])

Shuffle the elements of this array

Repopulate a new form with each element of this array. In this way, page order will be randomized.

My JavaScript skills are poor (this is the first time I've used it). There is a step that produces null entries and I don't know why... I had to remove them manually. I am not able to complete step 5 as I get the following error:

Cannot convert Item,Item,Item to (class).

"Item,Item,Item" is the array element containing all the items from a particular page. So it seems that I can't add three items to a page at a time? Or is something else going on here?

Here is my code:

```<code>function shuffleForms() {
  var itemsArray,shuffleQuestionsInNewForm,fncGetQuestionID,
      newFormFile,newForm,newID,shuffle, sections;

  // Copy template form by ID, set a new name
  newFormFile = DriveApp.getFileById('1prfcl-RhaD4gn0b2oP4sbcKaRcZT5XoCAQCbLm1PR7I')
               .makeCopy();
  newFormFile.setName('AAAAA_Shuffled_Form');

  // Get ID of new form and open it
  newID = newFormFile.getId();
  newForm = FormApp.openById(newID);

  // Initialize array to put IDs in
  itemsArray = [];

  function getPageItems(thisPageNum) {
    Logger.log("Getting items for page number: " + thisPageNum );
    var thisPageItems = []; // Used for result
    var thisPageBreakIndex = getPageItem(thisPageNum).getIndex();
    Logger.log( "This is index num : " + thisPageBreakIndex );

    // Get all items from page
    var allItems = newForm.getItems();
    thisPageItems.push(allItems[thisPageBreakIndex]);
    Logger.log( "Added pagebreak item: " + allItems[thisPageBreakIndex].getIndex() );
    for( var i = thisPageBreakIndex+1; ( i < allItems.length ) && ( allItems[i].getType() != FormApp.ItemType.PAGE_BREAK ); ++i ) {
      thisPageItems.push(allItems[i]);
      Logger.log( "Added non-pagebreak item: " + allItems[i].getIndex() );
    }
    return thisPageItems;
  }

  function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    Logger.log('shuffle ran')

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

      // Pick a remaining element...
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      // And swap it with the current element.
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
  }

  return array;
  }

  function shuffleAndMove() {

    // Get page items for all pages into an array
    for(i = 2; i <= 5; i++) {
      itemsArray[i] = getPageItems(i);
    }

    // Removes null values from array
    itemsArray = itemsArray.filter(function(x){return x});

    // Shuffle page items
    itemsArray = shuffle(itemsArray);

    // Move page items to the new form
    for(i = 2; i <= 5; ++i) {
      newForm.moveItem(itemsArray[i], i);
    }
  }

  shuffleAndMove();
}
</code>```

Original post: I have used Google forms to create a questionnaire. For my purposes, each question needs to be on a separate page but I need the pages to be randomized. A quick Google search shows this feature has not been added yet.

I see that the Form class in the Google apps script has a number of methods that alter/give access to various properties of Google Forms. Since I do not know Javascript and am not too familiar with Google apps/API I would like to know if what I am trying to do is even possible before diving in and figuring it all out.

If it is possible, I would appreciate any insight on what methods would be relevant for this task just to give me some direction to get started.

Based on comments from Sandy Good and two SE questions found here and here, this is the code I have so far:

```<code>// Script to shuffle question in a Google Form when the questions are in separate sections

function shuffleFormSections() {
  getQuestionID();
  createNewShuffledForm();
}

// Get question IDs
  function getQuestionID() {
    var form = FormApp.getActiveForm();
    var items = form.getItems();
    arrayID = [];
    for (var i in items) {
      arrayID[i] = items[i].getId();
    }
    // Logger.log(arrayID);
    return(arrayID);
}

// Shuffle function
  function shuffle(a) {
    var j, x, i;
    for (i = a.length; i; i--) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
}

// Shuffle IDs and create new form with new question order
function createNewShuffledForm() {
    shuffle(arrayID);
    // Logger.log(arrayID);
    var newForm = FormApp.create('Shuffled Form');
    for (var i in arrayID) {
      arrayID[i].getItemsbyId();
  }
}
</code>```

答:
I tested this code. It created a new Form, and then shuffled the questions in the new Form.  It excludes page breaks, images and section headers.  You need to provide a source file ID for the original template Form.  This function has 3 inner sub-functions.  The inner functions are at the top, and they are called at the bottom of the outer function.  The arrayOfIDs variable does not need to be returned or passed to another function because it is available in the outer scope.

```<code>function shuffleFormSections() {
  var arrayOfIDs,shuffleQuestionsInNewForm,fncGetQuestionID,
      newFormFile,newForm,newID,items,shuffle;

  newFormFile = DriveApp.getFileById('Put the source file ID here')
               .makeCopy();
  newFormFile.setName('AAAAA_Shuffled_Form');

  newID = newFormFile.getId();

  newForm = FormApp.openById(newID);

  arrayOfIDs = [];

  fncGetQuestionID = function() {
    var i,L,thisID,thisItem,thisType;

    items = newForm.getItems();
    L = items.length;

    for (i=0;i<L;i++) {
      thisItem = items[i];
      thisType = thisItem.getType();

      if (thisType === FormApp.ItemType.PAGE_BREAK ||
      thisType === FormApp.ItemType.SECTION_HEADER ||
      thisType === FormApp.ItemType.IMAGE) {
       continue;
      }

      thisID = thisItem.getId();
      arrayOfIDs.push(thisID);
    }

    Logger.log('arrayOfIDs: ' + arrayOfIDs);
    //the array arrayOfIDs does not need to be returned since it is available
    //in the outermost scope
  }// End of fncGetQuestionID function

  shuffle = function() {// Shuffle function
    var j, x, i;
    Logger.log('shuffle ran')

    for (i = arrayOfIDs.length; i; i--) {
      j = Math.floor(Math.random() * i);
      Logger.log('j: ' + j)

      x = arrayOfIDs[i - 1];
      Logger.log('x: ' + x)

      arrayOfIDs[i - 1] = arrayOfIDs[j];

      arrayOfIDs[j] = x;
    }

    Logger.log('arrayOfIDs: ' + arrayOfIDs)
  }

  shuffleQuestionsInNewForm = function() {
    var i,L,thisID,thisItem,thisQuestion,questionType;

    L = arrayOfIDs.length;

    for (i=0;i<L;i++) {
      thisID = arrayOfIDs[i];
      Logger.log('thisID: ' + thisID)
      thisItem = newForm.getItemById(thisID);

      newForm.moveItem(thisItem, i)
    }
  }

  fncGetQuestionID();//Get all the question ID's and put them into an array
  shuffle();

  shuffleQuestionsInNewForm();
}
</code>```

Body:
Update #2: Okay, I'm pretty sure my error in update #1 was because of indexing out of bounds over the array (I'm still not used to JS indexing at 0). But here is the new problem... if I write out the different combinations of the loop manually, setting the page index to 1 in moveItem() like so:

newForm.moveItem(itemsArray[0][0], 1);
newForm.moveItem(itemsArray[0][1], 1);
newForm.moveItem(itemsArray[0][2], 1);
newForm.moveItem(itemsArray[1][0], 1);
newForm.moveItem(itemsArray[1][1], 1);
newForm.moveItem(itemsArray[1][2], 1);
newForm.moveItem(itemsArray[2][0], 1);
...

...I don't get any errors but the items end up on different pages! What is going on?

Update #1:: Using Sandy Good's answer as well as a script I found at this WordPress blog, I have managed to get closer to what I needed. I believe Sandy Good misinterpreted what I wanted to do because I wasn't specific enough in my question.

I would like to:

Get all items from a page (section header, images, question etc)

Put them into an array

Do this for all pages, adding these arrays to an array (i.e: [[all items from page 1][all items from page 2][all items from page 3]...])

Shuffle the elements of this array

Repopulate a new form with each element of this array. In this way, page order will be randomized.

My JavaScript skills are poor (this is the first time I've used it). There is a step that produces null entries and I don't know why... I had to remove them manually. I am not able to complete step 5 as I get the following error:

Cannot convert Item,Item,Item to (class).

"Item,Item,Item" is the array element containing all the items from a particular page. So it seems that I can't add three items to a page at a time? Or is something else going on here?

Here is my code:

function shuffleForms() {
  var itemsArray,shuffleQuestionsInNewForm,fncGetQuestionID,
      newFormFile,newForm,newID,shuffle, sections;

  // Copy template form by ID, set a new name
  newFormFile = DriveApp.getFileById('1prfcl-RhaD4gn0b2oP4sbcKaRcZT5XoCAQCbLm1PR7I')
               .makeCopy();
  newFormFile.setName('AAAAA_Shuffled_Form');

  // Get ID of new form and open it
  newID = newFormFile.getId();
  newForm = FormApp.openById(newID);

  // Initialize array to put IDs in
  itemsArray = [];

  function getPageItems(thisPageNum) {
    Logger.log("Getting items for page number: " + thisPageNum );
    var thisPageItems = []; // Used for result
    var thisPageBreakIndex = getPageItem(thisPageNum).getIndex();
    Logger.log( "This is index num : " + thisPageBreakIndex );

    // Get all items from page
    var allItems = newForm.getItems();
    thisPageItems.push(allItems[thisPageBreakIndex]);
    Logger.log( "Added pagebreak item: " + allItems[thisPageBreakIndex].getIndex() );
    for( var i = thisPageBreakIndex+1; ( i < allItems.length ) && ( allItems[i].getType() != FormApp.ItemType.PAGE_BREAK ); ++i ) {
      thisPageItems.push(allItems[i]);
      Logger.log( "Added non-pagebreak item: " + allItems[i].getIndex() );
    }
    return thisPageItems;
  }

  function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    Logger.log('shuffle ran')

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

      // Pick a remaining element...
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      // And swap it with the current element.
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
  }

  return array;
  }

  function shuffleAndMove() {

    // Get page items for all pages into an array
    for(i = 2; i <= 5; i++) {
      itemsArray[i] = getPageItems(i);
    }

    // Removes null values from array
    itemsArray = itemsArray.filter(function(x){return x});

    // Shuffle page items
    itemsArray = shuffle(itemsArray);

    // Move page items to the new form
    for(i = 2; i <= 5; ++i) {
      newForm.moveItem(itemsArray[i], i);
    }
  }

  shuffleAndMove();
}

Original post: I have used Google forms to create a questionnaire. For my purposes, each question needs to be on a separate page but I need the pages to be randomized. A quick Google search shows this feature has not been added yet.

I see that the Form class in the Google apps script has a number of methods that alter/give access to various properties of Google Forms. Since I do not know Javascript and am not too familiar with Google apps/API I would like to know if what I am trying to do is even possible before diving in and figuring it all out.

If it is possible, I would appreciate any insight on what methods would be relevant for this task just to give me some direction to get started.

Based on comments from Sandy Good and two SE questions found here and here, this is the code I have so far:

// Script to shuffle question in a Google Form when the questions are in separate sections

function shuffleFormSections() {
  getQuestionID();
  createNewShuffledForm();
}

// Get question IDs
  function getQuestionID() {
    var form = FormApp.getActiveForm();
    var items = form.getItems();
    arrayID = [];
    for (var i in items) {
      arrayID[i] = items[i].getId();
    }
    // Logger.log(arrayID);
    return(arrayID);
}

// Shuffle function
  function shuffle(a) {
    var j, x, i;
    for (i = a.length; i; i--) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
}

// Shuffle IDs and create new form with new question order
function createNewShuffledForm() {
    shuffle(arrayID);
    // Logger.log(arrayID);
    var newForm = FormApp.create('Shuffled Form');
    for (var i in arrayID) {
      arrayID[i].getItemsbyId();
  }
}

Body:
I tested this code. It created a new Form, and then shuffled the questions in the new Form.  It excludes page breaks, images and section headers.  You need to provide a source file ID for the original template Form.  This function has 3 inner sub-functions.  The inner functions are at the top, and they are called at the bottom of the outer function.  The arrayOfIDs variable does not need to be returned or passed to another function because it is available in the outer scope.

function shuffleFormSections() {
  var arrayOfIDs,shuffleQuestionsInNewForm,fncGetQuestionID,
      newFormFile,newForm,newID,items,shuffle;

  newFormFile = DriveApp.getFileById('Put the source file ID here')
               .makeCopy();
  newFormFile.setName('AAAAA_Shuffled_Form');

  newID = newFormFile.getId();

  newForm = FormApp.openById(newID);

  arrayOfIDs = [];

  fncGetQuestionID = function() {
    var i,L,thisID,thisItem,thisType;

    items = newForm.getItems();
    L = items.length;

    for (i=0;i<L;i++) {
      thisItem = items[i];
      thisType = thisItem.getType();

      if (thisType === FormApp.ItemType.PAGE_BREAK ||
      thisType === FormApp.ItemType.SECTION_HEADER ||
      thisType === FormApp.ItemType.IMAGE) {
       continue;
      }

      thisID = thisItem.getId();
      arrayOfIDs.push(thisID);
    }

    Logger.log('arrayOfIDs: ' + arrayOfIDs);
    //the array arrayOfIDs does not need to be returned since it is available
    //in the outermost scope
  }// End of fncGetQuestionID function

  shuffle = function() {// Shuffle function
    var j, x, i;
    Logger.log('shuffle ran')

    for (i = arrayOfIDs.length; i; i--) {
      j = Math.floor(Math.random() * i);
      Logger.log('j: ' + j)

      x = arrayOfIDs[i - 1];
      Logger.log('x: ' + x)

      arrayOfIDs[i - 1] = arrayOfIDs[j];

      arrayOfIDs[j] = x;
    }

    Logger.log('arrayOfIDs: ' + arrayOfIDs)
  }

  shuffleQuestionsInNewForm = function() {
    var i,L,thisID,thisItem,thisQuestion,questionType;

    L = arrayOfIDs.length;

    for (i=0;i<L;i++) {
      thisID = arrayOfIDs[i];
      Logger.log('thisID: ' + thisID)
      thisItem = newForm.getItemById(thisID);

      newForm.moveItem(thisItem, i)
    }
  }

  fncGetQuestionID();//Get all the question ID's and put them into an array
  shuffle();

  shuffleQuestionsInNewForm();
}


问:
Glide Cache management in Recyclerview with Grid layout
I am trying to build a gallery for my app. Following some tutorials and stackoverflow, I finally managed to make the gallery. I am using Glide to set images, so no issue of memory crashing and all. The only problem is, when I fling, Images are not set into their views as fast as those views are being shown. Here is a gif. So I get to see the placeholders or the background of the recyclerview while imageviews are being set. Depending on the fling speed, this may last for 500-1000ms. But that is sufficient to make the gallery look bad. This happens when I use fling to scroll up or down. To my knowledge, this is because glide freeing the images from it's cache. Is there any solution for it.
Here is my code.

activity_gallery:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_monuments"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".GalleryActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview_gallery"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:alwaysDrawnWithCache="true"
        android:clipToPadding="false"
        android:scrollbars="vertical"
        android:scrollbarStyle="insideOverlay"/>

</LinearLayout>```
</div>
</div>
</p>
<p>Here is how I am setting recyclerview:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>RecyclerView gridView = (RecyclerView)findViewById(R.id.recyclerview_gallery);
        gridView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),NUM_OF_COLUMNS);
        gridView.setLayoutManager(layoutManager);
        gridView.isDrawingCacheEnabled();
        gridView.addItemDecoration(new MarginDecoration(GalleryActivity.this, NUM_OF_COLUMNS, GRID_PADDING, true));
        gridView.setHasFixedSize(true);
        gridView.setVerticalScrollBarEnabled(true);
        gridView.setBackgroundColor(getResources().getColor(R.color.colorBlack));
        GalleryAdapter galleryAdapter = new GalleryAdapter(GalleryActivity.this, GalleryActivity.this, ImageNamesList, columnWidth);

        gridView.setAdapter(galleryAdapter);</code>```

Here is how I am setting imageview in adapter:

 viewHolder.galleryImage.setLayoutParams(new GridView.LayoutParams(imageWidth, imageWidth));
        Glide.with(context)
                .load(uri)
                .asBitmap()
                .placeholder(R.drawable.monument)
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(viewHolder.galleryImage);```

Please let me know of the possible solutions.

P.S: The gif is low frame rate and hence showing the slow fling which is not the case.

答:
To solve cache management, i use a singleton store best practice. Realm for android is perfect it is NoSql and super fast, what i normally do is create a realm object, in the adapter check if the current url is in realm, if true dont pull new image else, pull and store.

Then when the main activity or fragment is ever being destroy just delete all from realm.

Body:
I am trying to build a gallery for my app. Following some tutorials and stackoverflow, I finally managed to make the gallery. I am using Glide to set images, so no issue of memory crashing and all. The only problem is, when I fling, Images are not set into their views as fast as those views are being shown. Here is a gif. So I get to see the placeholders or the background of the recyclerview while imageviews are being set. Depending on the fling speed, this may last for 500-1000ms. But that is sufficient to make the gallery look bad. This happens when I use fling to scroll up or down. To my knowledge, this is because glide freeing the images from it's cache. Is there any solution for it.
Here is my code.

activity_gallery:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_monuments"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".GalleryActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview_gallery"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:alwaysDrawnWithCache="true"
        android:clipToPadding="false"
        android:scrollbars="vertical"
        android:scrollbarStyle="insideOverlay"/>

</LinearLayout>

Here is how I am setting recyclerview:

RecyclerView gridView = (RecyclerView)findViewById(R.id.recyclerview_gallery);
        gridView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),NUM_OF_COLUMNS);
        gridView.setLayoutManager(layoutManager);
        gridView.isDrawingCacheEnabled();
        gridView.addItemDecoration(new MarginDecoration(GalleryActivity.this, NUM_OF_COLUMNS, GRID_PADDING, true));
        gridView.setHasFixedSize(true);
        gridView.setVerticalScrollBarEnabled(true);
        gridView.setBackgroundColor(getResources().getColor(R.color.colorBlack));
        GalleryAdapter galleryAdapter = new GalleryAdapter(GalleryActivity.this, GalleryActivity.this, ImageNamesList, columnWidth);

        gridView.setAdapter(galleryAdapter);

Here is how I am setting imageview in adapter:

 viewHolder.galleryImage.setLayoutParams(new GridView.LayoutParams(imageWidth, imageWidth));
        Glide.with(context)
                .load(uri)
                .asBitmap()
                .placeholder(R.drawable.monument)
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(viewHolder.galleryImage);

Please let me know of the possible solutions.

P.S: The gif is low frame rate and hence showing the slow fling which is not the case.


问:
How to compare comma separated string in one column with the comma separated strings other dataframe
I have two df as below
df1:

```<code>    M1     |
    -------+
    a,b,c  |
    a      |
    b,c    |
    c,b,a  |
    b,a,d  |
    d,a,b,c|
    a,d,c  |
    b      |
    c,d    |
    d,a    |
</code>```

df2:

```<code>X1      |X2
--------+---
a       |1
b       |2
c       |3
d       |4
a,b     |5
a,c     |6
a,d     |7
b,c     |8
b,d     |9
c,d     |10
a,b,c   |11
a,c,d   |12
a,b,d   |13
b,c,d   |14
a,b,c,d |15
</code>```

can someone help me to match values in df1$M1 and df2$X1. and put the corresponding X2 value in column M2 as below

df1:

```<code>M1      |M2
--------+---
a,b,c   |11
a       |1
b,c     |8
c,b,a   |11
b,a,d   |13
d,a,b,c |15
a,d,c   |12
b       |2
c,d     |10
d,a     |7
</code>```

Can someone help me

答:
X1 and M1 have to be stored as Characters. You can check with str(df1), and re-assign if necessary df1 <- as.character(df1$X1), and the same for df2

Then, create new columns with the values in alphabetical order:

df1$Ordered <- sapply(lapply(strsplit(df1$X1, ","), sort),paste,collapse=",")

df2$Ordered <- sapply(lapply(strsplit(df2$M1, ","), sort),paste,collapse=",")

Then perform a join like so:

merge(df1, df2, by="Ordered")

If you want to include all the values in df1 regardless of whether they have a matching value in df2, add the all.x = TRUE argument. Same logic applies adding all = TRUE (include everything from both data frames), or all.y = TRUE for df2.

Body:
I have two df as below
df1:

    M1     |
    -------+
    a,b,c  |
    a      |
    b,c    |
    c,b,a  |
    b,a,d  |
    d,a,b,c|
    a,d,c  |
    b      |
    c,d    |
    d,a    |

df2:

X1      |X2
--------+---
a       |1
b       |2
c       |3
d       |4
a,b     |5
a,c     |6
a,d     |7
b,c     |8
b,d     |9
c,d     |10
a,b,c   |11
a,c,d   |12
a,b,d   |13
b,c,d   |14
a,b,c,d |15

can someone help me to match values in df1$M1 and df2$X1. and put the corresponding X2 value in column M2 as below

df1:

M1      |M2
--------+---
a,b,c   |11
a       |1
b,c     |8
c,b,a   |11
b,a,d   |13
d,a,b,c |15
a,d,c   |12
b       |2
c,d     |10
d,a     |7

Can someone help me


问:
Python HTTP Header Content-Type boundary
Here is my code:

```<code>headers={
'Host': 'cafe.upphoto.naver.com',
'Content-Length': '879990',
'Accept': '*/*',
'Origin': 'http://cafe.upphoto.naver.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36',
'Content-Type':content,
'Content-Type': 'multipart/form-data;',# boundary=----WebKitFormBoundary3oLjjtLvU7AzQqTF',
'Referer': write,
'Accept-Language': 'ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4',
}

files = {'image':('test.jpg',open('C:\\Users\\Public\\Pictures\\Sample Pictures\\test.jpg','rb'),'Content-Type: image/jpeg'),'filename':(None,'test.jpg'),'autorotate':(None,'true'),'extractAnimatedCnt':(None,'true'),'userId':(None,'beg1995')}

resp=self.post(url2+'upload/0',files=files,headers=headers)
</code>```

When you run this code, the following packet is created:

```<code>POST http://cafe.upphoto.naver.com/MjAxNzA3MDcwMTExNDAHMTQ5OTM1ODQzNjkyNwdjYWZlMgdiZWcxOTk1BzAHMgdhODA1MzhiZmMyMGMyYTFlYTlhODE1NGY5OTc1ZDRkZA/upload/0 HTTP/1.1
Host: cafe.upphoto.naver.com
Proxy-Connection: keep-alive
Content-Length: 879990
Accept: */*
Origin: http://cafe.upphoto.naver.com
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary9xhUsyQOPYJrPr3R
Referer: http://cafe.upphoto.naver.com/MjAxNzA3MDcwMTExNDAHMTQ5OTM1ODQzNjkyNwdjYWZlMgdiZWcxOTk1BzAHMgdhODA1MzhiZmMyMGMyYTFlYTlhODE1NGY5OTc1ZDRkZA/startup?mode=base&width=960
Accept-Language: ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4

--e2f306a6b5a3485fb70bc2f7f1af2e9a
Content-Disposition: form-data; name="image"; filename="test.jpg"
Content-Type: Content-Type: image/jpeg

ÿØÿà

Content-Disposition: form-data; name="filename"

test.jpg
--e2f306a6b5a3485fb70bc2f7f1af2e9a
Content-Disposition: form-data; name="autorotate"

true
--e2f306a6b5a3485fb70bc2f7f1af2e9a
Content-Disposition: form-data; name="extractAnimatedCnt"

true
--e2f306a6b5a3485fb70bc2f7f1af2e9a
Content-Disposition: form-data; name="userId"

beg1995
--e2f306a6b5a3485fb70bc2f7f1af2e9a-
</code>```

Look. The boundaries set and the boundaries actually applied are different.

What is the problem?

答: I suppose you use requests  library. It doesn't allow to setup boundaries. So it is generated automatically on the fly.</p>

Body:
Here is my code:

headers={
'Host': 'cafe.upphoto.naver.com',
'Content-Length': '879990',
'Accept': '*/*',
'Origin': 'http://cafe.upphoto.naver.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36',
'Content-Type':content,
'Content-Type': 'multipart/form-data;',# boundary=----WebKitFormBoundary3oLjjtLvU7AzQqTF',
'Referer': write,
'Accept-Language': 'ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4',
}

files = {'image':('test.jpg',open('C:\\Users\\Public\\Pictures\\Sample Pictures\\test.jpg','rb'),'Content-Type: image/jpeg'),'filename':(None,'test.jpg'),'autorotate':(None,'true'),'extractAnimatedCnt':(None,'true'),'userId':(None,'beg1995')}

resp=self.post(url2+'upload/0',files=files,headers=headers)

When you run this code, the following packet is created:

POST http://cafe.upphoto.naver.com/MjAxNzA3MDcwMTExNDAHMTQ5OTM1ODQzNjkyNwdjYWZlMgdiZWcxOTk1BzAHMgdhODA1MzhiZmMyMGMyYTFlYTlhODE1NGY5OTc1ZDRkZA/upload/0 HTTP/1.1
Host: cafe.upphoto.naver.com
Proxy-Connection: keep-alive
Content-Length: 879990
Accept: */*
Origin: http://cafe.upphoto.naver.com
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary9xhUsyQOPYJrPr3R
Referer: http://cafe.upphoto.naver.com/MjAxNzA3MDcwMTExNDAHMTQ5OTM1ODQzNjkyNwdjYWZlMgdiZWcxOTk1BzAHMgdhODA1MzhiZmMyMGMyYTFlYTlhODE1NGY5OTc1ZDRkZA/startup?mode=base&width=960
Accept-Language: ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4

--e2f306a6b5a3485fb70bc2f7f1af2e9a
Content-Disposition: form-data; name="image"; filename="test.jpg"
Content-Type: Content-Type: image/jpeg

ÿØÿà

Content-Disposition: form-data; name="filename"

test.jpg
--e2f306a6b5a3485fb70bc2f7f1af2e9a
Content-Disposition: form-data; name="autorotate"

true
--e2f306a6b5a3485fb70bc2f7f1af2e9a
Content-Disposition: form-data; name="extractAnimatedCnt"

true
--e2f306a6b5a3485fb70bc2f7f1af2e9a
Content-Disposition: form-data; name="userId"

beg1995
--e2f306a6b5a3485fb70bc2f7f1af2e9a-

Look. The boundaries set and the boundaries actually applied are different.

What is the problem?


问:
Access is denied while trying to migrate EntityFramework6 mdf file - wrong path
I'm trying to play around with EntityFramework6. I'm using a code first approach, and I've created a database in my projectfolder/bin/debug/SchoolContext.mdf. The database has the proper tables when created and I'm also capable of adding data to it.

I reached a point in the tutorial where I can use migration to update the field. So I enabled the migrations from package manager, removed a field from a table and generated the migration by using Add-Migration MigrationName. The migration is generated, but when I try to run it by using Update-Database, I get the following:

```<code>CREATE FILE encountered operating system error 5(Access is denied.) while attempting to open or create the physical file 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\SchoolContext.mdf'.
</code>```

...

The problem is that it is looking for the mdf file in the wrong path. I've tried to find how to solve this, but I couldn't.

The right path would be: C:\Users\home\Documents\Visual Studio 2017\Projects\Test2\Test2\bin\Debug\SchoolContext.mdf

Here is my auto generated App.config file + my modifications of adding a connection string.

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=bcsfdadsa56145" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="SchoolContext" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|SchoolContext.mdf;Integrated Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
 </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>
</code>```

I do set the DataDirectory in the configuration file:

```<code>internal sealed class Configuration : DbMigrationsConfiguration<Test2.Data.SchoolContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory());
...
</code>```

答:
Code First allows you to stop using file path based connection strings in favour of much simpler connection strings that use a database name:

```<code><connectionStrings>
    <add name="SchoolContext"
         connectionString="Server=(LocalDB)\MSSQLLocalDB;Database=School;Integrated Security=True;Connect Timeout=30"
         providerName="System.Data.SqlClient"  />
</connectionStrings>
</code>```

You don't need to configure the path of the database, you just need the database name. You can remove the AppDomain.CurrentDomain.SetData() code from your Configuration class.

A simple way to make sure that the right connection string is used by your application runtime and also at design time by the Package Manager Console: your DbContext class should have a parameterless constructor that invokes the base constructor with the connection string name in your app.config file:

```<code>public MyDbContext() : base("SchoolContext")
{ ... }
</code>```

This is the easiest way to specify the connection data. EF 6 provides other ways to do it, as explained in this msdn reference page.

And where will your database file be stored? It doesn't really matter anymore. This page explains it. But be aware that LocalDB is not intended to be used in production systems, only in development environments.

Body:
I'm trying to play around with EntityFramework6. I'm using a code first approach, and I've created a database in my projectfolder/bin/debug/SchoolContext.mdf. The database has the proper tables when created and I'm also capable of adding data to it.

I reached a point in the tutorial where I can use migration to update the field. So I enabled the migrations from package manager, removed a field from a table and generated the migration by using Add-Migration MigrationName. The migration is generated, but when I try to run it by using Update-Database, I get the following:

CREATE FILE encountered operating system error 5(Access is denied.) while attempting to open or create the physical file 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\SchoolContext.mdf'.

...

The problem is that it is looking for the mdf file in the wrong path. I've tried to find how to solve this, but I couldn't.

The right path would be: C:\Users\home\Documents\Visual Studio 2017\Projects\Test2\Test2\bin\Debug\SchoolContext.mdf

Here is my auto generated App.config file + my modifications of adding a connection string.

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

  </configSections>
  <connectionStrings>
    <add name="SchoolContext" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|SchoolContext.mdf;Integrated Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
 </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

I do set the DataDirectory in the configuration file:

internal sealed class Configuration : DbMigrationsConfiguration<Test2.Data.SchoolContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory());
...

Body:
Code First allows you to stop using file path based connection strings in favour of much simpler connection strings that use a database name:

<connectionStrings>
    <add name="SchoolContext"
         connectionString="Server=(LocalDB)\MSSQLLocalDB;Database=School;Integrated Security=True;Connect Timeout=30"
         providerName="System.Data.SqlClient"  />
</connectionStrings>

You don't need to configure the path of the database, you just need the database name. You can remove the AppDomain.CurrentDomain.SetData() code from your Configuration class.

A simple way to make sure that the right connection string is used by your application runtime and also at design time by the Package Manager Console: your DbContext class should have a parameterless constructor that invokes the base constructor with the connection string name in your app.config file:

public MyDbContext() : base("SchoolContext")
{ ... }

This is the easiest way to specify the connection data. EF 6 provides other ways to do it, as explained in this msdn reference page.

And where will your database file be stored? It doesn't really matter anymore. This page explains it. But be aware that LocalDB is not intended to be used in production systems, only in development environments.


问:
How to partial match words within a string - TSQL
I have a table called Keywords that 100's of keywords ranging from one word to several, all separated by commas. For example:

```<code>change of name, asb, repair, reporting violence
</code>```

These keywords are grouped into categories.

We have users who can enter any text into a free text field. Example:

```<code>Caller rang to to speak to ASB about violence
</code>```

How do I use SQL to read the words in the free text field to check for any matches in the keyword table? So in the example above I want it to pick up that ASB and Violence was stored in the Keyword table.

I would also want it bring back a result if only one word was used like ASB.

It's important to note that any words could be entered into the free text field.

I'm using Microsoft SQL Server 2014 SP2.

Thanks

答:
As you have not specified your table names; I will create some.  Please run this:

```<code>create table dbWords (id int not null identity, words varchar(100), primary key (id))
insert into dbWords (words) values ('change of name, asb, repair, reporting violence')

CREATE FUNCTION [dbo].[fnSplitString]
(
    @string NVARCHAR(MAX),
    @delimiter CHAR(1)
)
RETURNS @output TABLE(splitdata NVARCHAR(MAX)
)
BEGIN
    DECLARE @start INT, @end INT
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string)
    WHILE @start < LEN(@string) + 1 BEGIN
        IF @end = 0
            SET @end = LEN(@string) + 1

        INSERT INTO @output (splitdata)
        VALUES(SUBSTRING(@string, @start, @end - @start))
        SET @start = @end + 1
        SET @end = CHARINDEX(@delimiter, @string, @start)

    END
    RETURN
ENd
</code>```

Then run this:

```<code>    select * from dbWords inner join (
select * from dbo.fnSplitString('change of name, change of dob', ',')
) as splitdatatable on dbwords.words like '%,' + splitdata+ ',%'
or dbwords.words like '%,' + splitdata
or dbwords.words like splitdata + ',%'
</code>```

The text passed to the function in the SQL statement above is the text entered by the user.

Body:
I have a table called Keywords that 100's of keywords ranging from one word to several, all separated by commas. For example:

change of name, asb, repair, reporting violence

These keywords are grouped into categories.

We have users who can enter any text into a free text field. Example:

Caller rang to to speak to ASB about violence

How do I use SQL to read the words in the free text field to check for any matches in the keyword table? So in the example above I want it to pick up that ASB and Violence was stored in the Keyword table.

I would also want it bring back a result if only one word was used like ASB.

It's important to note that any words could be entered into the free text field.

I'm using Microsoft SQL Server 2014 SP2.

Thanks

Body:
As you have not specified your table names; I will create some.  Please run this:

create table dbWords (id int not null identity, words varchar(100), primary key (id))
insert into dbWords (words) values ('change of name, asb, repair, reporting violence')

CREATE FUNCTION [dbo].[fnSplitString]
(
    @string NVARCHAR(MAX),
    @delimiter CHAR(1)
)
RETURNS @output TABLE(splitdata NVARCHAR(MAX)
)
BEGIN
    DECLARE @start INT, @end INT
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string)
    WHILE @start < LEN(@string) + 1 BEGIN
        IF @end = 0
            SET @end = LEN(@string) + 1

        INSERT INTO @output (splitdata)
        VALUES(SUBSTRING(@string, @start, @end - @start))
        SET @start = @end + 1
        SET @end = CHARINDEX(@delimiter, @string, @start)

    END
    RETURN
ENd

Then run this:

    select * from dbWords inner join (
select * from dbo.fnSplitString('change of name, change of dob', ',')
) as splitdatatable on dbwords.words like '%,' + splitdata+ ',%'
or dbwords.words like '%,' + splitdata
or dbwords.words like splitdata + ',%'

The text passed to the function in the SQL statement above is the text entered by the user.


问:
EC2 Instance Types with Fastest Download Speed
I'm looking for the most appropriate EC2 Instance Type to download large files at a fast rate. There are several options of Network performances, and I'm leaning towards "Up to 10 Gigabit" or "10 Gigabit". Is there a recommended Model with this networking performance options that best fit the requirement? Would it be possible to download 4~6GB files in under an hour?</p>

答:
There are a number of factors outside of AWS control which could potentially mean that you don't get the files in the amount of time you need it in. Some of these include:

Server on the other side has poor upload speed

Bad routing

Internet backbone latency issues (can happen)

Attempting to download from geographically far distances

Existing network traffic to the instance

The instance availability zone is down

Amount of security group and NACL rules (increases processing time of individual packets)

Assuming none of these are issues you won't have trouble getting large files downloaded. For getting data to AWS at a decent speed from an on site location you can also look into DirectConnect which helps on the routing front. For when you get into the petabyte+ level of data transfer there's also Snowball and Snowmobile which is physical shipping of the data to AWS for loading into servers.


问:
How to import all provided Wildfly libraries in my maven project?
Is there a way to translate this human language in an xml codeblock that Maven will happily understand?

Hey Maven, look you are a great dependency management system. I am working on a JavaEE project which is intended to be deployed on Wildfly 10.1.0. Please put all Libraries that are specified in Wildflys parent BOM http://repo1.maven.org/maven2/org/wildfly/wildfly-parent/10.1.0.Final/wildfly-parent-10.1.0.Final.pom on the compiletime classpath and consider them as provided by Wildfly at runtime. And please dont bother me to list every single referenced artifact in the dependencies section of the projects pom file. Thank you Maven, you are so cool.

To clarify:
As far as I understand, importing the bom file in the dependencyManagement section of my pom file will only spare me to specify the Version Number of every single artifact, but I will still have to declare every artifactID and groupID.

This is indeed discussed here How to use BOM file with Maven
But in this answer is also stated:

Then you do not have to specify the version attribute of a dependency.

I would prefer to declare only that I am using wildfly and then be able to use all client libraries without declaring any other dependencies.

But I must admit, I have the feeling to miss something obvious. There should be an easy way to do this.

答:
If you want everything in a another pom to be set as a dependency and as provided you can specify that in your pom. A minimal pom for wildfly 10.1.0.Final that includes everything seems to be as follows:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>wft</groupId>
    <artifactId>wft</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>wft</name>
    <description>wft</description>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.wildfly</groupId>
            <artifactId>wildfly-spec-api</artifactId>
            <version>10.1.0.Final</version>
            <type>pom</type>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>
</code>```

But I would still recommend doing it the way that wildfly does it themselves, which is to put the BOM in the depencency management section and declare artifacts as you need them. Why? I don't know other than it's cleaner to read and maybe easier for maven/java to compile and build.

Body:
If you want everything in a another pom to be set as a dependency and as provided you can specify that in your pom. A minimal pom for wildfly 10.1.0.Final that includes everything seems to be as follows:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>wft</groupId>
    <artifactId>wft</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>wft</name>
    <description>wft</description>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.wildfly</groupId>
            <artifactId>wildfly-spec-api</artifactId>
            <version>10.1.0.Final</version>
            <type>pom</type>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>

But I would still recommend doing it the way that wildfly does it themselves, which is to put the BOM in the depencency management section and declare artifacts as you need them. Why? I don't know other than it's cleaner to read and maybe easier for maven/java to compile and build.


问:
how to prevent calling virtual function in constructor or desturctor?
Some C++ materials mention we can't call a virtual function inside ctor or dtor,

(

sorry ,I think it's better to change to

Some C++ materials mention we'd better not to  call a virtual function inside ctor or dtor,

)

but we may call them accidentally. Is there any way to prevent that?

For example:

```<code># include < iostream >
using namespace std;

class CAT
{
public:
    CAT(){ f();}
    virtual void f(){cout<<"void CAT:f()"<<std::endl;}
};

class SMALLCAT :public CAT
{
public:
    SMALLCAT():CAT()
    {
    }
    void f(){cout<<"void SMALLCAT:f()"<<std::endl;}
};

int main()
{
    SMALLCAT sc;

}
</code>```

output:

```<code>void CAT::f()  //not we expected!!!
</code>```

Thanks

答: You can call a virtual function inside a destructor.  Only in certain cases it won't work, and may crash your program.  The way to avoid calling them is to not call them.  There's nothing fancier I know of, other than possibly some static analysis tools to look at your code and warn you of potential problems like this.</p>

Body:
Some C++ materials mention we can't call a virtual function inside ctor or dtor,

(

sorry ,I think it's better to change to

Some C++ materials mention we'd better not to  call a virtual function inside ctor or dtor,

)

but we may call them accidentally. Is there any way to prevent that?

For example:

# include < iostream >
using namespace std;

class CAT
{
public:
    CAT(){ f();}
    virtual void f(){cout<<"void CAT:f()"<<std::endl;}
};

class SMALLCAT :public CAT
{
public:
    SMALLCAT():CAT()
    {
    }
    void f(){cout<<"void SMALLCAT:f()"<<std::endl;}
};

int main()
{
    SMALLCAT sc;

}

output:

void CAT::f()  //not we expected!!!

Thanks


问:
Is method without async returning value using Task.Run a bad practice?
I don't see this patter used very often so it makes me wonder is there something wrong with the following approach?

```<code>class Program
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 100; i++)
        {
            Console.WriteLine(GetText());
        }
    }

    public static string GetText()
    {
        string result = "";
        Task.Run(() => result = Environment.TickCount.ToString()).Wait();
        return result;
    }
}
</code>```

Also, could someone please explain why I get a "not all paths return value" compiler error with:

```<code>    public static string GetText()
    {
        Task.Run(() => { return Environment.TickCount.ToString();  }).Wait();
    }
</code>```

答:
The reason you don't see this pattern very often is because it does nothing. You are creating tasks to run on separate threads, but you are also immediately asking your main thread to wait for the other thread to finish. There's no value there. The point of multi-threading is for the calling thread to keep going while the other threads do other work.

For your 2nd question: Your return statement exists within the lambda you provided (a lambda is the () => {} notation). When you call Task.Run, you are telling the compiler "Start a new thread and when the thread is ready to go, execute the code I'm about to give you". The lambda is the code that should execute in the other thread. It doesn't get executed in the thread that called Task.Run. As far as GetText() is concerned, you never called return, and you never returned a value. This is why the compiler is telling you there's a problem.

Body:
I don't see this patter used very often so it makes me wonder is there something wrong with the following approach?

class Program
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 100; i++)
        {
            Console.WriteLine(GetText());
        }
    }

    public static string GetText()
    {
        string result = "";
        Task.Run(() => result = Environment.TickCount.ToString()).Wait();
        return result;
    }
}

Also, could someone please explain why I get a "not all paths return value" compiler error with:

    public static string GetText()
    {
        Task.Run(() => { return Environment.TickCount.ToString();  }).Wait();
    }


问:
Dynamic Class Choice Via ENV variable
I have a Base class that has some basic functionality and some helper methods. I want to extend from this class different methods, more than 10. So I would have class Foo extends Base and class Bar extends Base and so on. Now as far as calling this methods, the applications runs only 1 of these extensions depending on the environment, so for example on production new Foo() gets called and on development new Bar() gets called.

I have some basic functionality on these but I'm afraid it won't scale and/or it's not the best way to do things. I have an ENV variable called CLASS_LOAD='bar'. This is my code and how I'm doing it so far:

```<code>class Base {
    //
}

class Foo extends Base {
    //
}

class Bar extends Base {
    //
}

class ClassLoader {
    public static function init() {
        switch (getenv('CLASS_LOAD')) {
            case 'bar':
                return new Bar();
            case 'foo':
                return new Foo();
            default:
                throw new Exception();
        }
    }
}
</code>```

And the way I call this in my application is:

```<code>$class = ClassLoader::init();
</code>```

This works fine for now I guess but I will have to keep updating the ClassLoader class every time I add a new extension of the Base class. And possibly in the future that switch-case statement will become unbearably large.

Can I be doing something else?
Any ideas?

Thanks

答:
I think you should try this approach that will no longer require switch statements and you don't have to panic anymore.

```<code>class ClassLoader{
     public static function init() {
      $class = getenv('CLASS_LOAD');
      if(class_exsists($class))
       return new $class;
      else
       throw new Exception("class not found");
  }
}
</code>```

Now call it.

Title: Dynamic Class Choice Via ENV variable

Body:
I have a Base class that has some basic functionality and some helper methods. I want to extend from this class different methods, more than 10. So I would have class Foo extends Base and class Bar extends Base and so on. Now as far as calling this methods, the applications runs only 1 of these extensions depending on the environment, so for example on production new Foo() gets called and on development new Bar() gets called.

I have some basic functionality on these but I'm afraid it won't scale and/or it's not the best way to do things. I have an ENV variable called CLASS_LOAD='bar'. This is my code and how I'm doing it so far:

class Base {
    //
}

class Foo extends Base {
    //
}

class Bar extends Base {
    //
}

class ClassLoader {
    public static function init() {
        switch (getenv('CLASS_LOAD')) {
            case 'bar':
                return new Bar();
            case 'foo':
                return new Foo();
            default:
                throw new Exception();
        }
    }
}

And the way I call this in my application is:

$class = ClassLoader::init();

This works fine for now I guess but I will have to keep updating the ClassLoader class every time I add a new extension of the Base class. And possibly in the future that switch-case statement will become unbearably large.

Can I be doing something else?
Any ideas?

Thanks

Body:
I think you should try this approach that will no longer require switch statements and you don't have to panic anymore.

class ClassLoader{
     public static function init() {
      $class = getenv('CLASS_LOAD');
      if(class_exsists($class))
       return new $class;
      else
       throw new Exception("class not found");
  }
}

Now call it.


问:
Splitting up text file into pieces, then searching key phrases in those sections
I am new to Python and I am already a fan of the language. I have a program that does the following:

Opens a text file that has sections of text separated by asterisks (***)

Uses the split() function to split up this text file into sections separated by these asterisks. The line of asterisks is uniform across the text file.

I want my code to iterate through each of these sections and do the following:

I have a dictionary with "key phrases" assigned to values. The value of each key in the dictionary is 0.

The code needs to iterate through each section created from the split and check to see if the keys in the dictionary are found in each section. If a key term is found, the value for that key increases by 1.

Once the code iterates through one section and has counted how many of the keys are in the section and added values accordingly, it should print out dictionary keys and the counts (values) for that setting, set the values to 0, and move on to the next section of text starting at #3 again.

My code is:

```<code>    from bs4 import BeautifulSoup
   import re
   import time
   import random
   import glob, os
   import string

termz = {'does not exceed' : 0, 'shall not exceed' : 0, 'not exceeding' : 0,
  'do not exceed' : 0, 'not to exceed' : 0, 'shall at no time exceed' : 0,
  'shall not be less than' : 0, 'not less than' : 0}
with open('Q:/hello/place/textfile.txt', 'r') as f:
  sections = f.read().split('**************************************************')
  for p in sections[1:]:
      for eachKey in termz.keys():
        if eachKey in p:
          termz[eachKey] = termz.get(eachKey) + 1
          print(termz)

#print(len(sections))  #there are thirty sections

        #should be if code encounters ***** then it resets the counters and just moves on....
        #so far only can count the phrases over the entire text file....

#GO BACK TO .SPLIT()
# termz = dict.fromkeys(termz,0) #resets the counter
</code>```

It spits out what it counts but it isn't the first, last, or even the entire file it's tracing - I don't know what it is doing.

The print statement at the end is out of place. The termz = dict.fromkeys(termz,0) line is a method I found to reset the values of the dictionary to 0, but is commented out because I'm not sure how to approach this. Essentially, struggling with Python control structures. If someone could point me in the right direction, that'd be amazing.

答:
```<code>if eachKey in p:
          termz[eachKey] += 1  # might do it
          print(termz)
</code>```

Body:
I am new to Python and I am already a fan of the language. I have a program that does the following:

Opens a text file that has sections of text separated by asterisks (***)

Uses the split() function to split up this text file into sections separated by these asterisks. The line of asterisks is uniform across the text file.

I want my code to iterate through each of these sections and do the following:

I have a dictionary with "key phrases" assigned to values. The value of each key in the dictionary is 0.

The code needs to iterate through each section created from the split and check to see if the keys in the dictionary are found in each section. If a key term is found, the value for that key increases by 1.

Once the code iterates through one section and has counted how many of the keys are in the section and added values accordingly, it should print out dictionary keys and the counts (values) for that setting, set the values to 0, and move on to the next section of text starting at #3 again.

My code is:

    from bs4 import BeautifulSoup
   import re
   import time
   import random
   import glob, os
   import string

termz = {'does not exceed' : 0, 'shall not exceed' : 0, 'not exceeding' : 0,
  'do not exceed' : 0, 'not to exceed' : 0, 'shall at no time exceed' : 0,
  'shall not be less than' : 0, 'not less than' : 0}
with open('Q:/hello/place/textfile.txt', 'r') as f:
  sections = f.read().split('**************************************************')
  for p in sections[1:]:
      for eachKey in termz.keys():
        if eachKey in p:
          termz[eachKey] = termz.get(eachKey) + 1
          print(termz)

#print(len(sections))  #there are thirty sections

        #should be if code encounters ***** then it resets the counters and just moves on....
        #so far only can count the phrases over the entire text file....

#GO BACK TO .SPLIT()
# termz = dict.fromkeys(termz,0) #resets the counter

It spits out what it counts but it isn't the first, last, or even the entire file it's tracing - I don't know what it is doing.

The print statement at the end is out of place. The termz = dict.fromkeys(termz,0) line is a method I found to reset the values of the dictionary to 0, but is commented out because I'm not sure how to approach this. Essentially, struggling with Python control structures. If someone could point me in the right direction, that'd be amazing.


问:
Export last trial from C5.0 model
I am trying to export a model built by c50 package in R.

I'm using the partykit package for extract the last trial, but it doesn't return the same fitting value.

I'dont understand why the as.party.c5.0 function doesn't fit exactly the same way as the C5.0 function does. it works for the first trial but not for the other ones.

For example :

```<code>poc_db<-iris
fullTree_prun_iris_Winow <- C5.0(Species ~ ., data =poc_db, trials = 10,control = C5.0Control(CF = 0.90,noGlobalPruning = FALSE,winnow = T))

cat(fullTree_prun_iris_Winow$output)
-----  Trial 9:  -----
Decision tree:
Petal.Width <= 0.6: setosa (10.5)
Petal.Width > 0.6:
:...Petal.Width <= 1.7: versicolor (116.3/49.4)
    Petal.Width > 1.7: virginica (22.2)

modParty <- C50:::as.party.C5.0(fullTree_prun_iris_Winow,trial=10)
Fitted party:
[1] root
|   [2] Petal.Width <= 0.6: setosa (n = 50, err = 0.0%)
|   [3] Petal.Width > 0.6
|   |   [4] Petal.Width <= 1.7: versicolor (n = 54, err = 9.3%)
|   |   [5] Petal.Width > 1.7: virginica (n = 46, err = 2.2%)
</code>```

We should have for the 4th node : ... versicolor(116/49)

Thanks for help

答:
The fourth node has 54 observations, and 49 of these are versicolor. See

```<code>table(subset(poc_db, Petal.Width > 0.6 & Petal.Width <= 1.7)$Species)
##     setosa versicolor  virginica
##          0         49          5
</code>```

Hence, partykit reports n = 54 and err = 9.3% corresponding to 5/54. The value reported by C5.0 is different because it comes from boosting the trees over several trials rather than just using a single tree by itself.

Title: Export last trial from C5.0 model

Body:
I am trying to export a model built by c50 package in R.

I'm using the partykit package for extract the last trial, but it doesn't return the same fitting value.

I'dont understand why the as.party.c5.0 function doesn't fit exactly the same way as the C5.0 function does. it works for the first trial but not for the other ones.

For example :

poc_db<-iris
fullTree_prun_iris_Winow <- C5.0(Species ~ ., data =poc_db, trials = 10,control = C5.0Control(CF = 0.90,noGlobalPruning = FALSE,winnow = T))

cat(fullTree_prun_iris_Winow$output)
-----  Trial 9:  -----
Decision tree:
Petal.Width <= 0.6: setosa (10.5)
Petal.Width > 0.6:
:...Petal.Width <= 1.7: versicolor (116.3/49.4)
    Petal.Width > 1.7: virginica (22.2)

modParty <- C50:::as.party.C5.0(fullTree_prun_iris_Winow,trial=10)
Fitted party:
[1] root
|   [2] Petal.Width <= 0.6: setosa (n = 50, err = 0.0%)
|   [3] Petal.Width > 0.6
|   |   [4] Petal.Width <= 1.7: versicolor (n = 54, err = 9.3%)
|   |   [5] Petal.Width > 1.7: virginica (n = 46, err = 2.2%)

We should have for the 4th node : ... versicolor(116/49)

Thanks for help

Body:
The fourth node has 54 observations, and 49 of these are versicolor. See

table(subset(poc_db, Petal.Width > 0.6 & Petal.Width <= 1.7)$Species)
##     setosa versicolor  virginica
##          0         49          5

Hence, partykit reports n = 54 and err = 9.3% corresponding to 5/54. The value reported by C5.0 is different because it comes from boosting the trees over several trials rather than just using a single tree by itself.


问:
No value and no error from event handler
Whenever I press the ESC key (anywhere on my desktop), I would like to print a message.

This is what I have so far:

```<code>from msvcrt import getch
while True:
    key = ord(getch())
    if key == 27:
        print('Key pressed.')
</code>```

When I run this code and hit ESC, I get nothing - not even an error. Why?

print(key) keeps giving me 255 repeatedly, even if I press nothing.

答:
Your code works just fine if you open the script through the console (double click on the file, not with IDLE).

You want a low-level keyboard hook. This simply listens to the keypresses made to the console, not anywhere else.

Body:
Whenever I press the ESC key (anywhere on my desktop), I would like to print a message.

This is what I have so far:

from msvcrt import getch
while True:
    key = ord(getch())
    if key == 27:
        print('Key pressed.')

When I run this code and hit ESC, I get nothing - not even an error. Why?

print(key) keeps giving me 255 repeatedly, even if I press nothing.


问:
combox box error
```<code>private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox Combo_Design = new ComboBox();
        Combo_Quality.Items.Add("Best");
        Combo_Quality.Items.Add("Normal");
        Combo_Quality.Items.Add("Draft");

        Combo_Quality.Text = "Best";

        MessageBox.Show(Combo_Quality.Text);

        string selectedItem = Combo_Quality.Items[Combo_Quality.SelectedIndex].ToString();

        Combo_Quality.Text = "Normal";

        MessageBox.Show(Combo_Quality.Text);

        string selectedItem2 = Combo_Quality.Items[Combo_Quality.SelectedIndex].ToString();

        Combo_Quality.Text = "Draft";

        MessageBox.Show(Combo_Quality.Text);

        string selectedItem3 = Combo_Quality.Items[Combo_Quality.SelectedIndex].ToString();

    }
</code>```

This relates to combo box, i have 3 items to select but i want it to be when i choose best a message box to pops out and let me select ok and same goes to normal and draf

答:
If you want it to alert the selected text, you could:

```<code>MessageBox.Show(Combo_Quality.SelectedItem.ToString());
</code>```

if you want to confirm and allow the user to cancel his selection look into this question:
How to prevent/cancel a combobox's value change in c#?

Title: combox box error

Body:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox Combo_Design = new ComboBox();
        Combo_Quality.Items.Add("Best");
        Combo_Quality.Items.Add("Normal");
        Combo_Quality.Items.Add("Draft");

        Combo_Quality.Text = "Best";

        MessageBox.Show(Combo_Quality.Text);

        string selectedItem = Combo_Quality.Items[Combo_Quality.SelectedIndex].ToString();

        Combo_Quality.Text = "Normal";

        MessageBox.Show(Combo_Quality.Text);

        string selectedItem2 = Combo_Quality.Items[Combo_Quality.SelectedIndex].ToString();

        Combo_Quality.Text = "Draft";

        MessageBox.Show(Combo_Quality.Text);

        string selectedItem3 = Combo_Quality.Items[Combo_Quality.SelectedIndex].ToString();

    }

This relates to combo box, i have 3 items to select but i want it to be when i choose best a message box to pops out and let me select ok and same goes to normal and draf

Body:
If you want it to alert the selected text, you could:

MessageBox.Show(Combo_Quality.SelectedItem.ToString());

if you want to confirm and allow the user to cancel his selection look into this question:
How to prevent/cancel a combobox's value change in c#?


问:
Rearranging multiple rows of a dataframe on big data in R
I am relatively new in R. I have a dataframe test that looks like this:

```<code>PMID    # id
LID
STAT
MH
RN
OT
PST     # cue
LID
STAT
MH
PMID    # id
OT
PST     # cue
LID
DEP
RN
PMID    # id
PST     # cue
</code>```

and I want it to look like this:

```<code>PMID    # id
LID
STAT
MH
RN
OT
PST     # cue
PMID    # id
LID
STAT
MH
OT
PST     # cue
PMID    # id
LID
DEP
RN
PST     # cue
</code>```

Basically, I want the entries that follow PMID to be for that particular PMID, which is the case for the first PMID. However, after the first PMID, the PMID is nestled randomly in between its entries. However, each PMID ends with a PST, so I want the subsequent PMIDs after the first one to be moved to the location after the previous PST's location. I have two dataframes that contain the index location of each PMID and of PST. So for instance, for PMID, df a_new contains

```<code>1
11
17
</code>```

and for PST, df b contains

```<code>7
13
18
</code>```

This is what I have tried, but because I have over 24 million rows, it didn't finish running after hours and when I stopped it, my dataframe had not changed:

```<code>for (i in 1:nrow(test))
{
  if (i %in% a_new$X1) # if it's a PMID
  {
    entry <- match(i, a_new$X1) # find entry index of PMID
    if (entry != 1) # as long as not first row from a_new (that's corrected)
    {
      r <- b[i, 1] # row of PST
      test <- rbind(test[1:r, ], test[entry, 1], test[-(1:r), ])
      test <- test[-c(i+1), ] # remove duplicate PMID
    }
  }
}
</code>```

As you can see, rbind would be extremely inefficient in this situation. Please advise.

答:
Here is an indexing method using which.

```<code># get positions of PST, the final value
endSpot <- which(temp == "PST")
# increment to get the desired positions of the PMID
# (dropping final value as we don't need to change it)
startSpot <- head(endSpot + 1, -1)
# get the current positions of the PMID, except the first one
PMIDSpot <- tail(which(temp == "PMID"), -1)
</code>```

Now, use these indices to swap rows

```<code>temp[c(startSpot, PMIDSpot), ] <- temp[c(PMIDSpot, startSpot), ]
</code>```

This returns (I added a row position variable called count to keep track).

```<code>temp
     V1 count
1  PMID     1
2   LID     2
3  STAT     3
4    MH     4
5    RN     5
6    OT     6
7   PST     7
8  PMID    11
9  STAT     9
10   MH    10
11  LID     8
12   OT    12
13  PST    13
14 PMID    17
15  DEP    15
16   RN    16
17  LID    14
18  PST    18
</code>```

data

```<code>temp <-
structure(list(V1 = c("PMID", "LID", "STAT", "MH", "RN", "OT",
"PST", "LID", "STAT", "MH", "PMID", "OT", "PST", "LID", "DEP",
"RN", "PMID", "PST"), count = 1:18), .Names = c("V1", "count"
), row.names = c(NA, -18L), class = "data.frame")
</code>```

Body:
I am relatively new in R. I have a dataframe test that looks like this:

PMID    # id
LID
STAT
MH
RN
OT
PST     # cue
LID
STAT
MH
PMID    # id
OT
PST     # cue
LID
DEP
RN
PMID    # id
PST     # cue

and I want it to look like this:

PMID    # id
LID
STAT
MH
RN
OT
PST     # cue
PMID    # id
LID
STAT
MH
OT
PST     # cue
PMID    # id
LID
DEP
RN
PST     # cue

Basically, I want the entries that follow PMID to be for that particular PMID, which is the case for the first PMID. However, after the first PMID, the PMID is nestled randomly in between its entries. However, each PMID ends with a PST, so I want the subsequent PMIDs after the first one to be moved to the location after the previous PST's location. I have two dataframes that contain the index location of each PMID and of PST. So for instance, for PMID, df a_new contains

1
11
17

and for PST, df b contains

7
13
18

This is what I have tried, but because I have over 24 million rows, it didn't finish running after hours and when I stopped it, my dataframe had not changed:

for (i in 1:nrow(test))
{
  if (i %in% a_new$X1) # if it's a PMID
  {
    entry <- match(i, a_new$X1) # find entry index of PMID
    if (entry != 1) # as long as not first row from a_new (that's corrected)
    {
      r <- b[i, 1] # row of PST
      test <- rbind(test[1:r, ], test[entry, 1], test[-(1:r), ])
      test <- test[-c(i+1), ] # remove duplicate PMID
    }
  }
}

As you can see, rbind would be extremely inefficient in this situation. Please advise.

Body:
Here is an indexing method using which.

# get positions of PST, the final value
endSpot <- which(temp == "PST")
# increment to get the desired positions of the PMID
# (dropping final value as we don't need to change it)
startSpot <- head(endSpot + 1, -1)
# get the current positions of the PMID, except the first one
PMIDSpot <- tail(which(temp == "PMID"), -1)

Now, use these indices to swap rows

temp[c(startSpot, PMIDSpot), ] <- temp[c(PMIDSpot, startSpot), ]

This returns (I added a row position variable called count to keep track).

temp
     V1 count
1  PMID     1
2   LID     2
3  STAT     3
4    MH     4
5    RN     5
6    OT     6
7   PST     7
8  PMID    11
9  STAT     9
10   MH    10
11  LID     8
12   OT    12
13  PST    13
14 PMID    17
15  DEP    15
16   RN    16
17  LID    14
18  PST    18

data

temp <-
structure(list(V1 = c("PMID", "LID", "STAT", "MH", "RN", "OT",
"PST", "LID", "STAT", "MH", "PMID", "OT", "PST", "LID", "DEP",
"RN", "PMID", "PST"), count = 1:18), .Names = c("V1", "count"
), row.names = c(NA, -18L), class = "data.frame")


问:
Laravel input validation, alphanumeric but don't allow spaces
I have a field in a form which accepts a username. I need to use Laravels validation to validate the username but I'm struggling to come up with a solution which allows both alpha and numeric characters, but does not allow spaces in the username.

My Current validator looks like this;

```<code>$validatorFields = [
            'name' => 'required|string|max:150|regex:/^[A-Za-z0-9\-\s]+$/'
        ];
</code>```

Can anyone suggest how to do this please?

答:
You could use alpha_num The field under validation must be entirely alpha-numeric characters. Does not allow spaces as well.
Example:</p>

```<code>$validatorFields = [
  'name' => 'required|string|max:150|alpha_num'
];
</code>```

Body:
I have a field in a form which accepts a username. I need to use Laravels validation to validate the username but I'm struggling to come up with a solution which allows both alpha and numeric characters, but does not allow spaces in the username.

My Current validator looks like this;

$validatorFields = [
            'name' => 'required|string|max:150|regex:/^[A-Za-z0-9\-\s]+$/'
        ];

Can anyone suggest how to do this please?

Body:
You could use alpha_num The field under validation must be entirely alpha-numeric characters. Does not allow spaces as well.
Example:

$validatorFields = [
  'name' => 'required|string|max:150|alpha_num'
];

ContentLicense: CC BY-SA 4.0