问:
I can't browse the pages Beautifulsoup
I am a beginner in Web-scraping and I am following this tutorial to extract movie data from this link, I chose to extract movies between 2016 and 2019 for the test. I get just 25 lines but I want more than 30000.
Do you think it's possible ?

this is the code :

```<code>from requests import get
from bs4 import BeautifulSoup
import csv
import pandas as pd
from time import sleep
from random import randint
from time import time
from IPython.core.display import clear_output

headers = {"Accept-Language": "en-US, en;q=0.5"}

pages = [str(i) for i in range(1,5)]
years_url = [str(i) for i in range(2000,2018)]

url = 'https://www.imdb.com/search/title?release_date=2016-01-01,2019-05-01'
response = get(url)
html_soup = BeautifulSoup(response.text, 'html.parser')
type(html_soup)

movie_containers = html_soup.find_all('div', class_ = 'lister-item mode-advanced')

names = []
years = []
imdb_ratings = []
metascores = []
votes = []
start_time = time()
requests = 0

for year_url in years_url:
# For every page in the interval 1-4
   for page in pages:
# Make a get request
      response = get('http://www.imdb.com/search/title?release_date=' + year_url +'&sort=num_votes,desc&page=' + page, headers = headers)
# Pause the loop
      sleep(randint(8,15))
# Monitor the requests
      requests += 1
      elapsed_time = time() - start_time
 print('Request:{}; Frequency: {} requests/s'.format(requests, requests/elapsed_time))
clear_output(wait = True)
# Throw a warning for non-200 status codes
if response.status_code != 200:
  warn('Request: {}; Status code: {}'.format(requests, response.status_code))
# Break the loop if the number of requests is greater than expected
  if requests > 72:
    warn('Number of requests was greater than expected.')

# Parse the content of the request with BeautifulSoup
page_html = BeautifulSoup(response.text, 'html.parser')
# Select all the 50 movie containers from a single page
mv_containers = page_html.find_all('div', class_ = 'lister-item mode-advanced')

# Extract data from individual movie container
for container in movie_containers:
# If the movie has Metascore, then extract:
  if container.find('div', class_ = 'ratings-metascore') is not None:
# The name
   name = container.h3.a.text
   names.append(name)
# The year
   year = container.h3.find('span', class_ = 'lister-item-year').text
   years.append(year)
# The IMDB rating
   imdb = float(container.strong.text)
   imdb_ratings.append(imdb)
# The Metascore
   m_score = container.find('span', class_ = 'metascore').text
   metascores.append(int(m_score))
# The number of votes
   vote = container.find('span', attrs = {'name':'nv'})['data-value']
   votes.append(int(vote))

   movie_ratings = pd.DataFrame({'movie': names,
  'year': years,
  'imdb': imdb_ratings,
  'metascore': metascores,
  'votes': votes
  })

#data cleansing
movie_ratings = movie_ratings[['movie', 'year', 'imdb', 'metascore', 'votes']]
movie_ratings.head()
movie_ratings['year'].unique()
movie_ratings.to_csv('movie_ratings.csv')
</code>```

答:
It's hard to tell exactly what the issue is here because of the lack of functions but from what I see, you need to parse each page separately.

After every request, you need to parse the text. However, I suspect the main issue is the ordering of your code, I would suggest using functions.

Title: I can't browse the pages Beautifulsoup

Body:
I am a beginner in Web-scraping and I am following this tutorial to extract movie data from this link, I chose to extract movies between 2016 and 2019 for the test. I get just 25 lines but I want more than 30000.
Do you think it's possible ?

this is the code :

from requests import get
from bs4 import BeautifulSoup
import csv
import pandas as pd
from time import sleep
from random import randint
from time import time
from IPython.core.display import clear_output

headers = {"Accept-Language": "en-US, en;q=0.5"}

pages = [str(i) for i in range(1,5)]
years_url = [str(i) for i in range(2000,2018)]

url = 'https://www.imdb.com/search/title?release_date=2016-01-01,2019-05-01'
response = get(url)
html_soup = BeautifulSoup(response.text, 'html.parser')
type(html_soup)

movie_containers = html_soup.find_all('div', class_ = 'lister-item mode-advanced')

names = []
years = []
imdb_ratings = []
metascores = []
votes = []
start_time = time()
requests = 0

for year_url in years_url:
# For every page in the interval 1-4
   for page in pages:
# Make a get request
      response = get('http://www.imdb.com/search/title?release_date=' + year_url +'&sort=num_votes,desc&page=' + page, headers = headers)
# Pause the loop
      sleep(randint(8,15))
# Monitor the requests
      requests += 1
      elapsed_time = time() - start_time
 print('Request:{}; Frequency: {} requests/s'.format(requests, requests/elapsed_time))
clear_output(wait = True)
# Throw a warning for non-200 status codes
if response.status_code != 200:
  warn('Request: {}; Status code: {}'.format(requests, response.status_code))
# Break the loop if the number of requests is greater than expected
  if requests > 72:
    warn('Number of requests was greater than expected.')

# Parse the content of the request with BeautifulSoup
page_html = BeautifulSoup(response.text, 'html.parser')
# Select all the 50 movie containers from a single page
mv_containers = page_html.find_all('div', class_ = 'lister-item mode-advanced')

# Extract data from individual movie container
for container in movie_containers:
# If the movie has Metascore, then extract:
  if container.find('div', class_ = 'ratings-metascore') is not None:
# The name
   name = container.h3.a.text
   names.append(name)
# The year
   year = container.h3.find('span', class_ = 'lister-item-year').text
   years.append(year)
# The IMDB rating
   imdb = float(container.strong.text)
   imdb_ratings.append(imdb)
# The Metascore
   m_score = container.find('span', class_ = 'metascore').text
   metascores.append(int(m_score))
# The number of votes
   vote = container.find('span', attrs = {'name':'nv'})['data-value']
   votes.append(int(vote))

   movie_ratings = pd.DataFrame({'movie': names,
  'year': years,
  'imdb': imdb_ratings,
  'metascore': metascores,
  'votes': votes
  })

#data cleansing
movie_ratings = movie_ratings[['movie', 'year', 'imdb', 'metascore', 'votes']]
movie_ratings.head()
movie_ratings['year'].unique()
movie_ratings.to_csv('movie_ratings.csv')


来源: stackexchange

问:
How to set a 2D index in Play Morphia?
How do I set a 2D index in play morphia?

Example:

```<code>db.places.ensureIndex( { loc : "2d" } )
</code>```

http://www.mongodb.org/display/DOCS/Geospatial+Indexing

答:
Just to add to this, years later:

```<code>@Indexes(
        @Index(fields=@Field( value = "location", type= IndexType.GEO2DSPHERE))
)
</code>```

on the @Entity class (if the member holding the GeoPoint is called location) generates the correct indices for spherical geospatial queries.

Don't forget to set the 4th param of the .near() method to true (spherical).

Also you should ensure the indices were generated by simply calling datastore.ensureIndexes() before querying.

ContentLicense: CC BY-SA 3.0

Title: How to set a 2D index in Play Morphia?

Body:
How do I set a 2D index in play morphia?

Example:

db.places.ensureIndex( { loc : "2d" } )

http://www.mongodb.org/display/DOCS/Geospatial+Indexing

Body:
Just to add to this, years later:

@Indexes(
        @Index(fields=@Field( value = "location", type= IndexType.GEO2DSPHERE))
)

on the @Entity class (if the member holding the GeoPoint is called location) generates the correct indices for spherical geospatial queries.

Don't forget to set the 4th param of the .near() method to true (spherical).

Also you should ensure the indices were generated by simply calling datastore.ensureIndexes() before querying.

ContentLicense: CC BY-SA 4.0


问:
Import custom-font in Laravel DOMPDF 0.8.3 / Laravel 5.8
I try to import my custom-font VAGRounded_BT.ttf in Laravel Dompdf. I've changed the directory in the config/dompdf.php, also the font_cache to public/fonts/. But I'm not able to display the font in my PDF.

Several offered solutions in the internet doesn't help me. I can't find the problem, respectively the way how to import my font. I tried different fonts like Lato or Roboto, but always the same.

Changes in the config/dompdf.php

        "font_dir" => storage_path('public/fonts/'),

        "font_cache" => storage_path('public/fonts/'),
```

<p>The controller function:</p>

<pre class="lang-php prettyprint-override"><code>    public function deliveryDetailsPDF($delivery_id){

        $header   = Delivery::where('id',$delivery_id)->first();
        $details  = Delivery::getDeliveryDetails($delivery_id);

        $pdf = \PDF::setOptions([
                      'isHtml5ParserEnabled'=> true,
                      'isRemoteEnabled' => true,
                    ])
                    ->loadView('delivery.pdf',compact('header','details'))
                    ->stream();

        return $pdf;
    }
</code>```

Style block in the header of the Blade file delivery/pdf.blade.php:

```

In the generated PDF is still Arial used.
How could I reach my goal?

Thank you in advance.

答:
You'll need to be a bit more explicit in your @font-face declaration. Try the following:

```<code>@font-face{
    font-family: VAGBlack;
    src: url('/fonts/VAGRounded_BT.ttf') format('truetype');
    font-weight: bold;
    font-style: normal;
}
</code>```

I specified a bold font weight because that is how h1 and h2 elements are styled. If you don't specify the weight and style:

I'm not sure Dompdf would register the font.

Even if Dompdf did register the font it wouldn't use it on the H1 and H2 elements since it's not registered for use with bold text.

Body:
I try to import my custom-font VAGRounded_BT.ttf in Laravel Dompdf. I've changed the directory in the config/dompdf.php, also the font_cache to public/fonts/. But I'm not able to display the font in my PDF.

Several offered solutions in the internet doesn't help me. I can't find the problem, respectively the way how to import my font. I tried different fonts like Lato or Roboto, but always the same.

Changes in the config/dompdf.php

        "font_dir" => storage_path('public/fonts/'),

        "font_cache" => storage_path('public/fonts/'),

The controller function:

    public function deliveryDetailsPDF($delivery_id){

        $header   = Delivery::where('id',$delivery_id)->first();
        $details  = Delivery::getDeliveryDetails($delivery_id);

        $pdf = \PDF::setOptions([
                      'isHtml5ParserEnabled'=> true,
                      'isRemoteEnabled' => true,
                    ])
                    ->loadView('delivery.pdf',compact('header','details'))
                    ->stream();

        return $pdf;
    }

Style block in the header of the Blade file delivery/pdf.blade.php:

In the generated PDF is still Arial used.
How could I reach my goal?

Thank you in advance.

Body:
You'll need to be a bit more explicit in your @font-face declaration. Try the following:

@font-face{
    font-family: VAGBlack;
    src: url('/fonts/VAGRounded_BT.ttf') format('truetype');
    font-weight: bold;
    font-style: normal;
}

I specified a bold font weight because that is how h1 and h2 elements are styled. If you don't specify the weight and style:

I'm not sure Dompdf would register the font.

Even if Dompdf did register the font it wouldn't use it on the H1 and H2 elements since it's not registered for use with bold text.


问:
Avoid inheriting of parent's css effect
Hi I have
something
 this line of code and the jumbotron has some CSS effects something like

```<code>.jumbotron{
    background: url("image-url") no-repeat center center;
    -webkit-background-size: 100% 100%;
    -moz-background-size: 100% 100%;
    -o-background-size: 100% 100%;
    background-size: 100% 100%;
    background-size: cover;
    height: 78vh;
    filter: brightness(50%);
}
</code>```

but all I want is only the jumbotron's background image gets the CSS effects, not the nav tag. currently, the nav tag inherits thefilter: brigtness (50%), is there anyway only the background-image gets the effect?

答:
No, it's not possible. A filter will affect current element with all its contents (including children).

Therefore the way to go here is to move  outside of .jumbotron, wrap them in a common relative parent and render  above .jumbotron.

Proof of concept:

.relative {
  position: relative;
}
.relative > .absolute {
  position: absolute;
  width: 100%;
  top: 0;
  /* making it visible */
  background-color: rgba(255,255,255,.25);
  border-bottom: 1px solid white;
  color: white;
  padding: 1rem;
  box-sizing: border-box;
}

.jumbotron{
  background: url("https://picsum.photos/id/237/1024/540") no-repeat center center /cover;
  height: 78vh;
  filter: brightness(50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="relative">
  <div class="jumbotron"></div>
  <nav class="absolute">something</nav>
</div></code>```

Feel free to rename the classes and adjust to your particular needs.

Title: Avoid inheriting of parent's css effect

Body:
Hi I have
something
 this line of code and the jumbotron has some CSS effects something like

.jumbotron{
    background: url("image-url") no-repeat center center;
    -webkit-background-size: 100% 100%;
    -moz-background-size: 100% 100%;
    -o-background-size: 100% 100%;
    background-size: 100% 100%;
    background-size: cover;
    height: 78vh;
    filter: brightness(50%);
}

but all I want is only the jumbotron's background image gets the CSS effects, not the nav tag. currently, the nav tag inherits thefilter: brigtness (50%), is there anyway only the background-image gets the effect?

Body:
No, it's not possible. A filter will affect current element with all its contents (including children).

Therefore the way to go here is to move <nav> outside of .jumbotron, wrap them in a common relative parent and render <nav> above .jumbotron.

Proof of concept:

.relative {
  position: relative;
}
.relative > .absolute {
  position: absolute;
  width: 100%;
  top: 0;
  /* making it visible */
  background-color: rgba(255,255,255,.25);
  border-bottom: 1px solid white;
  color: white;
  padding: 1rem;
  box-sizing: border-box;
}

.jumbotron{
  background: url("https://picsum.photos/id/237/1024/540") no-repeat center center /cover;
  height: 78vh;
  filter: brightness(50%);
}

<div class="relative">
  <div class="jumbotron"></div>
  <nav class="absolute">something</nav>
</div>

Feel free to rename the classes and adjust to your particular needs.


问:
Override Equatable and Hashable in Swift
Is there a way to override Equatable of NSManagedObject?  I have a coredata dataset of 300k objects and I need to remove duplicates base on the object's business id.

```<code>// Coredata NSManagedObject
import Foundation
import CoreData

@objc(Business)
public class Business: NSManagedObject {

}
</code>```

override error message:

答:
NSManagedObject already declares that it conforms to both Equatable and Hashable. No need to add the : Equatable.

You need to override the associated methods directly in your Business class without using the extension.

Body:
Is there a way to override Equatable of NSManagedObject?  I have a coredata dataset of 300k objects and I need to remove duplicates base on the object's business id.

// Coredata NSManagedObject
import Foundation
import CoreData

@objc(Business)
public class Business: NSManagedObject {

}

override error message:


问:
How can I redirect after POST in Pyramid?
I'm trying to have my form submit to a route which will validate the data then redirect back to the original route.

For example:

User loads the page website.com/post

Form POSTs the data to website.com/post-save

User gets redirected back to website.com/post

Pyramid is giving me some troubles doing this.

Here's my slimmed down views.py

```<code>def _get_link_form(post_data):
    """ Returns the initialised form object """

    return LinkForm(post_data)

def home_page(request):

    form = _get_link_form(request.POST)
    return {'form' : form}

def save_post(request):
    """ form data is submitted here """"

    form = _get_link_form(request.POST)

    if not form.validate():
        return home_page(request, form)
</code>```

This is the code I've been playing around with. Not only does it not work, it also feels messy and hacked up. Surely there's a simpler way to 'redirect after-POST' in Pyramid?

答:
Your problem is most easily solved by simply POSTing to the same URL that your form is shown at, and simply redirecting the user away from the page when the POST is successful. That way until the form is successfully submitted you do not change URLs.

If you're just dying to POST to a different URL, then you need to save the data using sessions, since you're obviously handling the form data between requests.

Typically if you want to be able to handle errors in your forms you would use a session and flash messages. To do this you simply add a location for flash messages to appear in your base template and setup session support using something like pyramid_beaker.

Assuming your home page is setup at the 'home' named-route:

```<code>from pyramid.httpexceptions import HTTPFound

def myview(request):
    user = '<default user field value>'
    if 'submit' in request.POST:
        user = request.POST.get('user')
        # validate your form data
        if <form validates successfully>:
            request.session.flash('Form was submitted successfully.')

            url = request.route_url('home')
            return HTTPFound(location=url)
    return {
        # globals for rendering your form
        'user': user,
    }
</code>```

Notice how if the form fails to validate you use the same code you did to render the form originally, and only if it is successful do you redirect. This format can also handle populating the form with the values used in the submission, and default values.

You can loop through the flash messages in your template of choice using request.session.peek_flash() and request.session.pop_flash().

route_url supports mutating the query string on the generated url as well, if you want to flag your home page view to check the session data.

You can obviously just pass everything in the query string back to the home page, but that's a pretty big security vulnerability that sessions can help protect against.

Body:
I'm trying to have my form submit to a route which will validate the data then redirect back to the original route.

For example:

User loads the page website.com/post

Form POSTs the data to website.com/post-save

User gets redirected back to website.com/post

Pyramid is giving me some troubles doing this.

Here's my slimmed down views.py

def _get_link_form(post_data):
    """ Returns the initialised form object """

    return LinkForm(post_data)

def home_page(request):

    form = _get_link_form(request.POST)
    return {'form' : form}

def save_post(request):
    """ form data is submitted here """"

    form = _get_link_form(request.POST)

    if not form.validate():
        return home_page(request, form)

This is the code I've been playing around with. Not only does it not work, it also feels messy and hacked up. Surely there's a simpler way to 'redirect after-POST' in Pyramid?

Body:
Your problem is most easily solved by simply POSTing to the same URL that your form is shown at, and simply redirecting the user away from the page when the POST is successful. That way until the form is successfully submitted you do not change URLs.

If you're just dying to POST to a different URL, then you need to save the data using sessions, since you're obviously handling the form data between requests.

Typically if you want to be able to handle errors in your forms you would use a session and flash messages. To do this you simply add a location for flash messages to appear in your base template and setup session support using something like pyramid_beaker.

Assuming your home page is setup at the 'home' named-route:

from pyramid.httpexceptions import HTTPFound

def myview(request):
    user = '<default user field value>'
    if 'submit' in request.POST:
        user = request.POST.get('user')
        # validate your form data
        if <form validates successfully>:
            request.session.flash('Form was submitted successfully.')

            url = request.route_url('home')
            return HTTPFound(location=url)
    return {
        # globals for rendering your form
        'user': user,
    }

Notice how if the form fails to validate you use the same code you did to render the form originally, and only if it is successful do you redirect. This format can also handle populating the form with the values used in the submission, and default values.

You can loop through the flash messages in your template of choice using request.session.peek_flash() and request.session.pop_flash().

route_url supports mutating the query string on the generated url as well, if you want to flag your home page view to check the session data.

You can obviously just pass everything in the query string back to the home page, but that's a pretty big security vulnerability that sessions can help protect against.


问:
python pip - development mode with local dependencies
Background

I have two python projects. Project A and Project B.

Each project has its own virtual environment and its own setup.py.

Both projects are not pure py files and has "build" process like building extensions, generate source etc.

A is dependent on B (setup.py install_requires points on B).

Each project is built and published/distributed as a wheel to pypi on-premise repository.

pip install w/wo -e (development mode) of project A, nicely installs project B into project A venv site-packages.

So far everything is working nicely and "by the book".

Now, my story get complicated ...

I would like to develop the two projects together without having to publish B in order A to consume it.

As example, I would like to:

Change something in B.

build B (setup.py build).

NOT publish B as wheel to pypi.

Goal - Project A will "know" the modified Project B. WITHOUT manually tweaking sys.path.

I actually want the pip install -e of project A to install project B in development mode too.

After some reading I understood (hopefully correctly) that one can define a "distribution" as a local source folder by --find-links flag.

I defined project B root folder in --find-links.

I tried it with (on project A setup.py folder):

pip install . -e --find-links = file:///path/to/B

pip install . -e --find-links = git+file://path/to/B

Both did not work.

BTW, Puting in the path to B wheel or egg of B,

ex: pip install . -e --find-links = file:///path/to/B.whl

did work but this is not what I am looking for.

Hope you are still with me :-) (sorry for the tedious story)

What am I missing?

Tx

答:
Let me try and restate the problem:

You work on two python packages, package A and package B. A depends on B.

You have chosen to develop these two packages in separate virtual environments.

You would like to make some local changes to package B and have package A use the modified version of package B.

I apologize if I'm missing something here, but why not simply install both packages in the same virtual environment, which will make this problem go away?

I.e. after creating your environment, you install package B in editable mode, followed by installing package A. Any changes in B will be picked up by A, no changes needed.


问:
How do I replace key coincidences only in square brackets?
I'm working on some function that replaces occurrences of a string enclosed in square brackets that matches a key, with its corresponding value from a given object, but I don't know how to replace only those strings inside the square brackets, it replaces everything, I would appreciate your help:

This is what I have tried so far:

```<code>function template(str, obj){
  let new_str = str;

  for (let key in obj)
  {
       new_str = new_str.replace(new RegExp(key, 'g'), obj[key]);
  }
 console.log(new_str);
}

template("Hi [name], your balance is [balance]", { name: "Joe", balance: 1200 });

</code>```

I'm getting :

```<code>"Hi [Joe], your 1200 is [12000]"
</code>```

but I expect:

```<code>"Hi Joe, your balance is 12000"
</code>```

答:
Because the keys are enclosed in square brackets, you must put that into your pattern as well:

function template(str, obj) {
  let new_str = str;

  for (let key in obj) {
    new_str = new_str.replace(new RegExp('\\[' + key + '\\]', 'g'), obj[key]);
  }
  console.log(new_str);
}

template("Hi [name], your balance is [balance]", {
  name: "Joe",
  balance: 1200
});```
</div>
</div>
</p>

<p>You also might consider using just a single regex with a replacer function, to simplify the code:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const template = (str, obj) => str.replace(
  /\[([^\]]*)\]/g,
  (match, possibleKey) => obj[possibleKey] ? obj[possibleKey] : match
);

console.log(template("Hi [name], your balance is [balance]", {
  name: "Joe",
  balance: 1200
}));</code>```

If what is contained in the square brackets will always exist in the object, then there's no need for the conditional operator:

const template = (str, obj) => str.replace(
  /\[([^\]]*)\]/g,
  (_, key) => obj[key]
);

console.log(template("Hi [name], your balance is [balance]", {
  name: "Joe",
  balance: 1200
}));```

Body:
I'm working on some function that replaces occurrences of a string enclosed in square brackets that matches a key, with its corresponding value from a given object, but I don't know how to replace only those strings inside the square brackets, it replaces everything, I would appreciate your help:

This is what I have tried so far:

function template(str, obj){
  let new_str = str;

  for (let key in obj)
  {
       new_str = new_str.replace(new RegExp(key, 'g'), obj[key]);
  }
 console.log(new_str);
}

template("Hi [name], your balance is [balance]", { name: "Joe", balance: 1200 });

I'm getting :

"Hi [Joe], your 1200 is [12000]"

but I expect:

"Hi Joe, your balance is 12000"

Body:
Because the keys are enclosed in square brackets, you must put that into your pattern as well:

function template(str, obj) {
  let new_str = str;

  for (let key in obj) {
    new_str = new_str.replace(new RegExp('\\[' + key + '\\]', 'g'), obj[key]);
  }
  console.log(new_str);
}

template("Hi [name], your balance is [balance]", {
  name: "Joe",
  balance: 1200
});

You also might consider using just a single regex with a replacer function, to simplify the code:

const template = (str, obj) => str.replace(
  /\[([^\]]*)\]/g,
  (match, possibleKey) => obj[possibleKey] ? obj[possibleKey] : match
);

console.log(template("Hi [name], your balance is [balance]", {
  name: "Joe",
  balance: 1200
}));

If what is contained in the square brackets will always exist in the object, then there's no need for the conditional operator:

const template = (str, obj) => str.replace(
  /\[([^\]]*)\]/g,
  (_, key) => obj[key]
);

console.log(template("Hi [name], your balance is [balance]", {
  name: "Joe",
  balance: 1200
}));


问:
How do you output a line break in the command view in Matlab when running a m-file?
I have a m-file that outputs some calculations basically this:

```<code>disp(['Value ', num2str(i)]);
disp(x)
disp(['Number of iterations ', num2str(iter)])
disp('----------')
</code>```

However this ouputs stuff rather messy in the command view which is really irritating when debugging the code. I would like to add a couple of line breaks to the output in the command window. However I can't seem to find any information about this, as the Matlab documentation is pretty awful. I've tried stuff like disp('\n') and disp(' ') to no avail.

How do you do it? Can it be done?

答:
As an update, since Matlab 2016b, there is another way to do it:

```<code>disp([ 'first line' newline 'second line' ])
</code>```

It is the recommended way. Source: https://en.wikibooks.org/wiki/MATLAB_Programming/Inserting_Newlines_into_Disp_Warn_and_Error

ContentLicense: CC BY-SA 2.5

Body:
I have a m-file that outputs some calculations basically this:

disp(['Value ', num2str(i)]);
disp(x)
disp(['Number of iterations ', num2str(iter)])
disp('----------')

However this ouputs stuff rather messy in the command view which is really irritating when debugging the code. I would like to add a couple of line breaks to the output in the command window. However I can't seem to find any information about this, as the Matlab documentation is pretty awful. I've tried stuff like disp('\n') and disp(' ') to no avail.

How do you do it? Can it be done?

Body:
As an update, since Matlab 2016b, there is another way to do it:

disp([ 'first line' newline 'second line' ])

It is the recommended way. Source: https://en.wikibooks.org/wiki/MATLAB_Programming/Inserting_Newlines_into_Disp_Warn_and_Error


问:
How to save a bool value into a memory location pointed to by a void*?
I have a void* lhs_value pointing to a sufficiently sized mallocated region of memory. I want to save a rvalue of type bool into it. Don't ask me why I wanted that. I think that this is as simple as casting that pointer to bool* and de referencing it. However the compiler complains. I am apparently doing something wrong. Can you help me with this?

```<code> error: expected '(' for function-style cast or type construction
                *((*bool) lhs_value) = true;
</code>```

```<code>void* lhs_value;
lhs_value = malloc( sizeof(int) );
memset(lhs_value, 0, sizeof(int));
*((*bool) lhs_value) = true;
</code>```

答:
There's only one way to type pun correctly in C++:

```<code>#include <cstring>

bool value = true;
std::memcpy(lhs_value, &value, sizeof value);  // ::memcpy also ok
                                               // in which case #include <string.h>
</code>```

Unions are not correct and pointer casts are not correct (although the pointer cast will work on a pointer returned directly from an allocation function, it is not required to work on all void* values to valid memory).

(Yes, you should have allocated memory in advance.  Use malloc only if you are passing the pointer to a C library which will call free() on it.  Otherwise use a proper C++ allocator like ::operator new().  lhs_value = new bool(true) is best of all, if you can cast back to the original type (bool*) when using the delete operator.
No, you should not intermix sizeof (bool) with sizeof (int) unless you test it is sufficient -- sizeof (char) == 1 always but no guarantees on other built-in types.  No, you do not need to call memset.)

Body:
I have a void* lhs_value pointing to a sufficiently sized mallocated region of memory. I want to save a rvalue of type bool into it. Don't ask me why I wanted that. I think that this is as simple as casting that pointer to bool* and de referencing it. However the compiler complains. I am apparently doing something wrong. Can you help me with this?

 error: expected '(' for function-style cast or type construction
                *((*bool) lhs_value) = true;

void* lhs_value;
lhs_value = malloc( sizeof(int) );
memset(lhs_value, 0, sizeof(int));
*((*bool) lhs_value) = true;

Body:
There's only one way to type pun correctly in C++:

#include <cstring>

bool value = true;
std::memcpy(lhs_value, &value, sizeof value);  // ::memcpy also ok
                                               // in which case #include <string.h>

Unions are not correct and pointer casts are not correct (although the pointer cast will work on a pointer returned directly from an allocation function, it is not required to work on all void* values to valid memory).

(Yes, you should have allocated memory in advance.  Use malloc only if you are passing the pointer to a C library which will call free() on it.  Otherwise use a proper C++ allocator like ::operator new().  lhs_value = new bool(true) is best of all, if you can cast back to the original type (bool*) when using the delete operator.
No, you should not intermix sizeof (bool) with sizeof (int) unless you test it is sufficient -- sizeof (char) == 1 always but no guarantees on other built-in types.  No, you do not need to call memset.)


问:
How to use Toast when I cant use "this" as context
I have a location listener activity and I want to make toast notifications. But it will not let me pass this as the context. How should I make toast work?

答:
You can use NameOfYourActivity.this

For example:

```<code>public class MyActivity extends Activity {

 ...
     Toast.makeText(MyActivity.this, text, duration).show();
</code>```

Body:
You can use NameOfYourActivity.this

For example:

public class MyActivity extends Activity {

 ...
     Toast.makeText(MyActivity.this, text, duration).show();


答:
You need match [] too. Use template literals and wrap the key in [] in your RegExp

function template(str, obj){
  let new_str = str;

  for (let key in obj)
  {
       new_str = new_str.replace(new RegExp(`\\[${key}\\]`, 'g'), obj[key]);
  }
 console.log(new_str);
}

template("Hi [name], your balance is [balance]", { name: "Joe", balance: 1200 });```

Title: How do I replace key coincidences only in square brackets?


答:
Since NSManagedObject already conforms to Equatable, why do you bother to conform to it again? :)
Just override the == function and you are good to go!

```<code>extension Business {
    static func == (lhs: Business, rhs: Business) -> Bool {
        print("custom equation has been called")
        return lhs.id == rhs.id
    }
}
</code>```

You can test it like so:

```<code>var b1 = Business()
var b2 = Business()
b1.id = "1"
b2.id = "2"

print("b1 == b2 ? \(b1 == b2)")
</code>```

The result printed out proves your custom == function get called.

```<code>custom equation has been called
b1 == b2 ? false
</code>```

Title: Override Equatable and Hashable in Swift

Body:
Since NSManagedObject already conforms to Equatable, why do you bother to conform to it again? :)
Just override the == function and you are good to go!

extension Business {
    static func == (lhs: Business, rhs: Business) -> Bool {
        print("custom equation has been called")
        return lhs.id == rhs.id
    }
}

You can test it like so:

var b1 = Business()
var b2 = Business()
b1.id = "1"
b2.id = "2"

print("b1 == b2 ? \(b1 == b2)")

The result printed out proves your custom == function get called.

custom equation has been called
b1 == b2 ? false


问:
Method returning different type if block_given?
Would it be bad practice to have a method that returns self on block_given? and a different type if a block was not provided?

The example:

Config#item will return the item if a block is not given, and will return Config if it is given.

```<code>class Item
  :attr_reader :key

  def initialize(key)
    @key = key
  end

  def do_stuff
    puts "#{key} doing some stuff"
    self
  end
end

class Config
  attr_reader :items

  def initialize
    @items = {}
  end

  def item(key)
    itm = @items[key] ||= Item.new(key)
    if block_given?
      yield(itm)
      self
    else
      itm
    end
  end
end
</code>```

Usage:

```<code>cnf = Config.new
cnf.item("foo") do |itm|
  itm.do_stuff
end

.item("bar") do |itm|
  itm.do_stuff
end

foo = .item("foo").do_stuff
cnf.item("baz").do_stuff
foo.do_stuff
</code>```

The model is meant to use the same method item as a getter and as a way to refer to an item that needs to be configured or which configuration needs to be reopened.

答:
Would it be bad practice to have a method that returns self on block_given? and a different type if a block was not provided?

No. In fact, there is an extremely well-known example of a method that has this exact signature: each. each returns self if a block is given, and an Enumerator when no block is given. In fact, many methods in Enumerable return an Enumerator when no block is given and something else if there is a block.

(I am actually surprised that you haven't encountered each or Enumerable so far.)

Body:
Would it be bad practice to have a method that returns self on block_given? and a different type if a block was not provided?

The example:

Config#item will return the item if a block is not given, and will return Config if it is given.

class Item
  :attr_reader :key

  def initialize(key)
    @key = key
  end

  def do_stuff
    puts "#{key} doing some stuff"
    self
  end
end

class Config
  attr_reader :items

  def initialize
    @items = {}
  end

  def item(key)
    itm = @items[key] ||= Item.new(key)
    if block_given?
      yield(itm)
      self
    else
      itm
    end
  end
end

Usage:

cnf = Config.new
cnf.item("foo") do |itm|
  itm.do_stuff
end

.item("bar") do |itm|
  itm.do_stuff
end

foo = .item("foo").do_stuff
cnf.item("baz").do_stuff
foo.do_stuff

The model is meant to use the same method item as a getter and as a way to refer to an item that needs to be configured or which configuration needs to be reopened.


问:
How to call Loopback4 controller's method from another controller
I have a loopback 4 controller with a function that I don't want to expose via HTTP. I would like to be able to call the function from another controller.

How can I do this? Is there any way of injecting a controller in another controller?
(I 'm able to inject repositories in controllers, but not controllers in other controllers).

答:
Answer is here: https://github.com/strongloop/loopback-next/issues/3028</p>

```<code>@inject(‘controllers.AnotherController’) c: AnotherController
</code>```

Body:
Answer is here: https://github.com/strongloop/loopback-next/issues/3028

@inject(‘controllers.AnotherController’) c: AnotherController


问:
HTML form to PDF sent to e-mail
I use the Form to PDF-script from http://koivi.com/fill-pdf-form-fields/ and would like it to send the PDF to e-mail. Fortunally he has already made this possible by using the file: "process-xfdf.php". However I can't seem to find out how to use this file correctly as I always get the "This script is meant to be used in conjunction with the web forms on our website only."-error message.

What am I doing wrong?

Index.php

```<code><?php
/*
KOIVI HTML Form to FDF Parser for PHP (C) 2004 Justin Koivisto
Version 2.1
Last Modified: 2005-04-21

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation; either version 2.1 of the License, or (at
    your option) any later version.

    This library is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
    License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this library; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

    Full license agreement notice can be found in the LICENSE file contained
    within this distribution package.

    Justin Koivisto
    justin.koivisto@gmail.com
    http://koivi.com
*/

    include dirname(__FILE__).'/pdf_process.php';
    echo '<?xml version="1.0" encoding="iso-8859-1"?>',"\n";    // because short_open_tags = On causes a parse error.
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>Using HTML forms to fill in PDF fields with PHP and FDF</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta name="description" content="A PHP solution to filling a PDF file's form fields with data from a submitted HTML form." />
  <style type="text/css">
   @import url(http://koivi.com/styles.css);
  </style>
  <!--[if lt IE 7]><script src="/ie7/ie7-standard.js" type="text/javascript"></script><![endif]-->

<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-207722-1";
urchinTracker();
</script>
 </head>

 <body>
  <div id="container">
   <div id="intro">
    <h1>Using HTML forms to fill in PDF fields with PHP and FDF</h1>
    <p>Using a simple HTML form and a small PHP function, it is possible to fill in the fields of a PDF form file for viewing without having to install any PHP libraries or modules. This is accomplished by using a pre-made PDF file with all the form fields necessary and FDF files.</p>
    <p>By taking values provided via a GET or POST web request from an HTML form or hyperlink, we can generate an FDF file that, when opened, will provide the values to fill the PDF form fields in the original document.</p>
    <h1>Tutorial</h1>
    <p>I have now posted a <a href="./tutorial.php">tutorial</a> on how to use the programming found in this article for those of you who need just a little extra help implementing this.</p>
   </div>

<?php
    if(isset($CREATED)){
?>
   <div id="pageResults">
    <h1>Your Result</h1>
    <p>You can now <a href="<?php echo str_replace(dirname(__FILE__).'/','',$fdf_file) ?>">download</a> the file you just created. When downloaded, open the FDF file with your Adobe Acrobat or Acrobat Reader program to view the original PDF document with the fields filled in with the information you posted through the form below.</p>
   </div>
<?php
    }
?>

   <div>
    <h1>Creating the PDF file</h1>
    <p>First, you need to have created your <a href="test.pdf">PDF form file</a>. I do this using the form tools in Adobe Acrobat. Remember to name each field in your document, you will need those names later when you create the HTML form.</p>
   </div>

   <div>
    <h1>Creating the HTML form</h1>
    <p>Next, you need to create the form fields to fill out in an HTML form. Below is an example that fits with the above PDF file. Note that the field names in your HTML form must match the field names in your PDF file.</p>
    <form method="post" action="process-xfdf.php">
     <table cellpadding="3" cellspacing="0" border="0">
      <tr><td>Name</td><td><input type="text" name="__NAME__" value="<?php if(isset($_POST['__NAME__'])) echo $_POST['__NAME__']; ?>" /></td></tr>
      <tr><td>Title</td><td><input type="text" name="__TITLE__" value="<?php if(isset($_POST['__TITLE__'])) echo $_POST['__TITLE__']; ?>" /></td></tr>
      <tr><td>Email</td><td><input type="text" name="__EMAIL__" value="<?php if(isset($_POST['__EMAIL__'])) echo $_POST['__EMAIL__']; ?>" /></td></tr>
      <tr><td>Address</td><td><input type="text" name="__ADDRESS__" value="<?php if(isset($_POST['__ADDRESS__'])) echo $_POST['__ADDRESS__']; ?>" /></td></tr>
      <tr><td>City</td><td><input type="text" name="__CITY__" value="<?php if(isset($_POST['__CITY__'])) echo $_POST['__CITY__']; ?>" /></td></tr>
      <tr><td>State</td><td><input type="text" name="__STATE__" value="<?php if(isset($_POST['__STATE__'])) echo $_POST['__STATE__']; ?>" /></td></tr>
      <tr><td>Zip</td><td><input type="text" name="__ZIP__" value="<?php if(isset($_POST['__ZIP__'])) echo $_POST['__ZIP__']; ?>" /></td></tr>
      <tr><td>Phone</td><td><input type="text" name="__PHONE__" value="<?php if(isset($_POST['__PHONE__'])) echo $_POST['__PHONE__']; ?>" /></td></tr>
      <tr><td>Fax</td><td><input type="text" name="__FAX__" value="<?php if(isset($_POST['__FAX__'])) echo $_POST['__FAX__']; ?>" /></td></tr>
     </table>
     <input type="submit" />
    </form>
   </div>

   <div>
    <h1>Processing the POST request</h1>
    <p>When the form is submitted, the $_POST array is passed to a function along with the location of the PDF file. The function returns the contents of an FDF file. This can them be used to write an FDF file to download an view.</p>
   </div>

   <div>
    <h1>The code behind this</h1>
    <div class="example"><?php highlight_file(dirname(__FILE__).'/createFDF.php'); ?></div>
    <h2>Code for using XFDF formatted data</h2>
    <div class="example"><?php highlight_file(dirname(__FILE__).'/createXFDF.php'); ?></div>
   </div>

   <div>
    <h1>Code Download</h1>
    <p>Because of the number of requests I have received for help getting this to work or copies of the code and PDF files, I have created a ZIP archive of this entire directory and am making it <a href="/fill-pdf-form-fields.zip">available for download</a> (~180K - updated 2006-09-08).</p>
    <p>Inside this zip file you will also find a file named <code>process-xfdf.php</code> which contains sample code for sending results as an email attachment as well as sending the output directly to the browser.</p>
   </div>

   <div>
    <h1>Updates</h1>
    <p>Seriously, read these updates as they may have some additional information about what YOU are trying to accomplish</p>
    <ul>
     <li>
      <p><b>2011-01-18</b> Unbelievably, I am still getting a TON of email about this article. The most often-asked question I receive is how to send the result via email attachment. For those of you that missed it, check under the "Code Download" section of the article. I added that mid 2009. I will no longer reply to emails asking for an example of how to do this since the answer is right next to where you click to download. (There are a lot of people that don't take the time to read!)</p>
      <p>The next most frequent question is where to find the final PDF file. This process does not create a PDF file. It only creates FDF or XFDF files. However, there have been a few people nice enough to reply back to me with a solution after I explained that my code doesn't do it. While I have not tried it myself (as I haven't had the time or need to do so), <a href="http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/">PDFLabs' pdftk</a> boasts "Fill PDF Forms with FDF Data or XFDF Data and/or Flatten Forms." If anyone wants to write a how-to for this process, give me a URL and I will link over to you. Alternatively, email it to me, and I will create a page to put up with this article as well.</p>
     </li>
     <li>
      <p><b>2010-02-17</b> Minor update to the createXFDF function to allow for html entities in the values posted to the script.</p>
     </li>
     <li>
      <p><b>2009-07-15</b> It has been a few years since I posted this and nearly as long since I have used it. However, I still get emails about this all the time. Apparently the programming is still useful for people to store the form data. I did receive an email about a month or so ago about a rogue line of code in the createXFDF function that was left over from the createFDF version of the function. Thank you AndreasDoöler for bringing this to my attention. I have now updated the function and download appropriately.</p>
     </li>
     <li>
      <p><b>2006-09-08</b> For those of you having problems with using PDF files created from Acrobat 7 or Designer, you'll be please to hear that I have an update for you.</p>
      <p>The problems were stemming from the way that the latest Acrobat, Acrobat Reader and Designer handle form data. Instead of using the previous FDF format, these programs are now defaulting to the newer XFDF file format. This is basically an XML-like file structure to define the values that would be filled into the fields.</p>
     </li>
     <li>
      <p><b>2005-09-12</b> In the move from my last web server, I found that some of my files were corrupted, and this particular demonstrations was not working correctly. That should be all fixed up now.</p>
      <p>Also, I did update the createFDF function a little as well. It turned out that Acrobat 7 was having problems importing data into the PDF form if there were spaces in the field definitions inside the FDF file. I have removed those spacer, and tested on a couple simple files. I will test on a better file with more options when I have a chance.</p>
     </li>
     <li>
      <p>
       <b>2005-04-21</b> - Thanks to Adrian James for submitting information about the FDF format of a multiple value selection field
       (<code><select multiple="multiple"></code> HTML equivalent). The createFDF function has now been updated to support these fields as well.
      </p>
     </li>
    </ul>
   </div>

<script type="text/javascript"><!--
google_ad_client = "pub-6879264339756189";
google_alternate_ad_url = "http://koivi.com/google_adsense_script.html";
google_ad_width = 728;
google_ad_height = 90;
google_ad_format = "728x90_as";
google_ad_type = "text_image";
google_ad_channel ="7653137181";
google_color_border = "6E6057";
google_color_bg = "DFE0D0";
google_color_link = "313040";
google_color_url = "0000CC";
google_color_text = "000000";
//--></script>
<script type="text/javascript"
  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
  </div>

<?php include_once 'site_menu.php'; ?>

 </body>
</html>
</code>```

process-xfdf.php:

```<code><?php
/*
KOIVI HTML Form to XFDF Parser for PHP (C) 2004 Justin Koivisto
Version 1.0 - customized
Last Modified: 2006-08-25

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation; either version 2.1 of the License, or (at
    your option) any later version.

    This library is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
    License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this library; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

    Full license agreement notice can be found in the LICENSE file contained
    within this distribution package.

    Justin Koivisto
    justin.koivisto@gmail.com
    http://koivi.com
*/

    require_once 'createXFDF.php';
    $mailto='kb@hatsofcress.com';
    $subject='Submitted Form Data';
    $from='webform@hatsofcress.com';
    $pdf_file='http://www.hatsofcress.com/html2pdf/test.pdf';

    // set $redirect to '' to just output the fdf data to the browser, or give a URL for a
    // thank-you type of page
    $redirect='http://www.hatsofcress.com';

    // set $file_directory to '' to skip saving the file to server
    $file_directory=dirname(__FILE__).'/results';

    $message=<<<EndMessage
The XFDF creation script on your website has received data. Save the
attachment in this message to your hard disk. Open the PDF file and
use the import form data option under the File menu. Some setups allow
you to simply double-click the .xfdf file.

--
createXFDF PHP script by Justin Koivisto
http://koivi.com/fill-pdf-form-fields/
EndMessage;

    /**
     * fields accepted by this script
     */

    $text_fields=array(
        '__NAME__',
        '__TITLE__',
        '__EMAIL__',
        '__ADDRESS__',
        '__CITY__',
        '__STATE__',
        '__ZIP__',
        '__PHONE__',
        '__FAX__',
    );

    /**
     * ony text fields are checked in this script as no other type was provided in the html form
     * -justin 8/25
     */

    if(isset($_POST['submit'])){
        unset($_POST['submit']); // don't need to process the submit button

        foreach($_POST as $k=>$v){
            if(in_array($k,$text_fields)){
                // this field was an "accepted" field
                // verify contents (these are single lines, so no \r or \n)
                if(preg_match('`[\r\n]+`',$v)){
                    $clean[$k]=''; // bad data - send empty
                }else{
                    $clean[$k]=$v;
                }
            }else{
                // bad field option, we do nothing with this
                unset($_POST[$k]);
            }
        }

        // get the XFDF file contents
        $xfdf=createXFDF($pdf_file,$clean);

        // this seems to be the most popular request, so we will mail the xfdf to an account

        // this is the file attachment's name - you may want to customize this to fit your needs.
        $fileattname = "{$clean['__NAME__']}-{$clean['__PHONE__']}.xfdf";
        $fileatttype = "application/vnd.adobe.xfdf";
        $data=chunk_split(base64_encode($xfdf));
        $mime_boundary = '==Multipart_Boundary_x'.md5(time()).'x';
        $headers = "From: $from\n".
            "MIME-Version: 1.0\n".
            "Content-Type: multipart/mixed;\n".
            " boundary=\"{$mime_boundary}\"";
        $message = "This is a multi-part message in MIME format.\n\n".
            "--{$mime_boundary}\n".
            "Content-Type: text/plain; charset=\"iso-8859-1\"\n".
            "Content-Transfer-Encoding: 7bit\n\n".
            $message."\n\n".
            "--{$mime_boundary}\n".
            "Content-Type: {$fileatttype};\n".
            " name=\"{$fileattname}\"\n".
            "Content-Disposition: attachment;\n".
            " filename=\"{$fileattname}\"\n".
            "Content-Transfer-Encoding: base64\n\n".
            $data."\n\n".
            "--{$mime_boundary}--\n";
        if(!mail($mailto,$subject,$message,$headers)){
            // mail failed!
            mail(
                $mailto,
                'ERROR in '.__FILE__,
                'Unable to send xfdf file via attachment. Data follows:'."\n----- Begin -----\n$xfdf\n----- End -----\n"
            );
        }

        $file_name=time().'-'.$fileattname;
        if(strlen($file_directory) && file_exists($file_directory) & is_writeable($file_directory)){
            // if we have defined a writable directory on the server, write the results there as well
            $target=$file_directory.'/'.$file_name;
            if($fp=fopen($target,'w')){
                fwrite($fp,$xfdf,strlen($xfdf));
                fclose($fp);

                // mail notification of file creation
                mail($mailto,'XFDF file saved to server',$target);
            }else{
                // can't open the file for writing...
                mail($mailto,'XFDF file cannot be saved',"File cannot be written to server: $target\n");
            }
        }else if(strlen($file_directory)){
            // can't use this directory - exists on server? writeable by web server process?
            mail($mailto,'XFDF file directory cannot be used',"File cannot be written to server directory: $file_directory\n");
        }

        if(strlen($redirect)){
            // success - redirect if a redirect url is provided
            header('Location: '.$redirect);
            exit;
        }else{
            // if no redirect, we want to just send the data to the browser

            // send the XFDF headers for the browser
            header('Content-type: application/vnd.adobe.xfdf');
            header('Content-Disposition: attachment; filename="'.$file_name.'"');
            echo $xfdf;
        }
    }else{
        die('This script is meant to be used in conjunction with the web forms on our website only.');
    }
?>
</code>```

Can any of you guys help me? I desperately need help!

答:
From the source of process-xfdf.php:

```<code>if(isset($_POST['submit'])){
    // [omitted]
}else{
    die('This script is meant to be used in conjunction with the web forms on our website only.');
}
</code>```

It's clear that the script expects input from a specific form via POST, and that it also expects all of the fields in the $text_fields array to be present so that they can be filled in to the PDF.

It's also clear that you attempted no troubleshooting and made no attempt whatsoever to read the source and understand why the error was occurring.  The error message is the very last line of code in that script.

You're going to need to read the entire example script from top to bottom, as there are settings, conditions, error messages, and other behavior in there that you have to understand in order to accomplish your goal.

Title: HTML form to PDF sent to e-mail

Body:
I use the Form to PDF-script from http://koivi.com/fill-pdf-form-fields/ and would like it to send the PDF to e-mail. Fortunally he has already made this possible by using the file: "process-xfdf.php". However I can't seem to find out how to use this file correctly as I always get the "This script is meant to be used in conjunction with the web forms on our website only."-error message.

What am I doing wrong?

Index.php

<?php
/*
KOIVI HTML Form to FDF Parser for PHP (C) 2004 Justin Koivisto
Version 2.1
Last Modified: 2005-04-21

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation; either version 2.1 of the License, or (at
    your option) any later version.

    This library is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
    License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this library; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

    Full license agreement notice can be found in the LICENSE file contained
    within this distribution package.

    Justin Koivisto
    justin.koivisto@gmail.com
    http://koivi.com
*/

    include dirname(__FILE__).'/pdf_process.php';
    echo '<?xml version="1.0" encoding="iso-8859-1"?>',"\n";    // because short_open_tags = On causes a parse error.
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Using HTML forms to fill in PDF fields with PHP and FDF</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta name="description" content="A PHP solution to filling a PDF file's form fields with data from a submitted HTML form." />

Using HTML forms to fill in PDF fields with PHP and FDF

Using a simple HTML form and a small PHP function, it is possible to fill in the fields of a PDF form file for viewing without having to install any PHP libraries or modules. This is accomplished by using a pre-made PDF file with all the form fields necessary and FDF files.

By taking values provided via a GET or POST web request from an HTML form or hyperlink, we can generate an FDF file that, when opened, will provide the values to fill the PDF form fields in the original document.

Tutorial

I have now posted a tutorial on how to use the programming found in this article for those of you who need just a little extra help implementing this.

<?php
    if(isset($CREATED)){
?>

Your Result

You can now <a href="<?php echo str_replace(dirname(__FILE__).'/','',$fdf_file) ?>">download the file you just created. When downloaded, open the FDF file with your Adobe Acrobat or Acrobat Reader program to view the original PDF document with the fields filled in with the information you posted through the form below.

<?php
    }
?>

Creating the PDF file

First, you need to have created your PDF form file. I do this using the form tools in Adobe Acrobat. Remember to name each field in your document, you will need those names later when you create the HTML form.

Creating the HTML form

Next, you need to create the form fields to fill out in an HTML form. Below is an example that fits with the above PDF file. Note that the field names in your HTML form must match the field names in your PDF file.

    <form method="post" action="process-xfdf.php">

Name	<input type="text" name="__NAME__" value="<?php if(isset($_POST['__NAME__'])) echo $_POST['__NAME__']; ?>" />

Title	<input type="text" name="__TITLE__" value="<?php if(isset($_POST['__TITLE__'])) echo $_POST['__TITLE__']; ?>" />

Email	<input type="text" name="__EMAIL__" value="<?php if(isset($_POST['__EMAIL__'])) echo $_POST['__EMAIL__']; ?>" />

Address	<input type="text" name="__ADDRESS__" value="<?php if(isset($_POST['__ADDRESS__'])) echo $_POST['__ADDRESS__']; ?>" />

City	<input type="text" name="__CITY__" value="<?php if(isset($_POST['__CITY__'])) echo $_POST['__CITY__']; ?>" />

State	<input type="text" name="__STATE__" value="<?php if(isset($_POST['__STATE__'])) echo $_POST['__STATE__']; ?>" />

Zip	<input type="text" name="__ZIP__" value="<?php if(isset($_POST['__ZIP__'])) echo $_POST['__ZIP__']; ?>" />

Phone	<input type="text" name="__PHONE__" value="<?php if(isset($_POST['__PHONE__'])) echo $_POST['__PHONE__']; ?>" />

Fax	<input type="text" name="__FAX__" value="<?php if(isset($_POST['__FAX__'])) echo $_POST['__FAX__']; ?>" />

     <input type="submit" />
    </form>

Processing the POST request

When the form is submitted, the $_POST array is passed to a function along with the location of the PDF file. The function returns the contents of an FDF file. This can them be used to write an FDF file to download an view.

The code behind this

<?php highlight_file(dirname(__FILE__).'/createFDF.php'); ?>

Code for using XFDF formatted data

<?php highlight_file(dirname(__FILE__).'/createXFDF.php'); ?>

Code Download

Because of the number of requests I have received for help getting this to work or copies of the code and PDF files, I have created a ZIP archive of this entire directory and am making it available for download (~180K - updated 2006-09-08).

Inside this zip file you will also find a file named process-xfdf.php which contains sample code for sending results as an email attachment as well as sending the output directly to the browser.

Updates

Seriously, read these updates as they may have some additional information about what YOU are trying to accomplish

2011-01-18 Unbelievably, I am still getting a TON of email about this article. The most often-asked question I receive is how to send the result via email attachment. For those of you that missed it, check under the "Code Download" section of the article. I added that mid 2009. I will no longer reply to emails asking for an example of how to do this since the answer is right next to where you click to download. (There are a lot of people that don't take the time to read!)

The next most frequent question is where to find the final PDF file. This process does not create a PDF file. It only creates FDF or XFDF files. However, there have been a few people nice enough to reply back to me with a solution after I explained that my code doesn't do it. While I have not tried it myself (as I haven't had the time or need to do so), PDFLabs' pdftk boasts "Fill PDF Forms with FDF Data or XFDF Data and/or Flatten Forms." If anyone wants to write a how-to for this process, give me a URL and I will link over to you. Alternatively, email it to me, and I will create a page to put up with this article as well.

2010-02-17 Minor update to the createXFDF function to allow for html entities in the values posted to the script.

2009-07-15 It has been a few years since I posted this and nearly as long since I have used it. However, I still get emails about this all the time. Apparently the programming is still useful for people to store the form data. I did receive an email about a month or so ago about a rogue line of code in the createXFDF function that was left over from the createFDF version of the function. Thank you AndreasDoöler for bringing this to my attention. I have now updated the function and download appropriately.

2006-09-08 For those of you having problems with using PDF files created from Acrobat 7 or Designer, you'll be please to hear that I have an update for you.

The problems were stemming from the way that the latest Acrobat, Acrobat Reader and Designer handle form data. Instead of using the previous FDF format, these programs are now defaulting to the newer XFDF file format. This is basically an XML-like file structure to define the values that would be filled into the fields.

2005-09-12 In the move from my last web server, I found that some of my files were corrupted, and this particular demonstrations was not working correctly. That should be all fixed up now.

Also, I did update the createFDF function a little as well. It turned out that Acrobat 7 was having problems importing data into the PDF form if there were spaces in the field definitions inside the FDF file. I have removed those spacer, and tested on a couple simple files. I will test on a better file with more options when I have a chance.

       2005-04-21 - Thanks to Adrian James for submitting information about the FDF format of a multiple value selection field
       (<select multiple="multiple"> HTML equivalent). The createFDF function has now been updated to support these fields as well.

<?php include_once 'site_menu.php'; ?>

process-xfdf.php:

<?php
/*
KOIVI HTML Form to XFDF Parser for PHP (C) 2004 Justin Koivisto
Version 1.0 - customized
Last Modified: 2006-08-25

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation; either version 2.1 of the License, or (at
    your option) any later version.

    This library is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
    License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this library; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

    Full license agreement notice can be found in the LICENSE file contained
    within this distribution package.

    Justin Koivisto
    justin.koivisto@gmail.com
    http://koivi.com
*/

    require_once 'createXFDF.php';
    $mailto='kb@hatsofcress.com';
    $subject='Submitted Form Data';
    $from='webform@hatsofcress.com';
    $pdf_file='http://www.hatsofcress.com/html2pdf/test.pdf';

    // set $redirect to '' to just output the fdf data to the browser, or give a URL for a
    // thank-you type of page
    $redirect='http://www.hatsofcress.com';

    // set $file_directory to '' to skip saving the file to server
    $file_directory=dirname(__FILE__).'/results';

    $message=<<<EndMessage
The XFDF creation script on your website has received data. Save the
attachment in this message to your hard disk. Open the PDF file and
use the import form data option under the File menu. Some setups allow
you to simply double-click the .xfdf file.

--
createXFDF PHP script by Justin Koivisto
http://koivi.com/fill-pdf-form-fields/
EndMessage;

    /**
     * fields accepted by this script
     */

    $text_fields=array(
        '__NAME__',
        '__TITLE__',
        '__EMAIL__',
        '__ADDRESS__',
        '__CITY__',
        '__STATE__',
        '__ZIP__',
        '__PHONE__',
        '__FAX__',
    );

    /**
     * ony text fields are checked in this script as no other type was provided in the html form
     * -justin 8/25
     */

    if(isset($_POST['submit'])){
        unset($_POST['submit']); // don't need to process the submit button

        foreach($_POST as $k=>$v){
            if(in_array($k,$text_fields)){
                // this field was an "accepted" field
                // verify contents (these are single lines, so no \r or \n)
                if(preg_match('`[\r\n]+`',$v)){
                    $clean[$k]=''; // bad data - send empty
                }else{
                    $clean[$k]=$v;
                }
            }else{
                // bad field option, we do nothing with this
                unset($_POST[$k]);
            }
        }

        // get the XFDF file contents
        $xfdf=createXFDF($pdf_file,$clean);

        // this seems to be the most popular request, so we will mail the xfdf to an account

        // this is the file attachment's name - you may want to customize this to fit your needs.
        $fileattname = "{$clean['__NAME__']}-{$clean['__PHONE__']}.xfdf";
        $fileatttype = "application/vnd.adobe.xfdf";
        $data=chunk_split(base64_encode($xfdf));
        $mime_boundary = '==Multipart_Boundary_x'.md5(time()).'x';
        $headers = "From: $from\n".
            "MIME-Version: 1.0\n".
            "Content-Type: multipart/mixed;\n".
            " boundary=\"{$mime_boundary}\"";
        $message = "This is a multi-part message in MIME format.\n\n".
            "--{$mime_boundary}\n".
            "Content-Type: text/plain; charset=\"iso-8859-1\"\n".
            "Content-Transfer-Encoding: 7bit\n\n".
            $message."\n\n".
            "--{$mime_boundary}\n".
            "Content-Type: {$fileatttype};\n".
            " name=\"{$fileattname}\"\n".
            "Content-Disposition: attachment;\n".
            " filename=\"{$fileattname}\"\n".
            "Content-Transfer-Encoding: base64\n\n".
            $data."\n\n".
            "--{$mime_boundary}--\n";
        if(!mail($mailto,$subject,$message,$headers)){
            // mail failed!
            mail(
                $mailto,
                'ERROR in '.__FILE__,
                'Unable to send xfdf file via attachment. Data follows:'."\n----- Begin -----\n$xfdf\n----- End -----\n"
            );
        }

        $file_name=time().'-'.$fileattname;
        if(strlen($file_directory) && file_exists($file_directory) & is_writeable($file_directory)){
            // if we have defined a writable directory on the server, write the results there as well
            $target=$file_directory.'/'.$file_name;
            if($fp=fopen($target,'w')){
                fwrite($fp,$xfdf,strlen($xfdf));
                fclose($fp);

                // mail notification of file creation
                mail($mailto,'XFDF file saved to server',$target);
            }else{
                // can't open the file for writing...
                mail($mailto,'XFDF file cannot be saved',"File cannot be written to server: $target\n");
            }
        }else if(strlen($file_directory)){
            // can't use this directory - exists on server? writeable by web server process?
            mail($mailto,'XFDF file directory cannot be used',"File cannot be written to server directory: $file_directory\n");
        }

        if(strlen($redirect)){
            // success - redirect if a redirect url is provided
            header('Location: '.$redirect);
            exit;
        }else{
            // if no redirect, we want to just send the data to the browser

            // send the XFDF headers for the browser
            header('Content-type: application/vnd.adobe.xfdf');
            header('Content-Disposition: attachment; filename="'.$file_name.'"');
            echo $xfdf;
        }
    }else{
        die('This script is meant to be used in conjunction with the web forms on our website only.');
    }
?>

Can any of you guys help me? I desperately need help!

Body:
From the source of process-xfdf.php:

if(isset($_POST['submit'])){
    // [omitted]
}else{
    die('This script is meant to be used in conjunction with the web forms on our website only.');
}

It's clear that the script expects input from a specific form via POST, and that it also expects all of the fields in the $text_fields array to be present so that they can be filled in to the PDF.

It's also clear that you attempted no troubleshooting and made no attempt whatsoever to read the source and understand why the error was occurring.  The error message is the very last line of code in that script.

You're going to need to read the entire example script from top to bottom, as there are settings, conditions, error messages, and other behavior in there that you have to understand in order to accomplish your goal.


答:
Not at all, as long as the users of your method have adequate understanding of this.  Documentation helps quite significantly in these situations.

Consider the Ruby Standard Library.  Many methods return different types based on their inputs and block_given?, such as Enumerable#map, Hash#each, and Range#step.

Like the standard library authors, you have to decide whether you prefer a compact interface to your class/model or consistent behavior from your methods.  There are always tradeoffs to make, and you have numerous strong examples of each of these to draw from within the Ruby Standard Library.

Title: Method returning different type if block_given?


问:
Relational database (RDBMS) denormalized data
I believe this question does not address specifically MySQL - which is the database that I'm using -, and it's one about best practices.

Up until now, my problems could be solved by creating tables and querying them (sometimes JOINing here and there). But there is something that I'm doing that doesn't feel right, and it triggers me whenever I need a denormalized data alongside my "common" queries.

Example Use-case

So that I can express myself better, let's create a superficial scenario where:

a user can buy a product, generating a purchase (let's ignore the fact that the purchase can only have a single product);

and we need to query the products with the total amount of times it has been purchased;

To solve our use-case, we could define a simple structure made by:

product table:

product_id [INT PK]

user table:

user_id [INT PK]

purchase table:

purchase_id [INT PK]

product_id [INT FK NOT NULL]

user_id [INT FK NOT NULL]

Here is where it doesn't feel right: When we need to retrieve a list of products with the total times it has been purchased, I would create the query:

```<code># There are probably faster queries than this to reach the same output
SELECT
    product.product_id,
    (SELECT COUNT(*) FROM purchase
      WHERE purchase.product_id = product.product_id)
FROM
    product
</code>```

My concern origin is that I've read that COUNT does a full table scan, and it scares me to perform the query above when scaled to thousands of products being purchased - even though I've created an INDEX with the product_id FK on purchase (MySQL does this by default).

Possible solutions

My knowledge with relational databases is pretty shallow, so I'm kind of lost when comparing what are the alternatives (plausible ones) for these kinds of problems. To not say that I haven't done my homework (searching before asking), I've found plausible to:

Create Transactions:

When INSERTing a new purchase, it must always be inside a transaction that also updates the product table with the purchase.product_id.

Possible Problems: human error. Someone might manually insert a purchase without doing the transaction and BAM - we have an inconsistency.

Create Triggers:

Whenever I insert, delete or update some row in some specific table, I would update my products table with a new value (bought_amount). So the table would become:

product table:

product_id [INT PK]

bought_amount [INT NOT NULL];

Possible problems: are triggers expensive? is there a way that the insertion succeeds but the trigger won't - thus leaving me with an inconsistency?

Question

Updating certain tables to store data that constantly changes is a plausible approach with RDBMSs? Is it safer and - in the long term - more beneficial to just keep joining and counting/summing other occurrences?

I've found a couple of useful questions/answers regarding this matter, but none of them addressed this subject in a wide perspective.
Please take into consideration my ignorance about RDBMS, as I may be suggesting nonsense Possible solutions.

答:
The usual way to get a count per key is

```<code>SELECT product_id, COUNT(*)
FROM purchase
GROUP BY product_id
</code>```

You don't need to mention the product table, because all it contains is the key column. Now although that uses COUNT(*), it doesn't need a full table scan for every product_id because the SQL engine is smart enough to see the GROUP BY.

But this produces a different result to your query: for products that have never been purchased, my query simply won't show them; your query will show the product_id with count zero.

Then before you start worrying about implementation and efficiency, what question(s) are you trying to answer? If you want to see all products whether purchased or not, then you must scan the whole product table and look up from that to purchase. I would go

```<code>SELECT product_id, count
FROM product
OUTER JOIN (SELECT product_id, COUNT(*) AS count
            FROM purchase
            GROUP BY product_id) AS purch
ON product.product_id = purch.product_id
</code>```

As regards your wider questions (not sure I fully understand them), in the early days SQL was quite inefficient at this sort of joining and aggregating, and schema often were denormalised with repeated columns in multiple tables. SQL engines are now much smarter, so that's not necessary. You might see that old-fashioned practice in older textbooks. I would ignore it and design your schema as normalised as possible.

Body:
I believe this question does not address specifically MySQL - which is the database that I'm using -, and it's one about best practices.

Up until now, my problems could be solved by creating tables and querying them (sometimes JOINing here and there). But there is something that I'm doing that doesn't feel right, and it triggers me whenever I need a denormalized data alongside my "common" queries.

Example Use-case

So that I can express myself better, let's create a superficial scenario where:

a user can buy a product, generating a purchase (let's ignore the fact that the purchase can only have a single product);

and we need to query the products with the total amount of times it has been purchased;

To solve our use-case, we could define a simple structure made by:

product table:

product_id [INT PK]

user table:

user_id [INT PK]

purchase table:

purchase_id [INT PK]

product_id [INT FK NOT NULL]

user_id [INT FK NOT NULL]

Here is where it doesn't feel right: When we need to retrieve a list of products with the total times it has been purchased, I would create the query:

# There are probably faster queries than this to reach the same output
SELECT
    product.product_id,
    (SELECT COUNT(*) FROM purchase
      WHERE purchase.product_id = product.product_id)
FROM
    product

My concern origin is that I've read that COUNT does a full table scan, and it scares me to perform the query above when scaled to thousands of products being purchased - even though I've created an INDEX with the product_id FK on purchase (MySQL does this by default).

Possible solutions

My knowledge with relational databases is pretty shallow, so I'm kind of lost when comparing what are the alternatives (plausible ones) for these kinds of problems. To not say that I haven't done my homework (searching before asking), I've found plausible to:

Create Transactions:

When INSERTing a new purchase, it must always be inside a transaction that also updates the product table with the purchase.product_id.

Possible Problems: human error. Someone might manually insert a purchase without doing the transaction and BAM - we have an inconsistency.

Create Triggers:

Whenever I insert, delete or update some row in some specific table, I would update my products table with a new value (bought_amount). So the table would become:

product table:

product_id [INT PK]

bought_amount [INT NOT NULL];

Possible problems: are triggers expensive? is there a way that the insertion succeeds but the trigger won't - thus leaving me with an inconsistency?

Question

Updating certain tables to store data that constantly changes is a plausible approach with RDBMSs? Is it safer and - in the long term - more beneficial to just keep joining and counting/summing other occurrences?

I've found a couple of useful questions/answers regarding this matter, but none of them addressed this subject in a wide perspective.
Please take into consideration my ignorance about RDBMS, as I may be suggesting nonsense Possible solutions.

Body:
The usual way to get a count per key is

SELECT product_id, COUNT(*)
FROM purchase
GROUP BY product_id

You don't need to mention the product table, because all it contains is the key column. Now although that uses COUNT(*), it doesn't need a full table scan for every product_id because the SQL engine is smart enough to see the GROUP BY.

But this produces a different result to your query: for products that have never been purchased, my query simply won't show them; your query will show the product_id with count zero.

Then before you start worrying about implementation and efficiency, what question(s) are you trying to answer? If you want to see all products whether purchased or not, then you must scan the whole product table and look up from that to purchase. I would go

SELECT product_id, count
FROM product
OUTER JOIN (SELECT product_id, COUNT(*) AS count
            FROM purchase
            GROUP BY product_id) AS purch
ON product.product_id = purch.product_id

As regards your wider questions (not sure I fully understand them), in the early days SQL was quite inefficient at this sort of joining and aggregating, and schema often were denormalised with repeated columns in multiple tables. SQL engines are now much smarter, so that's not necessary. You might see that old-fashioned practice in older textbooks. I would ignore it and design your schema as normalised as possible.


问:
Stop a For Loop at an Index Value
I am attempting to use a for loop to iterate through a list of items. I do not need all items in the list and would like to end on a certain index position. How would I go about this in python?

I've attempted to use enumerate and alter my code to other options. After hours of searching I am having a hard time understanding how to end a loop upon a certain parameter in python. The code I am providing WORKS excellent for my interests. I would only like to stop the for loop upon a certain index.

```<code>train_times = driver.find_element_by_class_name('stop-times').text
str(train_times)
train_times=train_times.split('\n')

print("Schedule for 900 East Station:")

for i in train_times:
    print('There is a train at {}'.format(i))
    print('--------------------------------------')
</code>```

答:
As you know the exact index to stop in the string you can provide the index to loop from and to</p>

```<code>for i in train_times[:20]:
    print('There is a train at {}'.format(i))
    print('--------------------------------------')
</code>```

Title: Stop a For Loop at an Index Value

Body:
I am attempting to use a for loop to iterate through a list of items. I do not need all items in the list and would like to end on a certain index position. How would I go about this in python?

I've attempted to use enumerate and alter my code to other options. After hours of searching I am having a hard time understanding how to end a loop upon a certain parameter in python. The code I am providing WORKS excellent for my interests. I would only like to stop the for loop upon a certain index.

train_times = driver.find_element_by_class_name('stop-times').text
str(train_times)
train_times=train_times.split('\n')

print("Schedule for 900 East Station:")

for i in train_times:
    print('There is a train at {}'.format(i))
    print('--------------------------------------')

Body:
As you know the exact index to stop in the string you can provide the index to loop from and to

for i in train_times[:20]:
    print('There is a train at {}'.format(i))
    print('--------------------------------------')


答:
You can use break and enumarate.

for index, value in enumerate(train_times):
   if index == x : break
   // your code here
```

Title: Stop a For Loop at an Index Value


问:
Why function shows none for more output when using insert() method in lists in Python?
I am using function to insert method to add a value in list as given below:
1. insert_value.py file as given below:

```<code>def insert_value(my_list, value, insert_position):

  str_list3 = ['one','three','four', 'five', 'six']
  str_list4 = ['i', 't']

  if my_list == str_list3:

        front = my_list[:insert_position]
        back = my_list[insert_position:]
        return front + [value] + back

  elif my_list == str_list4:

        front = my_list[:insert_position]

        back = my_list[insert_position:]

        a= front +[value]+ back

        return a
</code>```

insert_value_test_file.py as given below:

```<code>import insert_value
print("\ninsert_value Test")
str_list3 = ['one','three','four', 'five', 'six']

new_list = insert_value.insert_value(str_list3, 'two', 1)

print(new_list)

str_list4 = ['i', 't']

str_list4 = insert_value.insert_value(str_list4, 'p', 0)

print(str_list4)

str_list4 = insert_value.insert_value(str_list4, 's', -1)

print(str_list4)

str_list4 = insert_value.insert_value(str_list4, 's', 7)

print(str_list4)
</code>```

when running this file my output comes as :

insert_value Test ['one', 'two', 'three', 'four', 'five', 'six'] ['p',
  'i', 't'] None None

Why None ???? for other inputs in str_list4.

答: Neither of the conditionals in insert_value evaluate to True after the first two calls, so insert_value has no return (returns None) for the last two calls. </p>

Body:
I am using function to insert method to add a value in list as given below:
1. insert_value.py file as given below:

def insert_value(my_list, value, insert_position):

  str_list3 = ['one','three','four', 'five', 'six']
  str_list4 = ['i', 't']

  if my_list == str_list3:

        front = my_list[:insert_position]
        back = my_list[insert_position:]
        return front + [value] + back

  elif my_list == str_list4:

        front = my_list[:insert_position]

        back = my_list[insert_position:]

        a= front +[value]+ back

        return a

insert_value_test_file.py as given below:

import insert_value
print("\ninsert_value Test")
str_list3 = ['one','three','four', 'five', 'six']

new_list = insert_value.insert_value(str_list3, 'two', 1)

print(new_list)

str_list4 = ['i', 't']

str_list4 = insert_value.insert_value(str_list4, 'p', 0)

print(str_list4)

str_list4 = insert_value.insert_value(str_list4, 's', -1)

print(str_list4)

str_list4 = insert_value.insert_value(str_list4, 's', 7)

print(str_list4)

when running this file my output comes as :

insert_value Test ['one', 'two', 'three', 'four', 'five', 'six'] ['p',
  'i', 't'] None None

Why None ???? for other inputs in str_list4.


问:
CSS: first-child selector including text nodes
is there any way to select a CSS-element that is the first child of its parent, counting text nodes? I want to remove the top margin of a heading if it is at the top of its parent, but if I use:

```<code>#content h1 {
    margin-top: 1em;
}
#content h1:first-child {
    margin-top: 0;
}
</code>```

and have some HTML like

```<code><div id="content">
    This is some text.
    <h1>A heading</h1>
    Some more text.
</div>
</code>```

the margin is still removed. Is there any way in CSS to prevent this?

答:
In the example given in the OP, you could (remove the :first-child rule and) add

```<code>#content {
  margin-top: 1em;
}
</code>```

This would collapse (combine and overlap) with the h1’s margin if there’s no text before the heading, but if there is the h1 would have a separate top margin.  You’d then just have to adjust the bottom padding/margin of whatever is preceding so that your #content is positioned desirably, or perhaps alternatively add a ::before pseudo-element with a negative margin (which will collapse with and cancel out the container’s margin) to do the trick:

```<code>#content:before {
  display: block;
  margin-top: -1rem;
  content: ' ';
}
</code>```

Note that if h1 has a different font-size then 1em will different so you would have to account for that or use a fixed unit such as rem or px.

(This doesn’t help in my case – I want to add a top-margin to a floated img if there’s some text before it in the containing
 [in WordPress-generated content].  But margins of float-ed elements don’t collapse with their container, and the general answer to the question is “no, there’s no such selector.”)

Body:
is there any way to select a CSS-element that is the first child of its parent, counting text nodes? I want to remove the top margin of a heading if it is at the top of its parent, but if I use:

#content h1 {
    margin-top: 1em;
}
#content h1:first-child {
    margin-top: 0;
}

and have some HTML like

    This is some text.

A heading

    Some more text.

the margin is still removed. Is there any way in CSS to prevent this?

Body:
In the example given in the OP, you could (remove the :first-child rule and) add

#content {
  margin-top: 1em;
}

This would collapse (combine and overlap) with the h1’s margin if there’s no text before the heading, but if there is the h1 would have a separate top margin.  You’d then just have to adjust the bottom padding/margin of whatever is preceding so that your #content is positioned desirably, or perhaps alternatively add a ::before pseudo-element with a negative margin (which will collapse with and cancel out the container’s margin) to do the trick:

#content:before {
  display: block;
  margin-top: -1rem;
  content: ' ';
}

Note that if h1 has a different font-size then 1em will different so you would have to account for that or use a fixed unit such as rem or px.

(This doesn’t help in my case – I want to add a top-margin to a floated img if there’s some text before it in the containing <p> [in WordPress-generated content].  But margins of float-ed elements don’t collapse with their container, and the general answer to the question is “no, there’s no such selector.”)


问:
How to disable Widget updatePeriodMillis?
I'm trying to figure out how I can disable the update period on my widgets?  I don't need this particular feature.  I'm just fine with the widget calling onUpdate when added that's it...</p>

答: Just don't include it in your xml and it won't autoupdate, or set it to 0.</p>


问:
Canceled timer and screen lock
I have created an app which use count down timer, the problem is that the timer stops completely when the screen gets locked.
I already know that this happens due to onStop() is invoked,
So my question is how to prevent stopping the timers' work without needing to cancel screen lock? </p>

答: Personally I would store the start time, persist it or save with onSaveInstanceState and then recalculate / start your timers again when your activity has resumed. I feel this would be the easier and more reliable solution </p>

Title: Canceled timer and screen lock


问:
How to do Dynamic dataframe indexing in R
I have two dataframes; sauce and rules. rules has a column called fieldname which consists of column names present in sauce. rules has a row called fieldvalue which consists of fileds pertaining to the column name in sauce. I want to be extract data from sauce based on fieldname and fieldvalue of rules.

I was trying to use for loops but they take too long and have not been able to get the correct result out of it.

```<code>> sauce <- data.frame(Type = c("ketchup","mustard","mayo","lite-mayo","ketchup"), Brand = c("Heinz","Publix","Kroger","Kroger","Kroger"))
> rules <- data.frame(fieldname = c("Type","Type","Brand"),
                        fieldvalue = c("ketchup","lite-mayo","Kroger"),
                          operator = c("and","or",""),
                            fielname2 = c("Brand","Brand",""),
                             fieldvalue2 = c("Heinz","Kroger",""))
</code>```

I am intending to index column names but using a different dataframe
sauce[,c(rules$fieldname)]

I am ideally wanting to get data out of sauce based on rules dataframe.

for instance: fielname: Type and fieldvalue: ketchup (and being the operator) should result in ketchup Heinz as the output

答:
Create a vector of conditions using apply and sprintf from rules dataframe

```<code>#Change and, or to &, |
rules$operator_sym <- ifelse(rules$operator=="","",ifelse(rules$operator=="and",'&','|'))
conds <- apply(rules, 1, function(x) if(length(x[x!=''])==6)
  sprintf("%s == '%s' %s %s == '%s'", x['fieldname'], x['fieldvalue'], x['operator_sym'], x['fielname2'], x['fieldvalue2']) else
  sprintf("%s == '%s'",x['fieldname'],x['fieldvalue']))

> conds
[1] "Type == 'ketchup' & Brand == 'Heinz'"    "Type == 'lite-mayo' | Brand == 'Kroger'"
[3] "Brand == 'Kroger'"
</code>```

Use map to loop through conds and filter sauce using the current condition. Use parse_exprs to transfer the condition from a string into R epression then evaluated using !!!

```<code>library(dplyr)
library(purrr)
library(rlang)
map(conds %>% set_names(), ~filter(sauce, !!!parse_exprs(.x)))

$`Type == 'ketchup' & Brand == 'Heinz'`
     Type Brand
1 ketchup Heinz

$`Type == 'lite-mayo' | Brand == 'Kroger'`
       Type  Brand
1      mayo Kroger
2 lite-mayo Kroger
3   ketchup Kroger

$`Brand == 'Kroger'`
       Type  Brand
1      mayo Kroger
2 lite-mayo Kroger
3   ketchup Kroger
</code>```

Using map the output will be a list if you'd like the output as a dataframe you need map_dfr(conds %>% set_names(), ~filter(sauce, !!!parse_exprs(.x)), .id = "Condition")

Body:
I have two dataframes; sauce and rules. rules has a column called fieldname which consists of column names present in sauce. rules has a row called fieldvalue which consists of fileds pertaining to the column name in sauce. I want to be extract data from sauce based on fieldname and fieldvalue of rules.

I was trying to use for loops but they take too long and have not been able to get the correct result out of it.

> sauce <- data.frame(Type = c("ketchup","mustard","mayo","lite-mayo","ketchup"), Brand = c("Heinz","Publix","Kroger","Kroger","Kroger"))
> rules <- data.frame(fieldname = c("Type","Type","Brand"),
                        fieldvalue = c("ketchup","lite-mayo","Kroger"),
                          operator = c("and","or",""),
                            fielname2 = c("Brand","Brand",""),
                             fieldvalue2 = c("Heinz","Kroger",""))

I am intending to index column names but using a different dataframe
sauce[,c(rules$fieldname)]

I am ideally wanting to get data out of sauce based on rules dataframe.

for instance: fielname: Type and fieldvalue: ketchup (and being the operator) should result in ketchup Heinz as the output

Body:
Create a vector of conditions using apply and sprintf from rules dataframe

#Change and, or to &, |
rules$operator_sym <- ifelse(rules$operator=="","",ifelse(rules$operator=="and",'&','|'))
conds <- apply(rules, 1, function(x) if(length(x[x!=''])==6)
  sprintf("%s == '%s' %s %s == '%s'", x['fieldname'], x['fieldvalue'], x['operator_sym'], x['fielname2'], x['fieldvalue2']) else
  sprintf("%s == '%s'",x['fieldname'],x['fieldvalue']))

> conds
[1] "Type == 'ketchup' & Brand == 'Heinz'"    "Type == 'lite-mayo' | Brand == 'Kroger'"
[3] "Brand == 'Kroger'"

Use map to loop through conds and filter sauce using the current condition. Use parse_exprs to transfer the condition from a string into R epression then evaluated using !!!

library(dplyr)
library(purrr)
library(rlang)
map(conds %>% set_names(), ~filter(sauce, !!!parse_exprs(.x)))

$`Type == 'ketchup' & Brand == 'Heinz'`
     Type Brand
1 ketchup Heinz

$`Type == 'lite-mayo' | Brand == 'Kroger'`
       Type  Brand
1      mayo Kroger
2 lite-mayo Kroger
3   ketchup Kroger

$`Brand == 'Kroger'`
       Type  Brand
1      mayo Kroger
2 lite-mayo Kroger
3   ketchup Kroger

Using map the output will be a list if you'd like the output as a dataframe you need map_dfr(conds %>% set_names(), ~filter(sauce, !!!parse_exprs(.x)), .id = "Condition")


问:
Android Studio: "Gradle sync failed: Could not run JVM from the selected JDK."
Ever since installing Android Studio 3.2, I haven't been able to run Java, I have tried jdk-8u181-windows-x64, jdk-10.0.2_windows-x64_bin, jdk-11_windows-x64_bin, setting PATH and reinstalling everything umpteen times, the result is the same - no "java" appears and the error message is: -

Gradle sync failed: Could not run JVM from the selected JDK.
                    Please ensure JDK installation is valid and compatible with the current OS (Windows 8.1 6.3, amd64).
                    If you are using embedded JDK, please make sure to download Android Studio bundle compatible
                    with the current OS. For example, for x86 systems please choose a 32 bits download option. (369 ms)

Notes: I used to be able to open the java folder but after playing with it too much, something went wrong, so, I decided to start afresh... and I am dead ever since.

Is Studio 3.2 flawed? Not compatible with Java at all? Or am I missing something? is there a older Android Studio I can test? Thanks for any help you may provide.

答:
Solved YES
Other Settings ---> Default Project Structure ---> Uncheck Embedded jdk ( Write Your Own jdk Location )</p>