问:
how to see if a value is present in a list in django template. tried using IN operator but does'nt work
I'm trying to enable a button dynamically but the IN operator on my html does not work. I tried converting everything to string as well but it still did not work.

Models.py

```<code>class Product(models.Model):
    name=models.CharField(max_length=100)
    image=models.ImageField(default='default.jpg',upload_to='productimages')
    description=models.TextField()
    category=models.CharField(max_length=100)
    price=models.FloatField()

    def __str__(self):
        return f'{self.name}'

class Cart(models.Model):
    cart2user= models.ForeignKey(User, on_delete=models.CASCADE)
    cart2product=models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity=models.IntegerField(default=1)
</code>```

views.py

```<code>def home(request):
    productobj=Product.objects.all()
    cartobj=Cart.objects.filter(cart2user=request.user)
    cartobjlist=[x.cart2product for x in cartobj]
    print(cartobjlist)
    return render(request,'home.html',{'productobj':productobj,'cartobjlist':'cartobjlist'})
</code>```

home.html

```<code> {% for pobj in productobj%}
       <div class="col-xl-3 eachproduct">
        <form action="{%url 'home'%}" method="GET">
          {% csrf_token%}
            <img src="{{pobj.image.url}}" height="300px" width="100%">
            <h3 class="name" name="{{pobj}}" value={{pobj}}>{{pobj.id}}</h3>
            <h3 class="price" name="price" value={{pobj.price}}>${{pobj.price}}</h3>
            {% if pobj in cartobjlist %}
              <a href="{% url 'cart'%}" class="btn buttoncart">Go to cart</a>
            {% else %}
              <a href="addtocart/{{pobj.id}}" class="btn buttoncart">Add to cart</a>
            {%endif%}
        </form>
       </div>
       {%endfor%}
</code>```

答:
You did not pass the list to the template, you passed a string named 'cartobjlist' to the template. Indeed:

```<code>{'productobj':productobj,'cartobjlist':<s>'cartobjlist'</s>})</code>```

That being said, I strongly advice you to fetch the products more efficiently, and furthermore use a set to perform faster lookups, like:

```<code>def home(request):
    productobj = Product.objects.all()
    cartobjlist = <b>set(Product.objects.filter(cart__cart2user=request.user))</b>
    return render(
        request,
        'home.html',
        {'productobj':productobj,'cartobjlist':<b>cartobjlist</b>}
    )</code>```

Body:
I'm trying to enable a button dynamically but the IN operator on my html does not work. I tried converting everything to string as well but it still did not work.

Models.py

class Product(models.Model):
    name=models.CharField(max_length=100)
    image=models.ImageField(default='default.jpg',upload_to='productimages')
    description=models.TextField()
    category=models.CharField(max_length=100)
    price=models.FloatField()

    def __str__(self):
        return f'{self.name}'

class Cart(models.Model):
    cart2user= models.ForeignKey(User, on_delete=models.CASCADE)
    cart2product=models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity=models.IntegerField(default=1)

views.py

def home(request):
    productobj=Product.objects.all()
    cartobj=Cart.objects.filter(cart2user=request.user)
    cartobjlist=[x.cart2product for x in cartobj]
    print(cartobjlist)
    return render(request,'home.html',{'productobj':productobj,'cartobjlist':'cartobjlist'})

home.html

 {% for pobj in productobj%}

        <form action="{%url 'home'%}" method="GET">
          {% csrf_token%}

{{pobj.id}}

${{pobj.price}}

            {% if pobj in cartobjlist %}
              Go to cart
            {% else %}
              Add to cart
            {%endif%}
        </form>

       {%endfor%}

Body:
You did not pass the list to the template, you passed a string named 'cartobjlist' to the template. Indeed:

{'productobj':productobj,'cartobjlist':<s>'cartobjlist'</s>})

That being said, I strongly advice you to fetch the products more efficiently, and furthermore use a set to perform faster lookups, like:

def home(request):
    productobj = Product.objects.all()
    cartobjlist = set(Product.objects.filter(cart__cart2user=request.user))
    return render(
        request,
        'home.html',
        {'productobj':productobj,'cartobjlist':cartobjlist}
    )


来源: stackexchange

问:
Material UI auto complete value and onChange
I'm trying to implement auto complete on Material UI component,

this is their code :

```<code>  <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={option => option.title}
      style={{ width: 300 }}
      renderInput={params => (
        <TextField {...params} label="Combo box" variant="outlined" fullWidth />
      )}
    />
</code>```

the full code you can find here :https://github.com/mui-org/material-ui/blob/master/docs/src/pages/components/autocomplete/ComboBox.js

my question is, how do I add onChange and be able to show the value that was selected, as we do in Input we just show value={} but in here it does not work, and I cannot find anything about it in the documentation, thanks for the help!

答:
If you want to show the value of the textfield I have inserted the following onChange={e=>changeHandler(e.target.value)}

```<code>// in Hooks area
const changeHandler = value => {
    console.log(value); // value should be here
}

  <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={option => option.title}
      style={{ width: 300 }}
      renderInput={params => (
        <TextField onChange={e=>changeHandler(e.target.value)} {...params} label="Combo box" variant="outlined" fullWidth />
      )}
    />

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to implement auto complete on Material UI component,

this is their code :

  <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={option => option.title}
      style={{ width: 300 }}
      renderInput={params => (
        <TextField {...params} label="Combo box" variant="outlined" fullWidth />
      )}
    />

the full code you can find here :https://github.com/mui-org/material-ui/blob/master/docs/src/pages/components/autocomplete/ComboBox.js

my question is, how do I add onChange and be able to show the value that was selected, as we do in Input we just show value={} but in here it does not work, and I cannot find anything about it in the documentation, thanks for the help!

Body:
If you want to show the value of the textfield I have inserted the following onChange={e=>changeHandler(e.target.value)}

// in Hooks area
const changeHandler = value => {
    console.log(value); // value should be here
}

  <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={option => option.title}
      style={{ width: 300 }}
      renderInput={params => (
        <TextField onChange={e=>changeHandler(e.target.value)} {...params} label="Combo box" variant="outlined" fullWidth />
      )}
    />


问:
ASP.NET Core 3.1.1 MVC + angular : how should I get all recipes from user(id)?
I'm learning ASP.NET MVC, currently working on single page app in ASP.NET Core 3.1.1 with API's

I have User.cs which has collection of his Recipes.

In my User class I have a property:

```<code>public ICollection<Recipe> Recipes {get; set;}
</code>```

Recipe.cs has properties

```<code>public class Recipe
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Ingredients { get; set; }
    public int PreparationTime { get; set; }
    public string Description { get; set; }
    public DateTime DateAdded { get; set; }
    public ICollection<RecipePhoto> RecipePhotos {get; set;}
    public User User { get; set; }
    public int UserId { get; set; }
}
</code>```

I have 2 controllers, RecipesController and UserController, in which I can do things like GetUser(id), GetUsers(), GetRecipe(id), GetRecipes().

This example shown here is how I get a single user and all users in my controller:

```<code>[Authorize]
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
    private readonly IRecipesRepository _repository;
    private readonly IMapper _mapper;

    public UsersController(IRecipesRepository repository, IMapper mapper)
    {
        _repository = repository;
        _mapper = mapper;
    }

    [HttpGet]
    public async Task<IActionResult> GetUsers ()
    {
        var users = await _repository.GetUsers();

        var usersToReturn = _mapper.Map<IEnumerable<UserForListDto>>(users);

        return Ok(usersToReturn);
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetUser (int id)
    {
        var user = await _repository.GetUser(id);

        var userToReturn = _mapper.Map<UserForDetailDto>(user);

        return Ok(userToReturn);
    }
</code>```

And I would like to get all the user's recipes as well.

I should be something like localhost:4200/users/1/recipes

I'm not sure that the way i'm thinking is good.

Maybe i should try GetRecipes from Recipe class in which is Located UserId ?

I should recive List insead of single user

答:
One solution is to amend your controller to:

```<code>[HttpGet("{id}/{withRecipe?}")]
public async Task<IActionResult> GetUser (int id, bool withRecipe = false)
</code>```

This will match:
/users/1
and also
/users/1/true

Then add a new repository method e.g:

```<code>GetUserWithRecipe(id)
{
return await _context.Users
    .Include(u => u.Recipes)
    .ThenInclude(r => r.RecipePhotos)
    .FirstOrDefaultAsync(r => r.Id == id);
}
</code>```

And back in your controller, do:

```<code>var user = withRecipe? _repository.GetUserWithRecipe(id) : _repository.GetUser(id);
</code>```

Not sure how to use the await keyword with that but you could amend to an 'if' statment instead.

This could be made more efficient by re-using the same repository method / queries instead of creating a separate method but it gives the idea.

Alternative is to create another controller method with:

```<code>[HttpGet("{id}/recipes")]
public async Task<IActionResult> GetUser (int id)
</code>```

Which directly calls the repository method with the recipe include.

This gives you the url as you asked for.

Body:
I'm learning ASP.NET MVC, currently working on single page app in ASP.NET Core 3.1.1 with API's

I have User.cs which has collection of his Recipes.

In my User class I have a property:

public ICollection<Recipe> Recipes {get; set;}

Recipe.cs has properties

public class Recipe
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Ingredients { get; set; }
    public int PreparationTime { get; set; }
    public string Description { get; set; }
    public DateTime DateAdded { get; set; }
    public ICollection<RecipePhoto> RecipePhotos {get; set;}
    public User User { get; set; }
    public int UserId { get; set; }
}

I have 2 controllers, RecipesController and UserController, in which I can do things like GetUser(id), GetUsers(), GetRecipe(id), GetRecipes().

This example shown here is how I get a single user and all users in my controller:

[Authorize]
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
    private readonly IRecipesRepository _repository;
    private readonly IMapper _mapper;

    public UsersController(IRecipesRepository repository, IMapper mapper)
    {
        _repository = repository;
        _mapper = mapper;
    }

    [HttpGet]
    public async Task<IActionResult> GetUsers ()
    {
        var users = await _repository.GetUsers();

        var usersToReturn = _mapper.Map<IEnumerable<UserForListDto>>(users);

        return Ok(usersToReturn);
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetUser (int id)
    {
        var user = await _repository.GetUser(id);

        var userToReturn = _mapper.Map<UserForDetailDto>(user);

        return Ok(userToReturn);
    }

And I would like to get all the user's recipes as well.

I should be something like localhost:4200/users/1/recipes

I'm not sure that the way i'm thinking is good.

Maybe i should try GetRecipes from Recipe class in which is Located UserId ?

I should recive List insead of single user

Body:
One solution is to amend your controller to:

[HttpGet("{id}/{withRecipe?}")]
public async Task<IActionResult> GetUser (int id, bool withRecipe = false)

This will match:
/users/1
and also
/users/1/true

Then add a new repository method e.g:

GetUserWithRecipe(id)
{
return await _context.Users
    .Include(u => u.Recipes)
    .ThenInclude(r => r.RecipePhotos)
    .FirstOrDefaultAsync(r => r.Id == id);
}

And back in your controller, do:

var user = withRecipe? _repository.GetUserWithRecipe(id) : _repository.GetUser(id);

Not sure how to use the await keyword with that but you could amend to an 'if' statment instead.

This could be made more efficient by re-using the same repository method / queries instead of creating a separate method but it gives the idea.

Alternative is to create another controller method with:

[HttpGet("{id}/recipes")]
public async Task<IActionResult> GetUser (int id)

Which directly calls the repository method with the recipe include.

This gives you the url as you asked for.


问:
"Inverse SFINAE" to avoid ambiguous overload
How can I prevent the first template below from instantiating if the second template instantiates? (i.e. if both static_cast<T>(0) and T::zero() are defined)

```<code>template<typename T>
auto zero() ->decltype(static_cast<T>(0)) {
    return static_cast<T>(0);
}

template<typename T>
auto zero() ->decltype(T::zero()) {
    return T::zero();
}
</code>```

答:
If you need to extend it to multiple overloads with fine grained control of overload rank, a common technique is to use tag dispatching.

```<code>template<int r>
struct rank : rank<r - 1> {};

template<>
struct rank<0> {};

template<typename T>
auto zero_impl(rank<0>) -> decltype(static_cast<T>(0)) {
    return static_cast<T>(0);
}

template<typename T>
auto zero_impl(rank<1>) ->decltype(T::zero()) {
    return T::zero();
}

template<typename T>
auto zero() { return zero_impl<T>(rank<10>{}); }
</code>```

Derived to base conversions will prefer the closest base class. Which translates to calling the overload with the highest rank. Since that one will have the best implicit conversion sequence in the eyes of the compiler.

Body:
How can I prevent the first template below from instantiating if the second template instantiates? (i.e. if both static_cast<T>(0) and T::zero() are defined)

template<typename T>
auto zero() ->decltype(static_cast<T>(0)) {
    return static_cast<T>(0);
}

template<typename T>
auto zero() ->decltype(T::zero()) {
    return T::zero();
}

Body:
If you need to extend it to multiple overloads with fine grained control of overload rank, a common technique is to use tag dispatching.

template<int r>
struct rank : rank<r - 1> {};

template<>
struct rank<0> {};

template<typename T>
auto zero_impl(rank<0>) -> decltype(static_cast<T>(0)) {
    return static_cast<T>(0);
}

template<typename T>
auto zero_impl(rank<1>) ->decltype(T::zero()) {
    return T::zero();
}

template<typename T>
auto zero() { return zero_impl<T>(rank<10>{}); }

Derived to base conversions will prefer the closest base class. Which translates to calling the overload with the highest rank. Since that one will have the best implicit conversion sequence in the eyes of the compiler.


问:
How to make a Responsive A4 Page with CSS & JS?
I'm looking for a way to get an A4 responsive page like in this example : https://codepen.io/chriscoyier/pen/VvRoWy. But instead of resizing through a component, it would be using the navigator. Is that actually possible ?

I've been trying to get an answer with the help of the community in thoses posts :

responsive JS/CSS A4,

resize an image proportionnaly with aspect/ratio

A4 rendering page

However, the responsive is different. Because I really need to keep the A4 format from cellphone screens to 4K televisors. Like in any screen, we would see an entire page (not smaller, nor bigger than the screen itself).

In the very last case, I would use media queries but getting a solution with JS would be better. I guess in some way, I need to get the height and adjust the scale even after the page feets the screen. But I can't find a solution alone.

Any help is very welcomed :)

My actual code :

function adjustZoomLevel() {
  var documentWidth = window.innerWidth
    || document.documentElement.clientWidth
    || document.body.clientWidth;

  // 1 cm = 37.795276px;
  var zoomLevel = documentWidth / (21 * 37.795276);

  // stop zooming when book fits page
  if (zoomLevel >= 1) return;

  document.querySelector("body").style.transform = "scale(" + zoomLevel + ")";
}

adjustZoomLevel();

window.addEventListener("resize", adjustZoomLevel);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  padding: 0;
  background: #ddd;
  text-align: center;
  transform-origin: top center;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}

* {
  box-sizing: border-box;
}

.page {
  width: 21cm;
  height: 29.7cm;
  padding: 2cm;
  margin: 1cm 0;
  background: white;
  box-shadow: 0 4px 5px rgba(75, 75, 75, 0.2);
  border: 1px #d3d3d3 solid;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
}</code>```

TITLE

SUBTITLE

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

TITLE

SUBTITLE

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

```

答:
Well, in fact, I made it. I let my code here, if anyone needs it someday :
A4 pages scaled to always fit the screen

function adjustZoom() {
  var documentWidth = window.innerWidth;
  var documentHeight = window.innerHeight;
  var zoomWidth = documentWidth / (23 * 37.795276);
  var zoomHeight = documentHeight / (31.7 * 37.795276);
  var zoomLevel = Math.min(zoomWidth, zoomHeight);
  // stop zooming when book fits page
  if (zoomLevel >= 1) return;
  document.querySelector("body").style.transform = "scale(" + zoomLevel + ")";
}
adjustZoom();
window.addEventListener("resize", adjustZoom);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  padding: 0;
  background: #ddd;
  text-align: center;
  transform-origin: top center;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}

* {
  box-sizing: border-box;
}

.page {
  width: 21cm;
  height: 29.7cm;
  padding: 2cm;
  margin: 1cm 0;
  background: white;
  box-shadow: 0 4px 5px rgba(75, 75, 75, 0.2);
  border: 1px #d3d3d3 solid;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
}</code>```

TITLE

SUBTITLE

        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

TITLE

SUBTITLE

        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

```

Body:
I'm looking for a way to get an A4 responsive page like in this example : https://codepen.io/chriscoyier/pen/VvRoWy. But instead of resizing through a component, it would be using the navigator. Is that actually possible ?

I've been trying to get an answer with the help of the community in thoses posts :

responsive JS/CSS A4,

resize an image proportionnaly with aspect/ratio

A4 rendering page

However, the responsive is different. Because I really need to keep the A4 format from cellphone screens to 4K televisors. Like in any screen, we would see an entire page (not smaller, nor bigger than the screen itself).

In the very last case, I would use media queries but getting a solution with JS would be better. I guess in some way, I need to get the height and adjust the scale even after the page feets the screen. But I can't find a solution alone.

Any help is very welcomed :)

My actual code :

function adjustZoomLevel() {
  var documentWidth = window.innerWidth
    || document.documentElement.clientWidth
    || document.body.clientWidth;

  // 1 cm = 37.795276px;
  var zoomLevel = documentWidth / (21 * 37.795276);

  // stop zooming when book fits page
  if (zoomLevel >= 1) return;

  document.querySelector("body").style.transform = "scale(" + zoomLevel + ")";
}

adjustZoomLevel();

window.addEventListener("resize", adjustZoomLevel);

body {
  margin: 0;
  padding: 0;
  background: #ddd;
  text-align: center;
  transform-origin: top center;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}

* {
  box-sizing: border-box;
}

.page {
  width: 21cm;
  height: 29.7cm;
  padding: 2cm;
  margin: 1cm 0;
  background: white;
  box-shadow: 0 4px 5px rgba(75, 75, 75, 0.2);
  border: 1px #d3d3d3 solid;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
}

TITLE

SUBTITLE

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

TITLE

SUBTITLE

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

Body:
Well, in fact, I made it. I let my code here, if anyone needs it someday :
A4 pages scaled to always fit the screen

function adjustZoom() {
  var documentWidth = window.innerWidth;
  var documentHeight = window.innerHeight;
  var zoomWidth = documentWidth / (23 * 37.795276);
  var zoomHeight = documentHeight / (31.7 * 37.795276);
  var zoomLevel = Math.min(zoomWidth, zoomHeight);
  // stop zooming when book fits page
  if (zoomLevel >= 1) return;
  document.querySelector("body").style.transform = "scale(" + zoomLevel + ")";
}
adjustZoom();
window.addEventListener("resize", adjustZoom);

body {
  margin: 0;
  padding: 0;
  background: #ddd;
  text-align: center;
  transform-origin: top center;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}

* {
  box-sizing: border-box;
}

.page {
  width: 21cm;
  height: 29.7cm;
  padding: 2cm;
  margin: 1cm 0;
  background: white;
  box-shadow: 0 4px 5px rgba(75, 75, 75, 0.2);
  border: 1px #d3d3d3 solid;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
}

<body>
  <section id="one" class="page">
    <img src="https://helpx.adobe.com/content/dam/help/en/stock/how-to/visual-reverse-image-search/jcr_content/main-pars/image/visual-reverse-image-search-v2_intro.jpg"
      alt="" />
    <h3>TITLE</h2>
      <h3>SUBTITLE</h3>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
      </p>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
      </p>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
      </p>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
      </p>
  </section>
  <section id="two" class="page">
    <img src="https://helpx.adobe.com/content/dam/help/en/stock/how-to/visual-reverse-image-search/jcr_content/main-pars/image/visual-reverse-image-search-v2_intro.jpg"
      alt="" />
    <h3>TITLE</h2>
      <h3>SUBTITLE</h3>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
      </p>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
      </p>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
      </p>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
        pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
      </p>
  </section>
</body>


问:
Why do I get a NZEC error?
I'm working in Pascal, I don't understand why I'm getting an NZEC (Non Zero Exit Code) error when I'm submitting my problem. On my PC it works perfectly. Can you give me your opinion please?</p>

```<code>program super_factor_sum;
var k,i,j,s:longint;   f,g:text;

function prim(x:integer):boolean; var d:longint;
begin
prim:=true;
for d:=2 to x div 2 do if x mod d=0 then prim:=false;
end;

begin assign(f,'input.txt'); reset(f); assign(g,'output.txt'); rewrite(g);
while not eof(f) do
begin readln(f,k);  s:=0;  i:=2;
      while (k<>1) or (i<=k) do
            begin if (prim(i)) and (k mod i=0) then
                       begin j:=0;
                             repeat k:=k div i; j:=j+1;
                             until k mod i<>0;
                             s:=s+i*j; i:=i+1;
                       end
                             else i:=i+1;
            end;
      write(s);   writeln(g,s);
end;
close(f);  close(g);
end.
</code>```

答:
Avoid NZEC error in Erlang in SPOJ

"module name always has to be tested and the entry point should be function main . For example, after compilation it should be run as tested:main()"

ContentLicense: CC BY-SA 3.0

Title: Why do I get a NZEC error?

Body:
I'm working in Pascal, I don't understand why I'm getting an NZEC (Non Zero Exit Code) error when I'm submitting my problem. On my PC it works perfectly. Can you give me your opinion please?

program super_factor_sum;
var k,i,j,s:longint;   f,g:text;

function prim(x:integer):boolean; var d:longint;
begin
prim:=true;
for d:=2 to x div 2 do if x mod d=0 then prim:=false;
end;

begin assign(f,'input.txt'); reset(f); assign(g,'output.txt'); rewrite(g);
while not eof(f) do
begin readln(f,k);  s:=0;  i:=2;
      while (k<>1) or (i<=k) do
            begin if (prim(i)) and (k mod i=0) then
                       begin j:=0;
                             repeat k:=k div i; j:=j+1;
                             until k mod i<>0;
                             s:=s+i*j; i:=i+1;
                       end
                             else i:=i+1;
            end;
      write(s);   writeln(g,s);
end;
close(f);  close(g);
end.


问:
How to convert text files in a folder into a CSV file
I am trying to write a script to take a bunch of text files in a folder (which are all in the same format) and output them to a csv file. Each file has the same "header" information. I have been able to get information in a more easily usable format (removing the first and last lines, which aren't needed), but am having some trouble after that.

Here is the beginning of the text file, though there will be more than just these 7 lines, there will be a total of 36 lines per file:

```<code>TYPE       VOID
DOB        20200131
DATE       20200131
TIME       21:19:42
TERMINAL   3
ORGTERM    2
EMPLOYEE   1234 John Doe
</code>```

And here is what I have so far, though I know that it doesn't work:

```<code>$currentdir = '.\'
$results = @()
$outputfilename = 'data.csv'

foreach ($req in Get-ChildItem($currentdir)) {

(Get-Content $req)[1..((Get-Content $req).count - 2)] |
    ForEach-Object {
        $header = $_[0] -split '`t'
        $data = $_[1] -split '`t'
        $results = $header, $data
    }
}
</code>```

The final product would look something like this:

```<code>       A               B            C            D          E            F             G
1     TYPE            DOB          DATE         TIME     TERMINAL     ORGTERM       EMPLOYEE
2     VOID          20200131     20200131     21:19:42      3            2          1234 John Doe
3     AUTHORIZE     20200131     20200131     23:29:22      2                       4678 Jane Doe
</code>```

Full sample of VOID file:

```<code>BEGIN
TYPE       VOID
DOB        20200131
DATE       20200131
TIME       21:19:42
TERMINAL   3
ORGTERM    2
EMPLOYEE   1234 Jane Doe
TABLE      TBL 101
CHECK      20030
PAYMENT    20029
AUTHAMT    20.68
BATCHAMT   20.68
CARDTYPE   MASTERCARD
CARDMASK   XXXXXXXXXXXXXXXXX
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0423
REF        482
STANDALONE YES
PINDEX     1
APPROVEAMT 20.68
LOGTIME    21:07:01
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
ACTIONCODE 000
LASTSEND   1580585993
ORIGDATE   20200131
ORIGTIME   21:02:11
ORIGTYPE   AUTHORIZE
ORIGREF    482
ORGREFTIME 21:02:11
TENDER_NUM 12
CRCY       840
VPD        Sequence #: 107
REVID      2
REVNAME    712 Bar
END
</code>```

Sample AUTHORIZE file:

```<code>BEGIN
TYPE       AUTHORIZE
DOB        20200131
DATE       20200131
TIME       23:29:22
TERMINAL   2
EMPLOYEE   1234 Jane Doe
TABLE      Table 121
CHECK      20045
PAYMENT    20038
AUTHAMT    72.42
BATCHAMT   72.42
CARDTYPE   VISA
CARDMASK   XXXXXXXXXXXXXXXX
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0124
REF        485900
STANDALONE YES
PINDEX     1
LOGTIME    23:29:22
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
LASTSEND   1580586235
TENDER_NUM 13
CRCY       840
REVID      1
REVNAME    712 Restaurant
COMMERROR  TRUE
END
</code>```

Sample adjust file:

```<code>BEGIN
TYPE       ADJUST
DOB        20200131
DATE       20200131
TIME       22:18:27
TERMINAL   8
ORGTERM    8
EMPLOYEE   789 Judy Garland
TABLE      BAR GUEST
CHECK      80161
PAYMENT    80036
BATCHAMT   30.43
BATCHTIP   6
CARDTYPE   MASTERCARD
CARDMASK   XXXXXXXXXXXX8699
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0323
REF        1504602
STANDALONE YES
PINDEX     1
LOGTIME    22:18:27
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
LASTSEND   1580638928
TENDER_NUM 12
CRCY       840
REVID      4
REVNAME    712 Second Bar
END
</code>```

答:
To capture all fields in the files without hardcoding the headers and combine them into a CSV file, the below code should do it.

Snag is that there is one line in each file that does not have a 'Header', it is just a string {XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}.

I'm guessing that should be the Card Number, so I'm manually inserting the header CARDNUMBER there. If this is something else, please change that in the code.

```<code>$files = Get-ChildItem -Path 'D:\Test' -File

$result = foreach($file in $files) {
    $obj = [PsCustomObject]@{}
    Get-Content -Path $file.FullName | Where-Object { $_ -notmatch '^(BEGIN|END)$' } | ForEach-Object {
        # There is a line without 'header' name. Is this the card number?
        if ($_ -like '{*}') {
            $name = 'CARDNUMBER'  # <-- add your own preferred header name here
            $value = $_
        }
        else {
            $name,$value = $_ -split '\s+', 2
        }
        $obj | Add-Member -MemberType NoteProperty -Name $name -Value $value
    }
    # output the object for this file to be colected in the $result variable
    $obj
}

# output on screen
$result

#output  to CSV file
$result | Export-Csv -Path 'D:\output.csv' -NoTypeInformation
</code>```

You need to set the paths for Get-ChildItem and Export-CSV to match your own situation of course

Body:
I am trying to write a script to take a bunch of text files in a folder (which are all in the same format) and output them to a csv file. Each file has the same "header" information. I have been able to get information in a more easily usable format (removing the first and last lines, which aren't needed), but am having some trouble after that.

Here is the beginning of the text file, though there will be more than just these 7 lines, there will be a total of 36 lines per file:

TYPE       VOID
DOB        20200131
DATE       20200131
TIME       21:19:42
TERMINAL   3
ORGTERM    2
EMPLOYEE   1234 John Doe

And here is what I have so far, though I know that it doesn't work:

$currentdir = '.\'
$results = @()
$outputfilename = 'data.csv'

foreach ($req in Get-ChildItem($currentdir)) {

(Get-Content $req)[1..((Get-Content $req).count - 2)] |
    ForEach-Object {
        $header = $_[0] -split '`t'
        $data = $_[1] -split '`t'
        $results = $header, $data
    }
}

The final product would look something like this:

       A               B            C            D          E            F             G
1     TYPE            DOB          DATE         TIME     TERMINAL     ORGTERM       EMPLOYEE
2     VOID          20200131     20200131     21:19:42      3            2          1234 John Doe
3     AUTHORIZE     20200131     20200131     23:29:22      2                       4678 Jane Doe

Full sample of VOID file:

BEGIN
TYPE       VOID
DOB        20200131
DATE       20200131
TIME       21:19:42
TERMINAL   3
ORGTERM    2
EMPLOYEE   1234 Jane Doe
TABLE      TBL 101
CHECK      20030
PAYMENT    20029
AUTHAMT    20.68
BATCHAMT   20.68
CARDTYPE   MASTERCARD
CARDMASK   XXXXXXXXXXXXXXXXX
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0423
REF        482
STANDALONE YES
PINDEX     1
APPROVEAMT 20.68
LOGTIME    21:07:01
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
ACTIONCODE 000
LASTSEND   1580585993
ORIGDATE   20200131
ORIGTIME   21:02:11
ORIGTYPE   AUTHORIZE
ORIGREF    482
ORGREFTIME 21:02:11
TENDER_NUM 12
CRCY       840
VPD        Sequence #: 107
REVID      2
REVNAME    712 Bar
END

Sample AUTHORIZE file:

BEGIN
TYPE       AUTHORIZE
DOB        20200131
DATE       20200131
TIME       23:29:22
TERMINAL   2
EMPLOYEE   1234 Jane Doe
TABLE      Table 121
CHECK      20045
PAYMENT    20038
AUTHAMT    72.42
BATCHAMT   72.42
CARDTYPE   VISA
CARDMASK   XXXXXXXXXXXXXXXX
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0124
REF        485900
STANDALONE YES
PINDEX     1
LOGTIME    23:29:22
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
LASTSEND   1580586235
TENDER_NUM 13
CRCY       840
REVID      1
REVNAME    712 Restaurant
COMMERROR  TRUE
END

Sample adjust file:

BEGIN
TYPE       ADJUST
DOB        20200131
DATE       20200131
TIME       22:18:27
TERMINAL   8
ORGTERM    8
EMPLOYEE   789 Judy Garland
TABLE      BAR GUEST
CHECK      80161
PAYMENT    80036
BATCHAMT   30.43
BATCHTIP   6
CARDTYPE   MASTERCARD
CARDMASK   XXXXXXXXXXXX8699
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0323
REF        1504602
STANDALONE YES
PINDEX     1
LOGTIME    22:18:27
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
LASTSEND   1580638928
TENDER_NUM 12
CRCY       840
REVID      4
REVNAME    712 Second Bar
END

Body:
To capture all fields in the files without hardcoding the headers and combine them into a CSV file, the below code should do it.

Snag is that there is one line in each file that does not have a 'Header', it is just a string {XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}.

I'm guessing that should be the Card Number, so I'm manually inserting the header CARDNUMBER there. If this is something else, please change that in the code.

$files = Get-ChildItem -Path 'D:\Test' -File

$result = foreach($file in $files) {
    $obj = [PsCustomObject]@{}
    Get-Content -Path $file.FullName | Where-Object { $_ -notmatch '^(BEGIN|END)$' } | ForEach-Object {
        # There is a line without 'header' name. Is this the card number?
        if ($_ -like '{*}') {
            $name = 'CARDNUMBER'  # <-- add your own preferred header name here
            $value = $_
        }
        else {
            $name,$value = $_ -split '\s+', 2
        }
        $obj | Add-Member -MemberType NoteProperty -Name $name -Value $value
    }
    # output the object for this file to be colected in the $result variable
    $obj
}

# output on screen
$result

#output  to CSV file
$result | Export-Csv -Path 'D:\output.csv' -NoTypeInformation

You need to set the paths for Get-ChildItem and Export-CSV to match your own situation of course


问:
The smallest `max_arity` of compound terms in ISO Prolog programs
Prolog systems aiming at iso-prolog conformity do not have to support compound terms with arbitrarily large arities. The Prolog flag max_arity reflects this.

According to ISO/IEC 13211-1:1995:

7.11.2.3   Flag: max_arity

Possible values: The default value only

Default value: implementation defined

Changeable: No

Description: The maximum arity allowed for any compound term, or unbounded when the processor has no limit for the number of arguments for a compound term.

So Prolog systems may or may not impose an upper limit on max_arity ... but what about the lower limit?  Is, say, 5 okay?

NO!
ISO/IEC 13211-1:1995/Cor.2:2012, Technical Corrigendum 2, defines call/2..8 as:

8.15.4 call/2..8
 ...

NOTE — A standard-conforming processor may implement call/N in one of the following ways because error condition d is implementation dependent (3.91).

Implement only the seven built-in predicates call/2 up to call/8.

Implement call/2..N up to any N that is within 8..max_arity (7.11.2.3). Produce existence errors for larger arities below max_arity.

Implement call/9 and above only for certain execution modes.

All of these ways only imply Max_arity >= 8—but nothing more.

So my question has (at least) two sides:

Prolog User:

"What is the maximum arity I may use if I want to avoid vendor lock-in?"

Prolog Implementor:

"What is the smallest Max_arity I must support if I aim1 at ISO-Prolog conformity?"

Right now, I'm quite sure the answer is this:

Yes, Max_arity = 8 is okay.

But is it in fact so? Are there clues I am missing?

Footnotes:
 1) I do.

答:
Ad 2: Standard conformity is a precondition for a working system. It is by no means a guarantee that a system is fit for any purpose including the one you are (reasonably) interested in. Given that, I'd say 1 is the minimum, as zero cannot be the arity of a compound term. Of course, any attempt to produce a list would produce a representation error. It could be worse, see Purpose of this.

The usage of built-ins with higher arity (5 or 8) is not precluded in such a processor. After all, a conforming processor needs just to prepare Prolog text for execution (5.1.a) and correctly execute Prolog goals (5.1.b). Nowhere is it stated that such goals are represented as compound terms.

But of course that is what we expect, as we expect to be able to program our own top level loop which is itself out of scope of ISO/IEC 13211-1.

Ad 1: As for future portability, 255 appears to be the minimum. But IF has 127. Minerva 125. Of course unbounded would be the best choice, with up to 7 for fast and compact representation.

Are there clues I am missing?

The relation of compound terms to predicates is often overseen in this context.  A system may support predicates with only a smaller arity than max_arity — the appropriate error to issue here would be a resource_error. Compare this situation to a system with current_prolog_flag(max_arity, unbounded) and the goal functor(F,f,N) with N exceeding the processor's address space (in current implementations). While such a goal would never succeed in current implementations, it still issues a resource_error and not a representation_error.


问:
ANTLR parsing works when using TestRig, but fails when parsing with Java
I have a grammar for evaluating csv files, and it works correctly according to TestRig. The following parse tree is generated:

If, however I use the following java code in my application, the parsing fails with an error:

```<code>line 2:33 no viable alternative at input '=A2+B2+C1'
</code>```

Update: I'm now using the Char stream directly from file, but the error still remains.

```<code> private static void parseFile(String fileName) throws IOException {
        CSVLexer lexer = new CSVLexer(CharStreams.fromFileName("test.csv", StandardCharsets.UTF_8));
        CSVParser parser = new CSVParser(new CommonTokenStream(lexer));
        ParseTree tree = parser.start(); //start is the start rule
 }
</code>```

It is my understanding that the TestRig does the same, so how can that succeed, and this fail?

Here is test.csv that im using to test:

```<code>12;=35.5+6*2;=A1+B1
"szoveg";"masik szoveg";=A2+B2+C1
</code>```

As to how im calling the TestRig, im using the command line:

```<code>java -cp path\to\antln\jar org.antlr.v4.gui.TestRig CSV start -gui
</code>```

UPDATE: when using

```<code>java -cp path\to\antln\jar org.antlr.v4.gui.TestRig CSV start -gui test.csv
</code>```

I get the same error.

答:
So the problem was that my grammar requires a line break at the end of each line, and the test.csv DID NOT have a linebreak at the last line!

Upon hitting enter at the last line and saving, it now works.

Solution: To rewrite the line rule to make the last linebreak optional
or use java to add a linebreak at the end of the string read from file (I choose this)

```<code>if(!fileContent.endsWith("\n")) {
    fileContent += "\n";
}
</code>```

Body:
I have a grammar for evaluating csv files, and it works correctly according to TestRig. The following parse tree is generated:

If, however I use the following java code in my application, the parsing fails with an error:

line 2:33 no viable alternative at input '=A2+B2+C1'

Update: I'm now using the Char stream directly from file, but the error still remains.

 private static void parseFile(String fileName) throws IOException {
        CSVLexer lexer = new CSVLexer(CharStreams.fromFileName("test.csv", StandardCharsets.UTF_8));
        CSVParser parser = new CSVParser(new CommonTokenStream(lexer));
        ParseTree tree = parser.start(); //start is the start rule
 }

It is my understanding that the TestRig does the same, so how can that succeed, and this fail?

Here is test.csv that im using to test:

12;=35.5+6*2;=A1+B1
"szoveg";"masik szoveg";=A2+B2+C1

As to how im calling the TestRig, im using the command line:

java -cp path\to\antln\jar org.antlr.v4.gui.TestRig CSV start -gui

UPDATE: when using

java -cp path\to\antln\jar org.antlr.v4.gui.TestRig CSV start -gui test.csv

I get the same error.

Body:
So the problem was that my grammar requires a line break at the end of each line, and the test.csv DID NOT have a linebreak at the last line!

Upon hitting enter at the last line and saving, it now works.

Solution: To rewrite the line rule to make the last linebreak optional
or use java to add a linebreak at the end of the string read from file (I choose this)

if(!fileContent.endsWith("\n")) {
    fileContent += "\n";
}


问:
Groupby and selecting max row within groupby result
Is it possible to groupby and sort results within each groupby result in Python/Pandas? </p>

<p>Trying to find the top Genere in each year in below given data.Tried a lot using groupby and sort but no luck. </p>

```<code>Input::

release_year    Genere      Count

1997            Action      46
1997            Adventure   7
1997            Animation   2
1997            Children's  12
1997            Comedy      73
1997            Crime       22
1997            Documentary 6
1997            Drama       81
1997            Horror      6
1997            Mystery     5
1997            Romance     15
1997            Sci-Fi      1
1997            Thriller    9
1997            War         1

1998            Action      12
1998            Adventure   2
1998            Comedy      24
1998            Crime       6
1998            Documentary 2
1998            Drama       21
1998            Film-Noir   2
1998            Horror      3
1998            Romance     4
1998            Thriller    1

Expected Output:

release_year    Genere      Count
1997            Drama       81
1998            Comedy      24
</code>```

答:
Try:

df=df.sort_values("Count", ascending=False)

df.groupby("release_year").first()
```

<p>Outputs:</p>

<pre class="lang-py prettyprint-override"><code>              Genere  Count
release_year
1997           Drama     81
1998          Comedy     24
</code>```

Body:
Is it possible to groupby and sort results within each groupby result in Python/Pandas?

Trying to find the top Genere in each year in below given data.Tried a lot using groupby and sort but no luck.

Input::

release_year    Genere      Count

1997            Action      46
1997            Adventure   7
1997            Animation   2
1997            Children's  12
1997            Comedy      73
1997            Crime       22
1997            Documentary 6
1997            Drama       81
1997            Horror      6
1997            Mystery     5
1997            Romance     15
1997            Sci-Fi      1
1997            Thriller    9
1997            War         1

1998            Action      12
1998            Adventure   2
1998            Comedy      24
1998            Crime       6
1998            Documentary 2
1998            Drama       21
1998            Film-Noir   2
1998            Horror      3
1998            Romance     4
1998            Thriller    1

Expected Output:

release_year    Genere      Count
1997            Drama       81
1998            Comedy      24

Body:
Try:

df=df.sort_values("Count", ascending=False)

df.groupby("release_year").first()

Outputs:

              Genere  Count
release_year
1997           Drama     81
1998          Comedy     24


问:
Why does the While loop inside the QT loop is not blocking the QT GUI
I am using GLFW along with QT for an opengl application.

i have a while loop inside the main function.

Why the while loop is not blocking the QT GUI ?

```<code>int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    cont.SetName("RootItem");
    TreeModel* model = new TreeModel("RootElement", &cont);
    WavefrontRenderer w(model);
    w.show();
    glfwInit();
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    glfwWindowHint(GLFW_SAMPLES, 4);
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Renderer", nullptr, nullptr);   //
    glfwMakeContextCurrent(window);
    GLenum GlewInitResult;
    glewExperimental = GL_TRUE;
    GlewInitResult = glewInit();

    w.InitData();

    while (!glfwWindowShouldClose(window))
    {
        glClearColor(0.0, 0.3, 0.3, 0.0);
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
        w.render();
        glfwPollEvents();
        glfwSwapBuffers(window);
    }
    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    //return 0;

    return a.exec();
</code>```

}

答:
you are not even starting the Qt application event loop because you are not calling the a.exec() as your code is I side the while loop.
I'm no opengl expert but I guess the window you are seeing is the one rendered by opengl itself not a gl canvas inside you qt application window. </p>

Body:
I am using GLFW along with QT for an opengl application.

i have a while loop inside the main function.

Why the while loop is not blocking the QT GUI ?

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    cont.SetName("RootItem");
    TreeModel* model = new TreeModel("RootElement", &cont);
    WavefrontRenderer w(model);
    w.show();
    glfwInit();
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    glfwWindowHint(GLFW_SAMPLES, 4);
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Renderer", nullptr, nullptr);   //
    glfwMakeContextCurrent(window);
    GLenum GlewInitResult;
    glewExperimental = GL_TRUE;
    GlewInitResult = glewInit();

    w.InitData();

    while (!glfwWindowShouldClose(window))
    {
        glClearColor(0.0, 0.3, 0.3, 0.0);
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
        w.render();
        glfwPollEvents();
        glfwSwapBuffers(window);
    }
    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    //return 0;

    return a.exec();

}


问:
jsonpath find all keys leave contains a string
I'm using the JSON path to my elaborate.
I need to find all final leaves nodes which contain a specific string.
Suppose you have a json :

```<code>{  'nested' :{
              'leaf1' : 'MY_STRING_TO_FIND'
           },
   'leaf2' : 'MY_STRING_TO_FIND'
}
</code>```

my purpose is to output leaf1 and leaf2

答:
The json string in your question is invalid, but if I understand your question correctly and assuming the actual json string looks something like this:

```<code>{
    "nested": {
        "leaf1": "MY_STRING_TO_FIND",
         "leaf2": "some other string",
        "leaf3": "MY_STRING_TO_FIND"
    }
}
</code>```

and assuming you can use jsonpath-plus, then the following expression:

```<code>*[?(@ === "MY_STRING_TO_FIND")]~
</code>```

outputs:

```<code>[
    "leaf1",
    "leaf3"
]
</code>```

Body:
I'm using the JSON path to my elaborate.
I need to find all final leaves nodes which contain a specific string.
Suppose you have a json :

{  'nested' :{
              'leaf1' : 'MY_STRING_TO_FIND'
           },
   'leaf2' : 'MY_STRING_TO_FIND'
}

my purpose is to output leaf1 and leaf2

Body:
The json string in your question is invalid, but if I understand your question correctly and assuming the actual json string looks something like this:

{
    "nested": {
        "leaf1": "MY_STRING_TO_FIND",
         "leaf2": "some other string",
        "leaf3": "MY_STRING_TO_FIND"
    }
}

and assuming you can use jsonpath-plus, then the following expression:

*[?(@ === "MY_STRING_TO_FIND")]~

outputs:

[
    "leaf1",
    "leaf3"
]


问:
how to show the input time in a TextFormField?
I want to make a form so the user can input the date and time of his appointment.
I tried some options but only the date works(it shows the user's input) but the time remains empty even though the TimePicker appears and he can select the time he wants. How can I fix this?</p>

```<code>TextEditingController dateCtl = TextEditingController();

class MyCustomFormState extends State<MyCustomForm> {
final _formKey = GlobalKey<FormState>();
DateTime date = DateTime.now();
@override
Widget build(BuildContext context) {
String _formattedate = new DateFormat.yMMMMEEEEd().format(date);
return Form(
  key: _formKey,
  child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      Padding(
        padding: const EdgeInsets.only(left: 15, right: 15, bottom: 20),
        child: TextFormField(
          controller: dateCtl,
          decoration: InputDecoration(labelText: 'Date*'),
          onTap: () async {
            FocusScope.of(context).requestFocus(new FocusNode());

            DateTime picked = await showDatePicker(
                context: context,
                initialDate: DateTime.now(),
                firstDate: DateTime(2020),
                lastDate: DateTime(2021));
            dateCtl.text = _formattedate.toString();
            if(picked != null && picked != date){
              setState(() {
                date = picked;
              });
            }
          },
          validator: (value) {
            if (value.isEmpty) {
              return 'cant be empty';
            }
            return null;
          },
        ),
      ),
      Padding(
        padding: const EdgeInsets.only(left: 15, right: 15, bottom: 20),
        child: TextFormField(
          decoration: InputDecoration(
            labelText: 'time*',
          ),
          onTap: () async {
            TimeOfDay time = TimeOfDay.now();
            FocusScope.of(context).requestFocus(new FocusNode());

            TimeOfDay picked =
                await showTimePicker(context: context, initialTime: time);
            if (picked != null && picked != time)
              setState(() {
                time = picked;
              });
          },
          validator: (value) {
            if (value.isEmpty) {
              return 'cant be empty';
            }
            return null;
          },
        ),
      ),
    //more code
</code>```

答:
Add this line under the dateCtl.

```<code>TextEditingController timeCtl = TextEditingController();
</code>```

And add 2 lines.

```<code>child: TextFormField(
  controller: timeCtl,  // add this line.
  decoration: InputDecoration(
    labelText: 'time*',
  ),
  onTap: () async {
    TimeOfDay time = TimeOfDay.now();
    FocusScope.of(context).requestFocus(new FocusNode());

    TimeOfDay picked =
        await showTimePicker(context: context, initialTime: time);
    if (picked != null && picked != time) {
      timeCtl.text = picked.toString();  // add this line.
      setState(() {
        time = picked;
      });
    }
  },
  validator: (value) {
    if (value.isEmpty) {
      return 'cant be empty';
    }
    return null;
  },
),
</code>```

format ex 1

```<code>timeCtl.text = picked.format(context);
</code>```

ex 2

```<code>var now = DateTime.now();
var dt = DateTime(now.year, now.month, now.day, picked.hour, picked.minute);
String _formattetime = DateFormat.Hm().format(dt);
timeCtl.text = _formattetime;
</code>```

Body:
I want to make a form so the user can input the date and time of his appointment.
I tried some options but only the date works(it shows the user's input) but the time remains empty even though the TimePicker appears and he can select the time he wants. How can I fix this?

TextEditingController dateCtl = TextEditingController();

class MyCustomFormState extends State<MyCustomForm> {
final _formKey = GlobalKey<FormState>();
DateTime date = DateTime.now();
@override
Widget build(BuildContext context) {
String _formattedate = new DateFormat.yMMMMEEEEd().format(date);
return Form(
  key: _formKey,
  child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      Padding(
        padding: const EdgeInsets.only(left: 15, right: 15, bottom: 20),
        child: TextFormField(
          controller: dateCtl,
          decoration: InputDecoration(labelText: 'Date*'),
          onTap: () async {
            FocusScope.of(context).requestFocus(new FocusNode());

            DateTime picked = await showDatePicker(
                context: context,
                initialDate: DateTime.now(),
                firstDate: DateTime(2020),
                lastDate: DateTime(2021));
            dateCtl.text = _formattedate.toString();
            if(picked != null && picked != date){
              setState(() {
                date = picked;
              });
            }
          },
          validator: (value) {
            if (value.isEmpty) {
              return 'cant be empty';
            }
            return null;
          },
        ),
      ),
      Padding(
        padding: const EdgeInsets.only(left: 15, right: 15, bottom: 20),
        child: TextFormField(
          decoration: InputDecoration(
            labelText: 'time*',
          ),
          onTap: () async {
            TimeOfDay time = TimeOfDay.now();
            FocusScope.of(context).requestFocus(new FocusNode());

            TimeOfDay picked =
                await showTimePicker(context: context, initialTime: time);
            if (picked != null && picked != time)
              setState(() {
                time = picked;
              });
          },
          validator: (value) {
            if (value.isEmpty) {
              return 'cant be empty';
            }
            return null;
          },
        ),
      ),
    //more code

Body:
Add this line under the dateCtl.

TextEditingController timeCtl = TextEditingController();

And add 2 lines.

child: TextFormField(
  controller: timeCtl,  // add this line.
  decoration: InputDecoration(
    labelText: 'time*',
  ),
  onTap: () async {
    TimeOfDay time = TimeOfDay.now();
    FocusScope.of(context).requestFocus(new FocusNode());

    TimeOfDay picked =
        await showTimePicker(context: context, initialTime: time);
    if (picked != null && picked != time) {
      timeCtl.text = picked.toString();  // add this line.
      setState(() {
        time = picked;
      });
    }
  },
  validator: (value) {
    if (value.isEmpty) {
      return 'cant be empty';
    }
    return null;
  },
),

format ex 1

timeCtl.text = picked.format(context);

ex 2

var now = DateTime.now();
var dt = DateTime(now.year, now.month, now.day, picked.hour, picked.minute);
String _formattetime = DateFormat.Hm().format(dt);
timeCtl.text = _formattetime;


问:
Allocated table variation
```<code> PROGRAM satellite
  IMPLICIT NONE
  INTEGER                                  :: i, j, ok, nc
  REAL                                     :: alph, bet, chi, ninf1, C1
  REAL, DIMENSION(:), ALLOCATABLE          :: uexact, x, Econs
  REAL                                     :: E, k, Lc, hc, eps, h

  Read*,nc
  E=25. ; k=125. ; hc=0.01 ; eps=0.01 ; Lc=1 ;

  h = Lc/nc ; chi=sqrt((E*hc)/k) ; alph= -(1/h**2) ; bet=(2/h**2)+(k/(E*hc))

  ALLOCATE(x(0:nc), uexact(0:nc), Econs(0:nc))

  OPEN(UNIT=888,FILE="uetuexact.out",ACTION="write",STATUS='old')
  OPEN(UNIT=889,FILE="consistance.out",ACTION="write",STATUS='old')

  DO i = 0, nc
   x(i) = h*i-Lc/2
   uexact(i) = eps*chi*((sinh(x(i)/chi))/(cosh(Lc/(2*chi))))
 END DO
 !-------------------------------------------------------------------------------
 DO i=1,nc-1
   Econs(i)=(alph*(uexact(i-1)))+(bet*(uexact(i)))+(alph*(uexact(i+1)))
 END DO

 ninf1=maxval(Econs)
 C1=ninf1*(nc**2)

DO i = 0, nc
  WRITE(888,fmt='(3E15.6)') x(i), uexact(i)
  WRITE(889,fmt='(3E15.6)') x(i), uexact(i), -Econs(i)
END DO

Print* , 'nc :', nc
Print* , 'h :', h
Print* , 'ninf1 :', ninf1
Print* , 'C1 :', C1

END PROGRAM satellite
</code>```

I need my nc variable to change from 10,50,100,500,1000,5000,10000 in order to write out for each given nc, the ninf1 and C1 values. For now, i was doing nc manually but i will need a file .out : that gives me nc  | ninf1  | C1. I want to know how can i vary my nc to this values precisely.

答:
You could do the following:

define an array nsizes that would hold all the values you want nc to take.

declare a variable iter that would run along this array

iterate with iter over the length of nsizes

At the beginning of each iteration assign nc = nsizes(iter)

At the end of each iteration deallocate the arrays

Here is a patch that does just that.

```<code>--- satellite.f90   2020-02-16 18:13:35.662123215 +0700
+++ satellite_loop.f90  2020-02-16 18:50:09.662029872 +0700
@@ -1,11 +1,15 @@
 PROGRAM satellite
   IMPLICIT NONE
-  INTEGER                                  :: i, j, ok, nc
+  INTEGER                                  :: i, j, ok, nc, iter
   REAL                                     :: alph, bet, chi, ninf1, C1
   REAL, DIMENSION(:), ALLOCATABLE          :: uexact, x, Econs
   REAL                                     :: E, k, Lc, hc, eps, h
+  INTEGER, DIMENSION(7)                    :: nsizes = (/ 10, 50, 100, 500, 1000, 5000, 10000/)
+
+ !  Read*,nc
+ do  iter = 1, 7
+  nc = nsizes(iter)

-  Read*,nc
   E=25. ; k=125. ; hc=0.01 ; eps=0.01 ; Lc=1 ;

   h = Lc/nc ; chi=sqrt((E*hc)/k) ; alph= -(1/h**2) ; bet=(2/h**2)+(k/(E*hc))
@@ -38,4 +42,8 @@
 Print* , 'ninf1 :', ninf1
 Print* , 'C1 :', C1

+deallocate(x, uexact, econs)
+
+end do
+
 END PROGRAM satellite
</code>```

The output would look like this:

```<code> nc :          10
 h :  0.100000001
 ninf1 :   1.17741162E-02
 C1 :   1.17741168
 nc :          50
 h :   1.99999996E-02
 ninf1 :   2.39971280E-03
 C1 :   5.99928188
 nc :         100
 h :   9.99999978E-03
 ninf1 :   7.46726990E-04
 C1 :   7.46726990
 nc :         500
 h :   2.00000009E-03
 ninf1 :   1.44958496E-04
 C1 :   36.2396240
 nc :        1000
 h :   1.00000005E-03
 ninf1 :   8.23974609E-04
 C1 :   823.974609
 nc :        5000
 h :   1.99999995E-04
 ninf1 :   2.73437500E-02
 C1 :   683593.750
 nc :       10000
 h :   9.99999975E-05
 ninf1 :  0.125000000
 C1 :   12500000.0
</code>```

Title: Allocated table variation

Body:
 PROGRAM satellite
  IMPLICIT NONE
  INTEGER                                  :: i, j, ok, nc
  REAL                                     :: alph, bet, chi, ninf1, C1
  REAL, DIMENSION(:), ALLOCATABLE          :: uexact, x, Econs
  REAL                                     :: E, k, Lc, hc, eps, h

  Read*,nc
  E=25. ; k=125. ; hc=0.01 ; eps=0.01 ; Lc=1 ;

  h = Lc/nc ; chi=sqrt((E*hc)/k) ; alph= -(1/h**2) ; bet=(2/h**2)+(k/(E*hc))

  ALLOCATE(x(0:nc), uexact(0:nc), Econs(0:nc))

  OPEN(UNIT=888,FILE="uetuexact.out",ACTION="write",STATUS='old')
  OPEN(UNIT=889,FILE="consistance.out",ACTION="write",STATUS='old')

  DO i = 0, nc
   x(i) = h*i-Lc/2
   uexact(i) = eps*chi*((sinh(x(i)/chi))/(cosh(Lc/(2*chi))))
 END DO
 !-------------------------------------------------------------------------------
 DO i=1,nc-1
   Econs(i)=(alph*(uexact(i-1)))+(bet*(uexact(i)))+(alph*(uexact(i+1)))
 END DO

 ninf1=maxval(Econs)
 C1=ninf1*(nc**2)

DO i = 0, nc
  WRITE(888,fmt='(3E15.6)') x(i), uexact(i)
  WRITE(889,fmt='(3E15.6)') x(i), uexact(i), -Econs(i)
END DO

Print* , 'nc :', nc
Print* , 'h :', h
Print* , 'ninf1 :', ninf1
Print* , 'C1 :', C1

END PROGRAM satellite

I need my nc variable to change from 10,50,100,500,1000,5000,10000 in order to write out for each given nc, the ninf1 and C1 values. For now, i was doing nc manually but i will need a file .out : that gives me nc  | ninf1  | C1. I want to know how can i vary my nc to this values precisely.

Body:
You could do the following:

define an array nsizes that would hold all the values you want nc to take.

declare a variable iter that would run along this array

iterate with iter over the length of nsizes

At the beginning of each iteration assign nc = nsizes(iter)

At the end of each iteration deallocate the arrays

Here is a patch that does just that.

--- satellite.f90   2020-02-16 18:13:35.662123215 +0700
+++ satellite_loop.f90  2020-02-16 18:50:09.662029872 +0700
@@ -1,11 +1,15 @@
 PROGRAM satellite
   IMPLICIT NONE
-  INTEGER                                  :: i, j, ok, nc
+  INTEGER                                  :: i, j, ok, nc, iter
   REAL                                     :: alph, bet, chi, ninf1, C1
   REAL, DIMENSION(:), ALLOCATABLE          :: uexact, x, Econs
   REAL                                     :: E, k, Lc, hc, eps, h
+  INTEGER, DIMENSION(7)                    :: nsizes = (/ 10, 50, 100, 500, 1000, 5000, 10000/)
+
+ !  Read*,nc
+ do  iter = 1, 7
+  nc = nsizes(iter)

-  Read*,nc
   E=25. ; k=125. ; hc=0.01 ; eps=0.01 ; Lc=1 ;

   h = Lc/nc ; chi=sqrt((E*hc)/k) ; alph= -(1/h**2) ; bet=(2/h**2)+(k/(E*hc))
@@ -38,4 +42,8 @@
 Print* , 'ninf1 :', ninf1
 Print* , 'C1 :', C1

+deallocate(x, uexact, econs)
+
+end do
+
 END PROGRAM satellite

The output would look like this:

 nc :          10
 h :  0.100000001
 ninf1 :   1.17741162E-02
 C1 :   1.17741168
 nc :          50
 h :   1.99999996E-02
 ninf1 :   2.39971280E-03
 C1 :   5.99928188
 nc :         100
 h :   9.99999978E-03
 ninf1 :   7.46726990E-04
 C1 :   7.46726990
 nc :         500
 h :   2.00000009E-03
 ninf1 :   1.44958496E-04
 C1 :   36.2396240
 nc :        1000
 h :   1.00000005E-03
 ninf1 :   8.23974609E-04
 C1 :   823.974609
 nc :        5000
 h :   1.99999995E-04
 ninf1 :   2.73437500E-02
 C1 :   683593.750
 nc :       10000
 h :   9.99999975E-05
 ninf1 :  0.125000000
 C1 :   12500000.0


问:
Is there any other purpose of "dictionary.get" function in Python with two elements in it, apart from checking for a variable in the list?
I thougt it could store the answer for the case when user inputs a wrong key in it, like this:

```<code>month_conversion.get("Git", "Not a valid key")
month_conversion = input()
</code>```

So, if user input "Git" it would print out "Not a valid key"
But it doesn't store it and just prints out "None"

答:
From the docs: To check if a key exists in a dict there is key in dict syntax.

The purpose of .get() method is that the get with [] operators will raise a KeyError exception and this function is meant to not raise KeyError in case that key does not exists.

Body:
I thougt it could store the answer for the case when user inputs a wrong key in it, like this:

month_conversion.get("Git", "Not a valid key")
month_conversion = input()

So, if user input "Git" it would print out "Not a valid key"
But it doesn't store it and just prints out "None"


问:
Issue with condition in headerright
I try to add a conditional button in headerright but I get an error message that (probably) says this is not the way to go. I am sure the error is in the condition within the headerright of the stacknavbigator, since when I try with a straight button it works.

This is the stacknavigator code

```<code>const AppNavigator = createStackNavigator(
  {
    Loading: Loading,
    SignUp: SignUp,
    Login: Login,
    Main: Main,
  },
  {
    initialRouteName: 'Loading',

    defaultNavigationOptions: {
      headerLeft: null,
      headerRight:
      () => (
        if this.loggedIn: true {

          <Button
          onPress={() => alert('I know you')}
          title="Log-out"
          color="#fff"
          />
        }

        else {
          <Button
          onPress={() => alert('Please log in')}
          title="Log-in"
          color="#fff"
          />
             }
      );
      headerStyle: {
        backgroundColor: '#c6f1e7',
      },
      headerTintColor: '#59616e',
      headerTitleStyle: {
        fontFamily: 'Raleway-Regular',
        fontWeight: '400',
      },
    },
  },
);
</code>```

Where the fucntion in headerright is causing this error:

```<code>Error: TransformError SyntaxError: /Users/tim/Dropbox/co-own.it/apps/kowop/App.js: Unexpected token (33:8)

  31 |       headerLeft: null,
  32 |       headerRight: () => (
> 33 |         if this.loggedIn: true {
     |         ^
  34 |           <Button
  35 |           onPress={() => alert('I know you')}
  36 |           title="Log-out"

showCompileError
    index.bundle?platform=ios&dev=true&minify=false:34606:26
<unknown>
    index.bundle?platform=ios&dev=true&minify=false:34545:29
emit
    index.bundle?platform=ios&dev=true&minify=false:35025:35
<unknown>
    index.bundle?platform=ios&dev=true&minify=false:34872:23
dispatchEvent
    index.bundle?platform=ios&dev=true&minify=false:32343:31
<unknown>
</code>```

Can anyone point me in the good direction, since I can't really find the answer?

Thanks a lot!

Tim

答:
Looks like you are using a '(' where you should use a '{' when defining the function

```<code>   headerRight: () => (
</code>```

should be

```<code>headerRight: () => {

    code goes here
}
</code>```

Title: Issue with condition in headerright

Body:
I try to add a conditional button in headerright but I get an error message that (probably) says this is not the way to go. I am sure the error is in the condition within the headerright of the stacknavbigator, since when I try with a straight button it works.

This is the stacknavigator code

const AppNavigator = createStackNavigator(
  {
    Loading: Loading,
    SignUp: SignUp,
    Login: Login,
    Main: Main,
  },
  {
    initialRouteName: 'Loading',

    defaultNavigationOptions: {
      headerLeft: null,
      headerRight:
      () => (
        if this.loggedIn: true {

          <Button
          onPress={() => alert('I know you')}
          title="Log-out"
          color="#fff"
          />
        }

        else {
          <Button
          onPress={() => alert('Please log in')}
          title="Log-in"
          color="#fff"
          />
             }
      );
      headerStyle: {
        backgroundColor: '#c6f1e7',
      },
      headerTintColor: '#59616e',
      headerTitleStyle: {
        fontFamily: 'Raleway-Regular',
        fontWeight: '400',
      },
    },
  },
);

Where the fucntion in headerright is causing this error:

Error: TransformError SyntaxError: /Users/tim/Dropbox/co-own.it/apps/kowop/App.js: Unexpected token (33:8)

  31 |       headerLeft: null,
  32 |       headerRight: () => (
> 33 |         if this.loggedIn: true {
     |         ^
  34 |           <Button
  35 |           onPress={() => alert('I know you')}
  36 |           title="Log-out"

showCompileError
    index.bundle?platform=ios&dev=true&minify=false:34606:26
<unknown>
    index.bundle?platform=ios&dev=true&minify=false:34545:29
emit
    index.bundle?platform=ios&dev=true&minify=false:35025:35
<unknown>
    index.bundle?platform=ios&dev=true&minify=false:34872:23
dispatchEvent
    index.bundle?platform=ios&dev=true&minify=false:32343:31
<unknown>

Can anyone point me in the good direction, since I can't really find the answer?

Thanks a lot!

Tim

Body:
Looks like you are using a '(' where you should use a '{' when defining the function

   headerRight: () => (

should be

headerRight: () => {

    code goes here
}


问:
Spark joins performance issue
I'm trying to merge historical and incremental data. As part of the incremental data, I'm getting deletes. Below is the case.

historical data  - 100 records ( 20 columns, id is the key column)

incremental data - 10 records  ( 20 columns, id is the key column)

Out of the 10 records in incremental data, only 5 will match with historical data.

Now I want 100 records in the final dataframe of which 95 records belong to historical data and 5 records belong to incremental data(wherever id column is match).

Update timestamp field is available in both historical and incremental data.

Below is the approach I tried.

```<code>    DF1 - Historical  Data
    DF2 - Incremental Delete Dataset
    DF3 = DF1 LEFTANTIJOIN DF2
    DF4 = DF2 INNERJOIN DF1
    DF5 = DF3 UNION DF4
</code>```

However, I observed It has lot of performance issue as I'm running this join on billions of records. Any better way to do this?

答:
Below is the approach I did.</p>

```<code>historical_data.as("a").join(
incr_data.as("b"),
$"a.id" === $"b.id", "full")
.select(historical_data.columns.map(f => expr(s"""case when a.id=b.id then b.${f} else a.${f} end as $f""")): _*)
</code>```

Title: Spark joins performance issue

Body:
I'm trying to merge historical and incremental data. As part of the incremental data, I'm getting deletes. Below is the case.

historical data  - 100 records ( 20 columns, id is the key column)

incremental data - 10 records  ( 20 columns, id is the key column)

Out of the 10 records in incremental data, only 5 will match with historical data.

Now I want 100 records in the final dataframe of which 95 records belong to historical data and 5 records belong to incremental data(wherever id column is match).

Update timestamp field is available in both historical and incremental data.

Below is the approach I tried.

    DF1 - Historical  Data
    DF2 - Incremental Delete Dataset
    DF3 = DF1 LEFTANTIJOIN DF2
    DF4 = DF2 INNERJOIN DF1
    DF5 = DF3 UNION DF4

However, I observed It has lot of performance issue as I'm running this join on billions of records. Any better way to do this?

Body:
Below is the approach I did.

historical_data.as("a").join(
incr_data.as("b"),
$"a.id" === $"b.id", "full")
.select(historical_data.columns.map(f => expr(s"""case when a.id=b.id then b.${f} else a.${f} end as $f""")): _*)


问:
Printing the extension of a file name in python
Can Anyone explain why we are taking [-1] and the use of repr function over here.
Can't we use any other function ? </p>

```<code>filename = input("Input the Filename: ")
f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))
</code>```

答:
In this example, that you have shared :

```<code>filename = input("Input the Filename: ")
f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))
</code>```

Use of repr() is explained here.

split() method will split the string on the occurrence of . and you will be getting an list type of object as a result.
You can check that by type(f_extns) which is <class 'list'>.

As extensions are after dot for retrieving last element of the list by using negative index f_extns[-1] or you can use f_extns[len(f_extns) - 1].

Another way you can achieve this by :

```<code>import os
filename = input("Input the Filename: ")  # demo.py
name, ext = os.path.splitext(filename)    # name = "demo", ext = ".py"
ext_with_dot = ext[1:]
print ("The extension of the file is : " + ext)
</code>```

Body:
Can Anyone explain why we are taking [-1] and the use of repr function over here.
Can't we use any other function ?

filename = input("Input the Filename: ")
f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))

Body:
In this example, that you have shared :

filename = input("Input the Filename: ")
f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))

Use of repr() is explained here.

split() method will split the string on the occurrence of . and you will be getting an list type of object as a result.
You can check that by type(f_extns) which is <class 'list'>.

As extensions are after dot for retrieving last element of the list by using negative index f_extns[-1] or you can use f_extns[len(f_extns) - 1].

Another way you can achieve this by :

import os
filename = input("Input the Filename: ")  # demo.py
name, ext = os.path.splitext(filename)    # name = "demo", ext = ".py"
ext_with_dot = ext[1:]
print ("The extension of the file is : " + ext)


问:
Tricky situation calling variable with ÅÄÖ and & afterwards
I have these tricky problems.

On my site I allow registrations with the characters åäö in them, and I have friendly URLs linking to their profile, so lets say an URL looks like this:

example.com/profile/åäöismyname/

and the userfriendly variable is $_GET['vanlig'].

Now, this is called example.com/profile/åäömyname&favorisera

$_GET['vanlig'] is now called as åäömyname&favorisera instead of åäömyname, and &favorisera is not called.

This works perfectly fine as long as I don't have åäö in the $_GET variable, &favorisera is then called properly.

Any suggestions to this? Changing their friendly names is not an option. Since this may cause duplicate names in the DB.

I'm using nginx as a webserver for friendly URLs.

EDIT:

i tried this

```<code>$userid = urlencode($userid);

<div class="privat" onclick="window.location = '/profil/<?=$userid?>&favorisera'" style="cursor:pointer;" title=""></div>
</code>```

without any success, the linking shows ( as an actual example from the source code ) :

```<code><div class="privat" onclick="window.location = '/profil/k%C3%A5taelin&favorisera'" style="cursor:pointer;" title=""></div>
</code>```

When clicked, i return a var dump of $_GET['vanlig'], which results in string(19) "kåtaelin&favorisera" anyway.

答: You need a question mark to start the query string.</p>

Body:
I have these tricky problems.

On my site I allow registrations with the characters åäö in them, and I have friendly URLs linking to their profile, so lets say an URL looks like this:

example.com/profile/åäöismyname/

and the userfriendly variable is $_GET['vanlig'].

Now, this is called example.com/profile/åäömyname&favorisera

$_GET['vanlig'] is now called as åäömyname&favorisera instead of åäömyname, and &favorisera is not called.

This works perfectly fine as long as I don't have åäö in the $_GET variable, &favorisera is then called properly.

Any suggestions to this? Changing their friendly names is not an option. Since this may cause duplicate names in the DB.

I'm using nginx as a webserver for friendly URLs.

EDIT:

i tried this

$userid = urlencode($userid);

<div class="privat" onclick="window.location = '/profil/<?=$userid?>&favorisera'" style="cursor:pointer;" title="">

without any success, the linking shows ( as an actual example from the source code ) :

When clicked, i return a var dump of $_GET['vanlig'], which results in string(19) "kåtaelin&favorisera" anyway.


问:
The view above recyclerview is skipped
I have CardView above RecycleView, but when Page is loaded RecyclerView is  on the top and CardView is skipped. Why can this happen?</p>
```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ProgressBar
            android:id="@+id/homeProgress"
            android:layout_width="100dp"
            android:layout_height="100dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:progressTint="@color/colorText"
            android:visibility="visible"/>

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/homeMainLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/colorBackground"
            android:padding="10dp"
            android:visibility="gone">

            <androidx.cardview.widget.CardView
                android:id="@+id/firstPlace"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/colorCardView"
                app:cardCornerRadius="10dp"
                android:padding="10dp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:padding="10dp">

                        <TextView
                            android:id="@+id/firstPlaceName"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textSize="30sp"
                            android:textColor="@color/colorText"/>

                        <TextView
                            android:id="@+id/firstPlaceCount"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textSize="15sp"
                            android:textColor="@color/colorText"/>

                    </LinearLayout>

                    <ImageView
                        android:id="@+id/firstPlaceImage"
                        android:layout_width="100dp"
                        android:layout_height="100dp"
                        android:layout_alignParentEnd="true"/>

                </RelativeLayout>
            </androidx.cardview.widget.CardView>

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/artistsWithImagesRecycler"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@+id/firstPlace"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                android:overScrollMode="never"
                app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager">

            </androidx.recyclerview.widget.RecyclerView>

        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
</code>```

答:
Add weight to cardview and recyclerview or change constraint layout to relative layout, remove below lines in recyclerview

app:layout_constraintStart_toStartOf="parent"
 app:layout_constraintEnd_toEndOf="parent

Title: The view above recyclerview is skipped

Body:
I have CardView above RecycleView, but when Page is loaded RecyclerView is  on the top and CardView is skipped. Why can this happen?

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ProgressBar
            android:id="@+id/homeProgress"
            android:layout_width="100dp"
            android:layout_height="100dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:progressTint="@color/colorText"
            android:visibility="visible"/>

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/homeMainLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/colorBackground"
            android:padding="10dp"
            android:visibility="gone">

            <androidx.cardview.widget.CardView
                android:id="@+id/firstPlace"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/colorCardView"
                app:cardCornerRadius="10dp"
                android:padding="10dp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:padding="10dp">

                        <TextView
                            android:id="@+id/firstPlaceName"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textSize="30sp"
                            android:textColor="@color/colorText"/>

                        <TextView
                            android:id="@+id/firstPlaceCount"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textSize="15sp"
                            android:textColor="@color/colorText"/>

                    </LinearLayout>

                    <ImageView
                        android:id="@+id/firstPlaceImage"
                        android:layout_width="100dp"
                        android:layout_height="100dp"
                        android:layout_alignParentEnd="true"/>

                </RelativeLayout>
            </androidx.cardview.widget.CardView>

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/artistsWithImagesRecycler"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@+id/firstPlace"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                android:overScrollMode="never"
                app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager">

            </androidx.recyclerview.widget.RecyclerView>

        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>