问:
Body content in HTML not full screen although set width 100% in CSS? when responsive
In normal (not responsive yet) my website running good, but after I set responsive to (width: 1336px) for my web it's display screen like this although I've set width for this is 100%

/* Here is my CSS *style.css* */

* {
  box-sizing: border-box;
}

body {
  font-family: 'Montserrat', sans-serif;
  margin: 0;
  width: 100%;
}

/* style for header section */

h1 {
  line-height: 65px;
  font-size: 48px;
}

.header-container {
  background-image: linear-gradient( 0deg, rgba(35, 39, 49, -0.18), rgba(35, 39, 49, 1.82)), url("images/bg-image.jpeg");
  background-repeat: no-repeat;
  background-size: cover;
  box-sizing: border-box;
  position: absolute;
  width: 100%;
  height: 743px;
  left: -1px;
  top: 0px;
}

.nav-bar {
  position: absolute;
  width: 1700px;
  height: 135px;
  left: 69px;
  top: 17px;
  filter: brightness(100%);
}

.header-logo {
  float: left;
}

.nav-content {
  list-style-type: none;
}

.menu-section {
  width: 50%;
  float: right;
  margin-top: 34px;
}

.menu-item {
  float: left;
  display: block;
  margin-right: 70px;
}

/* nav menu */

.nav-content li a {
  text-decoration: none;
  color: #fff;
  font-size: 20px;
}

.nav-content li a:hover {
  color: #00B9F7;
}

/* header title */

.header-title {
  color: #fff;
  text-align: center;
  margin: auto;
  width: 30%;
  padding: 10px;
  margin-top: 10%;
}

/* header video */

.header-video {
  margin-left: 30%;
  width: fit-content;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- here is my HTML code *index.html* -->

<header class="header-container">
  <div class="header-content">
    <div class="nav-bar">
      <div class="header-logo">

          <img id="image-logo-header" class="bottom img-logo" src="images/logo.png">

      </div>

      <div class="menu-section">
        <div class="menu-btn-group">
          <div class="menu-toggle"></div>
          <div class="menu-close"></div>
        </div>
        <div class="navigation navbar-collapse ">
          <nav role="navigation">
            <ul class="nav-content">
              <li class="menu-item">Home</li>
              <li class="menu-item">Blog</li>
              <li class="menu-item">About</li>
              <li class="menu-item">Contact</li>
              <li class="menu-item">Login</li>
              <li class="menu-item">Sign up</li>
            </ul>
          </nav>
        </div>
      </div>
    </div>

    <div class="header-title">
      <h1>SHARE YOUR HOLIDDAY DREAM</h1>
    </div>

    <div class="header-video">
      <img class="video-img" src="images/video-img.png">
    </div>
  </div>
</header></code>```

Can anyone help me, please? your answer is my happiness, thank you so much

答:
Can you try using img: { width: 100vw };?

In css, verify the margins and padding.

Body:
In normal (not responsive yet) my website running good, but after I set responsive to (width: 1336px) for my web it's display screen like this although I've set width for this is 100%

/* Here is my CSS *style.css* */

* {
  box-sizing: border-box;
}

body {
  font-family: 'Montserrat', sans-serif;
  margin: 0;
  width: 100%;
}

/* style for header section */

h1 {
  line-height: 65px;
  font-size: 48px;
}

.header-container {
  background-image: linear-gradient( 0deg, rgba(35, 39, 49, -0.18), rgba(35, 39, 49, 1.82)), url("images/bg-image.jpeg");
  background-repeat: no-repeat;
  background-size: cover;
  box-sizing: border-box;
  position: absolute;
  width: 100%;
  height: 743px;
  left: -1px;
  top: 0px;
}

.nav-bar {
  position: absolute;
  width: 1700px;
  height: 135px;
  left: 69px;
  top: 17px;
  filter: brightness(100%);
}

.header-logo {
  float: left;
}

.nav-content {
  list-style-type: none;
}

.menu-section {
  width: 50%;
  float: right;
  margin-top: 34px;
}

.menu-item {
  float: left;
  display: block;
  margin-right: 70px;
}

/* nav menu */

.nav-content li a {
  text-decoration: none;
  color: #fff;
  font-size: 20px;
}

.nav-content li a:hover {
  color: #00B9F7;
}

/* header title */

.header-title {
  color: #fff;
  text-align: center;
  margin: auto;
  width: 30%;
  padding: 10px;
  margin-top: 10%;
}

/* header video */

.header-video {
  margin-left: 30%;
  width: fit-content;
}

Home

Blog

About

Contact

Login

Sign up

SHARE YOUR HOLIDDAY DREAM

Can anyone help me, please? your answer is my happiness, thank you so much


来源: stackexchange

问:
Laravel policies: How to make a "on behalf of" behaivour
This is maybe a question on how Laravel works internally.

I'm writting an app. Only a logged user can create certain kind of records, that's easy, you just add $this->middleware('auth') to the controller, and that's it.

Now I want something more complex, the users with the role admin can create/edit that kind of records on behalf of some user. Imagine something like StackOverflow where a user can edit the question another user made, but for creation. That's it, an admin can create a post on behalf of the user():

So I have my create() in my PronController, it is something like:

```<code>function create($sid, $uid=NULL) {
    // $sid is section id, where the post is going to be created... don't mind...

    // if $uid (user id) is null, it will take the user from Auth::user()->id
    $user = empty($uid) ? Auth::user() : User::findOrFail($uid);

    // I want that only "admin" can use this $uid parameter, so I plan to use
    // a Policy:
    $this->authorize('create', $user);
}
</code>```

The policy in PronPolicy is quite simple:

```<code>function create(User $authUser, User $user) {
    return ($authUser->id === $user->id) || $authUser->isAdmin;
}
</code>```

Now, I thought this should work, but it doesn't. It never reaches this edit() (I placed Log's)

So what I did is to change the $this->authorize() line to:

```<code>$this->authorize('createpron', $user);
</code>```

And change the UserPolicy() (The UserPolicy!!!) to:

```<code>function createpron(User $authUser, User $user) {
    return ($authUser->id === $user->id) || $authUser->isAdmin;
}
</code>```

Now this works as I wanted. But I don't know why. Looks like Laravel searches for the object type in the parameter and then it activates the policy for that parameter, is it correct?

I don't know, although my code is working, it seems to me a bit dirty since the create "Pron" should be a policy of Pron, not user. Am I doing something conceptually wrong? what would be the right way to implement this?

答:
Looks like Laravel searches for the object type in the parameter and then it activates the policy for that parameter, is it correct?

Correct! The docs mention this:

Policies are classes that organize authorization logic around a particular model or resource. For example, if your application is a blog, you may have a Post model and a corresponding PostPolicy to authorize user actions such as creating or updating posts.

By passing in the $user argument to $this->authorize(), you're asking if the current user can take an action against that particular record.

What you're doing isn't conceptually wrong (it is working), it just mixes a couple different authorizations together and as such feels kind of disorganized or unclear. Here's how I'd improve things:

Start by separating authorizations. You really have two separate but related permission checks happening:

Can the current User act on behalf of another User?

Can the end user (current or on-behalf-of) create a Pron?

#1 can be enacted as either a Gate or Policy, depending on if you want to pass in the on-behalf-of User for part of the check. That would be useful if, say, you can only act on behalf of Users within your own organization. The UserPolicy would be a good place for it.

#2 would be implemented as if you didn't have any on-behalf functionality. So maybe it's just return true because anyone can create them, or whatever your app's needs require for the ability to create a Pron.

Then, enact them separately.

function create($sid, $uid = null)
{
    $user = Auth::user();

    if (!empty($uid)) {
        $user = User::findOrFail($uid);

        $this->authorize('on-behalf-of', $user);
    }

    $this->authorizeForUser($user, 'create', new Pron());

    // Continue your create logic...
}
```

Some benefits this provides:

Controller reads a little more explicitly for what authorization actions are happening, and how they're related

Gates and policies don't have to rely as much on mixing record types, and can strictly compare a permission to the specified user without arguments

Tighter control on permissions (e.g. if User X can't create posts, User Y acting on their behalf still can't create posts)

Possible down sides:

Opposite of tighter controls above: if you want to combine permission checks in order to modify them, this doesn't exactly solve that. For example, User X cannot create posts, but if an Admin is acting on their behalf then they CAN, the above doesn't exactly solve that

ContentLicense: CC BY-SA 4.0

Body:
This is maybe a question on how Laravel works internally.

I'm writting an app. Only a logged user can create certain kind of records, that's easy, you just add $this->middleware('auth') to the controller, and that's it.

Now I want something more complex, the users with the role admin can create/edit that kind of records on behalf of some user. Imagine something like StackOverflow where a user can edit the question another user made, but for creation. That's it, an admin can create a post on behalf of the user():

So I have my create() in my PronController, it is something like:

function create($sid, $uid=NULL) {
    // $sid is section id, where the post is going to be created... don't mind...

    // if $uid (user id) is null, it will take the user from Auth::user()->id
    $user = empty($uid) ? Auth::user() : User::findOrFail($uid);

    // I want that only "admin" can use this $uid parameter, so I plan to use
    // a Policy:
    $this->authorize('create', $user);
}

The policy in PronPolicy is quite simple:

function create(User $authUser, User $user) {
    return ($authUser->id === $user->id) || $authUser->isAdmin;
}

Now, I thought this should work, but it doesn't. It never reaches this edit() (I placed Log's)

So what I did is to change the $this->authorize() line to:

$this->authorize('createpron', $user);

And change the UserPolicy() (The UserPolicy!!!) to:

function createpron(User $authUser, User $user) {
    return ($authUser->id === $user->id) || $authUser->isAdmin;
}

Now this works as I wanted. But I don't know why. Looks like Laravel searches for the object type in the parameter and then it activates the policy for that parameter, is it correct?

I don't know, although my code is working, it seems to me a bit dirty since the create "Pron" should be a policy of Pron, not user. Am I doing something conceptually wrong? what would be the right way to implement this?

Body:
Looks like Laravel searches for the object type in the parameter and then it activates the policy for that parameter, is it correct?

Correct! The docs mention this:

Policies are classes that organize authorization logic around a particular model or resource. For example, if your application is a blog, you may have a Post model and a corresponding PostPolicy to authorize user actions such as creating or updating posts.

By passing in the $user argument to $this->authorize(), you're asking if the current user can take an action against that particular record.

What you're doing isn't conceptually wrong (it is working), it just mixes a couple different authorizations together and as such feels kind of disorganized or unclear. Here's how I'd improve things:

Start by separating authorizations. You really have two separate but related permission checks happening:

Can the current User act on behalf of another User?

Can the end user (current or on-behalf-of) create a Pron?

#1 can be enacted as either a Gate or Policy, depending on if you want to pass in the on-behalf-of User for part of the check. That would be useful if, say, you can only act on behalf of Users within your own organization. The UserPolicy would be a good place for it.

#2 would be implemented as if you didn't have any on-behalf functionality. So maybe it's just return true because anyone can create them, or whatever your app's needs require for the ability to create a Pron.

Then, enact them separately.

function create($sid, $uid = null)
{
    $user = Auth::user();

    if (!empty($uid)) {
        $user = User::findOrFail($uid);

        $this->authorize('on-behalf-of', $user);
    }

    $this->authorizeForUser($user, 'create', new Pron());

    // Continue your create logic...
}

Some benefits this provides:

Controller reads a little more explicitly for what authorization actions are happening, and how they're related

Gates and policies don't have to rely as much on mixing record types, and can strictly compare a permission to the specified user without arguments

Tighter control on permissions (e.g. if User X can't create posts, User Y acting on their behalf still can't create posts)

Possible down sides:

Opposite of tighter controls above: if you want to combine permission checks in order to modify them, this doesn't exactly solve that. For example, User X cannot create posts, but if an Admin is acting on their behalf then they CAN, the above doesn't exactly solve that


问:
Python zip function with iterator vs iterable
I am having trouble understanding working of the zip() function in python when an iterator is passed in instead of iterable.

Have a look at these two print statements:

```<code>string = "ABCDEFGHI"

print(list(zip(*[iter(string)] * 3)))
# Output: [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'H', 'I')]

print(list(zip(*[string] * 3)))
# Output: [('A', 'A', 'A'), ('B', 'B', 'B'), ('C', 'C', 'C'), ('D', 'D', 'D'), ('E', 'E', 'E'), ('F', 'F', 'F'), ('G', 'G', 'G'), ('H', 'H', 'H'), ('I', 'I', 'I')]
</code>```

Can someone explain me the working of zip() in both the cases?

答:
The difference is that for [iter(string)] * 3, zip creates aliases of a single iterator. For [string] * 3, zip creates unique iterators per argument. The shorter output without duplicates is zip exhausting the single aliased iterator.

See what is meaning of [iter(list)]*2 in python? for more details on how [iter(...)] * 2 works and causes potentially unexpected results.

See the canonical answer List of lists changes reflected across sublists unexpectedly if the [...] * 3 aliasing behavior is surprising.

Body:
I am having trouble understanding working of the zip() function in python when an iterator is passed in instead of iterable.

Have a look at these two print statements:

string = "ABCDEFGHI"

print(list(zip(*[iter(string)] * 3)))
# Output: [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'H', 'I')]

print(list(zip(*[string] * 3)))
# Output: [('A', 'A', 'A'), ('B', 'B', 'B'), ('C', 'C', 'C'), ('D', 'D', 'D'), ('E', 'E', 'E'), ('F', 'F', 'F'), ('G', 'G', 'G'), ('H', 'H', 'H'), ('I', 'I', 'I')]

Can someone explain me the working of zip() in both the cases?


问:
How to add a button that scrolls up and down through a multiselect list?
Similar to this question, How can I move selected option in multiselect up and down by buttons using jquery? but not moving the selection up and down. But being able to scroll up and down a list without the scrollbar for more accurate scrolling. Similar to using the up and down keys to progress through the list one at a time up or down.
How can I achieve this with an up and down button with jQuery or JavaScript?

Or are there any HTML attributes that may aid in browsing a long list more user friendly?

```<code><select id="selectLongList" multiple>
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
</select>

</code>```

Two buttons, maybe to the side

```<code><button id="up">Up</button>
<button id="down">Down</button>
</code>```

Update
After further looking I came across this solution, Choose option from select list using next/previous button with jquery. This kind of replicates what I am trying to accomplish. But I'm not wanting to move the selection. I would just like to move through the list of options.

Borrowing from one of the answers. https://stackoverflow.com/a/9112759/2946802
>

```<code>$("#next, #prev").click(function() {
   $("#mycars :selected")[this.id]().prop("selected", true);
});
</code>```

Sort of like this in how it changes to the next value, but working with a multiple select and not changing the actual selection. Just moving on to the next value.

$("#prev").click(function() {
   $('#selectLongList option:selected').prev().prop('selected', true);

 });

$("#next").click(function() {
$('#selectLongList option:selected').next().prop('selected', true);

 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button type="button" id="prev">Previous</button>
   <select id="selectLongList">
       <option value="1">1</option>
       <option value="2">2</option>
       <option value="3">3</option>
       <option value="4">4</option>
       <option value="4">4</option>
       <option value="4">4</option>
   </select>
<button type="button" id="next">Next</button></code>```

答:
Check out Select2 for jQuery, it will most likely solve your problem.
You won't need to move any options. Select2 will just display every selected item inside the select itself.

Select2 Docs Getting Started

Body:
Similar to this question, How can I move selected option in multiselect up and down by buttons using jquery? but not moving the selection up and down. But being able to scroll up and down a list without the scrollbar for more accurate scrolling. Similar to using the up and down keys to progress through the list one at a time up or down.
How can I achieve this with an up and down button with jQuery or JavaScript?

Or are there any HTML attributes that may aid in browsing a long list more user friendly?

<select id="selectLongList" multiple>
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
</select>

Two buttons, maybe to the side

<button id="up">Up</button>
<button id="down">Down</button>

Update
After further looking I came across this solution, Choose option from select list using next/previous button with jquery. This kind of replicates what I am trying to accomplish. But I'm not wanting to move the selection. I would just like to move through the list of options.

Borrowing from one of the answers. https://stackoverflow.com/a/9112759/2946802
>

$("#next, #prev").click(function() {
   $("#mycars :selected")[this.id]().prop("selected", true);
});

Sort of like this in how it changes to the next value, but working with a multiple select and not changing the actual selection. Just moving on to the next value.

$("#prev").click(function() {
   $('#selectLongList option:selected').prev().prop('selected', true);

 });

$("#next").click(function() {
$('#selectLongList option:selected').next().prop('selected', true);

 });

<button type="button" id="prev">Previous</button>
   <select id="selectLongList">
       <option value="1">1</option>
       <option value="2">2</option>
       <option value="3">3</option>
       <option value="4">4</option>
       <option value="4">4</option>
       <option value="4">4</option>
   </select>
<button type="button" id="next">Next</button>


问:
Infinispan-specific configuration when used as JCache (JSR-107) provider?
Our Thorntail (2.4.0.Final) webapp is using Infinispan as a JCache (JSR-107) provider. We would like to modify Infinispan specific attributes (such as default acquire timeout) in addition to JCache's attributes (such as store-by-value option).

Our current solution isn't working. Here's what we've tried so far.

Defined infinispan.xml:

```<code><infinispan
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="urn:infinispan:config:5.2 http://www.infinispan.org/schemas/infinispan-config-9.4.xsd"
        xmlns="urn:infinispan:config:9.4">

    <cache-container>
        <local-cache  name="foo">
            <locking acquire-timeout="15000"/>
        </local-cache>
    </cache-container>
</infinispan>
</code>```

The config above is then used by the following class:

```<code>public class CacheManagerProducer {

    @Produces
    @ApplicationScoped
    public CacheManager defaultEmbeddedCacheManager() {
        return Caching.getCachingProvider().getCacheManager(URI.create("infinispan.xml"), this.getClass().getClassLoader());
    }
}
</code>```

FooCache interface is defined as:

```<code>@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)

@Documented
public @interface FooCache {
}
</code>```

Here's how we're configuring cache using JCache API:

```<code>@Produces
@FooCache
public Cache<Long, DiscountOrAddition> createDiscoCache(InjectionPoint injectionPoint) {
    MutableConfiguration<Long, DiscountOrAddition> config = new MutableConfiguration<>();
    config.setStoreByValue(true);
    config.setStatisticsEnabled(false);
    config.setManagementEnabled(false);
    return mgr.createCache("foo", config);
}
</code>```

This is where we fail as foo cache already exists (created as per XML config). Is there a way we could configure existing cache? Or any other alternative way allowing us to stay cache-provider agnostic? Thank you for your answers.

答:
We encountered similar issue, except defining cache configuration instead cache in the infinispan.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<infinispan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="urn:infinispan:config:8.2 https://infinispan.org/schemas/infinispan-config-8.2.xsd"
    xmlns="urn:infinispan:config:8.2">

    <cache-container>
        <local-cache-configuration name="foo">
            <locking acquire-timeout="15000"/>
        </local-cache-configuration>
    </cache-container>
</infinispan>
</code>```

Expecting the above configuration will be used as a template and merged with JCache configuration to create the cache foo.
This is working correctly in Infinispan 8.2 stream, but upgrade to 9.4 stream it is not working now. We think this is unintended and already submit a bug report (ISPN-11918)

Body:
Our Thorntail (2.4.0.Final) webapp is using Infinispan as a JCache (JSR-107) provider. We would like to modify Infinispan specific attributes (such as default acquire timeout) in addition to JCache's attributes (such as store-by-value option).

Our current solution isn't working. Here's what we've tried so far.

Defined infinispan.xml:

<infinispan
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="urn:infinispan:config:5.2 http://www.infinispan.org/schemas/infinispan-config-9.4.xsd"
        xmlns="urn:infinispan:config:9.4">

    <cache-container>
        <local-cache  name="foo">
            <locking acquire-timeout="15000"/>
        </local-cache>
    </cache-container>
</infinispan>

The config above is then used by the following class:

public class CacheManagerProducer {

    @Produces
    @ApplicationScoped
    public CacheManager defaultEmbeddedCacheManager() {
        return Caching.getCachingProvider().getCacheManager(URI.create("infinispan.xml"), this.getClass().getClassLoader());
    }
}

FooCache interface is defined as:

@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)

@Documented
public @interface FooCache {
}

Here's how we're configuring cache using JCache API:

@Produces
@FooCache
public Cache<Long, DiscountOrAddition> createDiscoCache(InjectionPoint injectionPoint) {
    MutableConfiguration<Long, DiscountOrAddition> config = new MutableConfiguration<>();
    config.setStoreByValue(true);
    config.setStatisticsEnabled(false);
    config.setManagementEnabled(false);
    return mgr.createCache("foo", config);
}

This is where we fail as foo cache already exists (created as per XML config). Is there a way we could configure existing cache? Or any other alternative way allowing us to stay cache-provider agnostic? Thank you for your answers.

Body:
We encountered similar issue, except defining cache configuration instead cache in the infinispan.xml:

<?xml version="1.0" encoding="UTF-8"?>
<infinispan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="urn:infinispan:config:8.2 https://infinispan.org/schemas/infinispan-config-8.2.xsd"
    xmlns="urn:infinispan:config:8.2">

    <cache-container>
        <local-cache-configuration name="foo">
            <locking acquire-timeout="15000"/>
        </local-cache-configuration>
    </cache-container>
</infinispan>

Expecting the above configuration will be used as a template and merged with JCache configuration to create the cache foo.
This is working correctly in Infinispan 8.2 stream, but upgrade to 9.4 stream it is not working now. We think this is unintended and already submit a bug report (ISPN-11918)


问:
Why does Combine require macOS 10.15 and above?
I recently discovered that usage of the new Combine SDK in a macOS necessitates a minimum deployment target of 10.15.

Admittedly, I am new to macOS development. It is surprising to me that a library of this nature would have strict dependencies on the latest OS version.

My mental model (which is apparently missing key information) tells me either (a) the SDK uses new syscalls introduced in 10.15 or (b) macOS binaries are dynamically-linked and not statically-linked as I had assumed.

Is it some other (c)?

答:
macOS apps are dynamically linked against system frameworks.

It is also possible that Combine uses other new 10.15 features under the hood, although there is nothing in its public API that seems likely to require new 10.15 features.

Also, historically, Apple has not shipped significant new frameworks as standalone libraries for back-deployment. The only such cases I'm aware of are the “arclite” library which enabled back-deployment of some (not all) ARC features when ARC was introduced, and the Swift runtime libraries for Mojave releases earlier than 10.14.3 and again didn't support all the new Swift features. Both of those were cases of supporting low-level language runtime features, not significant app-building APIs.


问:
What's the best way to implement a counter that counts up when a different counter hits certain milestones
i'm trying to make a clicker game in unity, where for every 100 "views" a dollar is generated, i'm not sure as to how to tackle this problem. i have tried using an update function that adds 1 to the dollar counter for every multiple of 100, but that misses out counting up if the number lands on say 101, i'm lost on what else to try as i'm a beginner really in this kind of code and i'm not really sure where to look for how to do this any other way.</p>

答:
One potential way to set this up would be to set a separate Limbo_Views variable alongside implied Total_Views and Total_Earnings variables to keep track of how far towards the next 100 view milestone the counter is or has surpassed

For example...

```<code>public class Video{

    public int Total_Views;
    public int Total_Earnings;
    private int Limbo_Views;

    public Video() {
        Total_Views = 0;
        Total_Earnings = 0;
        Limbo_Views = 0;
    }

    public void addViews(int views) {
        Total_Views += views;           // <-- add views to total
        Limbo_Views += views;           // <- add views to limbo view count
        if(Limbo_Views >= 100) {        // <-- if there 100+ views in limbo...
            int dollarsToAdd = Limbo_Views / 100;  // <-- determine how many dollars should be paid out
            Total_Earnings += dollarsToAdd; // <-- add that amount to earnings
            Limbo_Views -= (dollarsToAdd * 100); // <-- decrement limbo views to reflect views that have been accounted for
        }
    }
}
</code>```

This should be able to handle any positive number you throw at it in terms of adding views and accounting for their earnings.

Let me know if you have any additional questions!

Body:
One potential way to set this up would be to set a separate Limbo_Views variable alongside implied Total_Views and Total_Earnings variables to keep track of how far towards the next 100 view milestone the counter is or has surpassed

For example...

public class Video{

    public int Total_Views;
    public int Total_Earnings;
    private int Limbo_Views;

    public Video() {
        Total_Views = 0;
        Total_Earnings = 0;
        Limbo_Views = 0;
    }

    public void addViews(int views) {
        Total_Views += views;           // <-- add views to total
        Limbo_Views += views;           // <- add views to limbo view count
        if(Limbo_Views >= 100) {        // <-- if there 100+ views in limbo...
            int dollarsToAdd = Limbo_Views / 100;  // <-- determine how many dollars should be paid out
            Total_Earnings += dollarsToAdd; // <-- add that amount to earnings
            Limbo_Views -= (dollarsToAdd * 100); // <-- decrement limbo views to reflect views that have been accounted for
        }
    }
}

This should be able to handle any positive number you throw at it in terms of adding views and accounting for their earnings.

Let me know if you have any additional questions!


问:
How to handle multiple dispatch results from react using redux-thunk and try-catch?
I am using redux-thunk to make action calls and reducers to return back states. My actions are essentially axios API requests to the back end. For one particular action, I need a set events dispatched in the exact order as they are shown in the code:

Check if tokenvalue passed by the user is valid (which has its own axios api request to the tokencollection). If 1. fails, jump to the catch block.

If token is indeed valid, register the user using axios post. if 2. fails, jump to catch block

If user was registered successfully, set the token to the user (thus only one unique token per user). If 3. fails, jump to catch block.

In order to implement them sequentially in the order above, I put them in try-catch blocks. Turns out my understanding of how dispatch works is wrong - if a dispatch fails with an error, it still executes subsequent dispatches. Any suggestions on how I can solve this? :

```<code>export const register = ({name,email,password,tokenval}) => async(dispatch) =>{
try{
    await dispatch(checkTokenValidity(tokenval)); // if this fails, jump to catch block
    const res = await axios.post("/api/users", body, config); //if this fails jump to catch
    await dispatch(setUserToToken({ tokenval, userID: res.data.userID })); //if this fails jump to catch
    dispatch({
      type: REGISTER_SUCCESS,
      payload: res.data,
    });
}catch(err){
  dispatch({
      type: REGISTER_FAIL,
    });
}
};
</code>```

答:
make sure that the checkTokenValidity throws an error upon fail. With this, it automatically goes to catch block

no need to use dispatch and await for token validity

store api results in variables and make required checks and dispatch the actions accordingly.

Your refactored code

export const register = ({ name, email, password, tokenval }) => async (
  dispatch
) => {
  try {
    const isValidToken = await checkTokenValidity(tokenval); // no need of dispatch - just make sure that the checkTokenValidity throws an error upon fail
    if(!isValidToken ){
        throw new Error('server error - invalid token')
    }
    const usersResult = await axios.post("/api/users", body, config); //if this fails jump to catch
    if(!usersResult ){
        throw new Error('server error - usersResult')
    }
    const setUserToTokenResults = await dispatch(setUserToToken({ tokenval, userID: res.data.userID })); //if this fails jump to catch
    if(!setUserToTokenResults ){
        throw new Error('server error - setUserToTokenResults')
    }
    dispatch({
      type: REGISTER_SUCCESS,
      payload: res.data,
    });
  } catch (err) {
    dispatch({
      type: REGISTER_FAIL,
      payload: {err} //<---- provide some error message to the reducer
    });
  }
};
```

Body:
I am using redux-thunk to make action calls and reducers to return back states. My actions are essentially axios API requests to the back end. For one particular action, I need a set events dispatched in the exact order as they are shown in the code:

Check if tokenvalue passed by the user is valid (which has its own axios api request to the tokencollection). If 1. fails, jump to the catch block.

If token is indeed valid, register the user using axios post. if 2. fails, jump to catch block

If user was registered successfully, set the token to the user (thus only one unique token per user). If 3. fails, jump to catch block.

In order to implement them sequentially in the order above, I put them in try-catch blocks. Turns out my understanding of how dispatch works is wrong - if a dispatch fails with an error, it still executes subsequent dispatches. Any suggestions on how I can solve this? :

export const register = ({name,email,password,tokenval}) => async(dispatch) =>{
try{
    await dispatch(checkTokenValidity(tokenval)); // if this fails, jump to catch block
    const res = await axios.post("/api/users", body, config); //if this fails jump to catch
    await dispatch(setUserToToken({ tokenval, userID: res.data.userID })); //if this fails jump to catch
    dispatch({
      type: REGISTER_SUCCESS,
      payload: res.data,
    });
}catch(err){
  dispatch({
      type: REGISTER_FAIL,
    });
}
};


问:
_TABLE_SUFFIX BETWEEN syntax is not selecting any tables
I'm looking at the public GitHub events dataset githubarchive.day.YYYYMMDD to pull public events that belong to me.

For this I use a simple query like:

SELECT id, actor.login, type
FROM `githubarchive.day.2*`
WHERE
  _TABLE_SUFFIX BETWEEN '20200520' AND '20200528'
AND actor.login='ahmetb'
```

<p>This <code>BETWEEN</code> clause doesn't seem to be matching any tables according to this message</p>

<blockquote>
  <p>Query complete (0.4 sec elapsed, 0 B processed)</p>
</blockquote>

<p>If I use a simpler syntax like this it works:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT id, actor.login, type
FROM `githubarchive.day.202005*`
WHERE actor.login='ahmetb'
</code>```

Query complete (2.2 sec elapsed, 2.4 GB processed)

However using the wildcard syntax directly in FROM is not an option for me as I determine the table suffix dynamically through a query parameter.

答:
Below is correct version

```<code>SELECT id, actor.login, type
FROM `githubarchive.day.2*`
WHERE
  _TABLE_SUFFIX BETWEEN '0200520' AND '0200528'
AND actor.login='ahmetb'
</code>```

Note: you needed to remove first 2 in dates in below line

```<code>_TABLE_SUFFIX BETWEEN '0200520' AND '0200528'
</code>```

Or you might wanted below one

```<code>SELECT id, actor.login, type
FROM `githubarchive.day.*`
WHERE
  _TABLE_SUFFIX BETWEEN '20200520' AND '20200528'
AND actor.login='ahmetb'
</code>```

which makes more sense to me

Body:
I'm looking at the public GitHub events dataset githubarchive.day.YYYYMMDD to pull public events that belong to me.

For this I use a simple query like:

SELECT id, actor.login, type
FROM `githubarchive.day.2*`
WHERE
  _TABLE_SUFFIX BETWEEN '20200520' AND '20200528'
AND actor.login='ahmetb'

This BETWEEN clause doesn't seem to be matching any tables according to this message

Query complete (0.4 sec elapsed, 0 B processed)

If I use a simpler syntax like this it works:

SELECT id, actor.login, type
FROM `githubarchive.day.202005*`
WHERE actor.login='ahmetb'

Query complete (2.2 sec elapsed, 2.4 GB processed)

However using the wildcard syntax directly in FROM is not an option for me as I determine the table suffix dynamically through a query parameter.

Body:
Below is correct version

SELECT id, actor.login, type
FROM `githubarchive.day.2*`
WHERE
  _TABLE_SUFFIX BETWEEN '0200520' AND '0200528'
AND actor.login='ahmetb'

Note: you needed to remove first 2 in dates in below line

_TABLE_SUFFIX BETWEEN '0200520' AND '0200528'

Or you might wanted below one

SELECT id, actor.login, type
FROM `githubarchive.day.*`
WHERE
  _TABLE_SUFFIX BETWEEN '20200520' AND '20200528'
AND actor.login='ahmetb'

which makes more sense to me


问:
Ggplot2: scales="free_y" but keeping x axis line
Sorry if this is too basic, but if anyone can guide me to a solution, it would be great.

I have a plot with 5 separate charts and I'm using scales="free_y". Is there a way to keep just the horizontal line for x axis label for each of the 4 charts above?

```<code>df <- data_frame(ReqID = 100, ID_Seq = 1:5, Created = dmy("01/01/2018","10/02/2018","18/03/2018", "22/04/2018", "18/05/2018"), fruits = c("Apple","Banana", "Blueberry", "Avocado", "Grapes"))

df <- df %>%
  group_by(ReqID) %>%
  complete(Created = seq.Date(min(Created),max(Created), by = "day")) %>%
  fill(ReqID,ID_Seq,fruits)

df$counts <- seq.int(nrow(df))

fruits <- ggplot(data = df) +
  geom_bar(aes(x=Created,y=counts,fill=fruits),
           stat = "identity",
           width = 1) +
  scale_x_date(date_breaks = "2 days", date_labels = "%b-%d",
               limits = c(min(df$Created),max(df$Created)+1),
               expand = c(0,0),
               name = "Date") +
  scale_y_continuous(limits = c(0,max(df$counts)*1.01),
                     expand = c(0,0),
                     name = "Fruits") +
  facet_wrap(fruits ~ ., scales = "free_y", nrow = 5) +
  theme(axis.text.x = element_text(angle = 90),
        legend.position = "bottom",  legend.justification = "center", axis.line = element_line(colour = "black"),

        strip.background = element_blank(),
        strip.text = element_blank()) +
  scale_fill_manual(name = element_blank(),
                    values = c("#BFBFBF","#99CCFF",
                               "#BFBFBF","#CCE5FF",
                               "#CCCFFF"))

fruits
</code>```

答:
Try this

I added a geom_segment, as per this answer here:
Add x and y axis to all facet_wrap

Your desired plots with x axis lines (code output)

(I also swapped df with df_ )

```<code>df_ <- data.frame(ReqID = 100, ID_Seq = 1:5, Created = dmy("01/01/2018","10/02/2018","18/03/2018", "22/04/2018", "18/05/2018"), fruits = c("Apple","Banana", "Blueberry", "Avocado", "Grapes"))

df_ <- df_ %>%
    group_by(ReqID) %>%
    complete(Created = seq.Date(min(Created),max(Created), by = "day")) %>%
    ungroup() %>%
    fill(ReqID,ID_Seq,fruits)

df_$counts <- seq.int(nrow(df_))

fruits <- ggplot(data = df_) +
    geom_bar(aes(x=Created,y=counts,fill=fruits),
             stat = "identity",
             width = 1) +
    scale_x_date(date_breaks = "2 days", date_labels = "%b-%d",
                 limits = c(min(df_$Created),max(df_$Created)+1),
                 expand = c(0,0),
                 name = "Date") +
    scale_y_continuous(limits = c(0,max(df_$counts)*1.01),
                       expand = c(0,0),
                       name = "Fruits")  +
    theme(axis.line = element_line()) +
    facet_wrap(fruits ~ ., scales = "free_y", nrow = 5) +
    theme(axis.text.x = element_text(angle = 90),
          legend.position = "bottom",  legend.justification = "center", axis.line = element_line(colour = "black"),

          strip.background = element_blank(),
          strip.text = element_blank()) +
    scale_fill_manual(name = element_blank(),
                      values = c("#BFBFBF","#99CCFF",
                                 "#BFBFBF","#CCE5FF",
                                 "#CCCFFF"))  +
    annotate("segment", x=min(df_$Created), xend=max(df_$Created), y=-Inf, yend=-Inf)

fruits
</code>```

Body:
Sorry if this is too basic, but if anyone can guide me to a solution, it would be great.

I have a plot with 5 separate charts and I'm using scales="free_y". Is there a way to keep just the horizontal line for x axis label for each of the 4 charts above?

df <- data_frame(ReqID = 100, ID_Seq = 1:5, Created = dmy("01/01/2018","10/02/2018","18/03/2018", "22/04/2018", "18/05/2018"), fruits = c("Apple","Banana", "Blueberry", "Avocado", "Grapes"))

df <- df %>%
  group_by(ReqID) %>%
  complete(Created = seq.Date(min(Created),max(Created), by = "day")) %>%
  fill(ReqID,ID_Seq,fruits)

df$counts <- seq.int(nrow(df))

fruits <- ggplot(data = df) +
  geom_bar(aes(x=Created,y=counts,fill=fruits),
           stat = "identity",
           width = 1) +
  scale_x_date(date_breaks = "2 days", date_labels = "%b-%d",
               limits = c(min(df$Created),max(df$Created)+1),
               expand = c(0,0),
               name = "Date") +
  scale_y_continuous(limits = c(0,max(df$counts)*1.01),
                     expand = c(0,0),
                     name = "Fruits") +
  facet_wrap(fruits ~ ., scales = "free_y", nrow = 5) +
  theme(axis.text.x = element_text(angle = 90),
        legend.position = "bottom",  legend.justification = "center", axis.line = element_line(colour = "black"),

        strip.background = element_blank(),
        strip.text = element_blank()) +
  scale_fill_manual(name = element_blank(),
                    values = c("#BFBFBF","#99CCFF",
                               "#BFBFBF","#CCE5FF",
                               "#CCCFFF"))

fruits

Body:
Try this

I added a geom_segment, as per this answer here:
Add x and y axis to all facet_wrap

Your desired plots with x axis lines (code output)

(I also swapped df with df_ )

df_ <- data.frame(ReqID = 100, ID_Seq = 1:5, Created = dmy("01/01/2018","10/02/2018","18/03/2018", "22/04/2018", "18/05/2018"), fruits = c("Apple","Banana", "Blueberry", "Avocado", "Grapes"))

df_ <- df_ %>%
    group_by(ReqID) %>%
    complete(Created = seq.Date(min(Created),max(Created), by = "day")) %>%
    ungroup() %>%
    fill(ReqID,ID_Seq,fruits)

df_$counts <- seq.int(nrow(df_))

fruits <- ggplot(data = df_) +
    geom_bar(aes(x=Created,y=counts,fill=fruits),
             stat = "identity",
             width = 1) +
    scale_x_date(date_breaks = "2 days", date_labels = "%b-%d",
                 limits = c(min(df_$Created),max(df_$Created)+1),
                 expand = c(0,0),
                 name = "Date") +
    scale_y_continuous(limits = c(0,max(df_$counts)*1.01),
                       expand = c(0,0),
                       name = "Fruits")  +
    theme(axis.line = element_line()) +
    facet_wrap(fruits ~ ., scales = "free_y", nrow = 5) +
    theme(axis.text.x = element_text(angle = 90),
          legend.position = "bottom",  legend.justification = "center", axis.line = element_line(colour = "black"),

          strip.background = element_blank(),
          strip.text = element_blank()) +
    scale_fill_manual(name = element_blank(),
                      values = c("#BFBFBF","#99CCFF",
                                 "#BFBFBF","#CCE5FF",
                                 "#CCCFFF"))  +
    annotate("segment", x=min(df_$Created), xend=max(df_$Created), y=-Inf, yend=-Inf)

fruits


答:
To understand this properly, first make sure you understand the relevant fundamentals: the Python iterator protocol and object identity versus equality.

```<code>print(list(zip(*[string] * 3)))
</code>```

We compute the list [string] * 3, and pass each element from that list to zip, so it's the same as if we had written zip(string, string, string). Python implicitly creates a separate iterator for each of the arguments (even though it's the same string object in each case - not copies!), and each one iterates over the same string. The first time through, each iterator finds the 'A', and so on.

```<code>print(list(zip(*[iter(string)] * 3)))
</code>```

Now we have made a single iterator for the string, and passed it to zip in three argument positions. Python's iteration logic attempts to "create an iterator" for that iterator in each case; but the iterator of an iterator is itself (not a copy of itself!). So once the iteration begins, zip will be using the same iterator object three times to create each of its outputs. And each time it grabs the next element from the iterator, it will be affected by the previous attempts. So the first time through, zip requests three elements from that same iterator, and gets 'A', 'B' and 'C'.

Title: Python zip function with iterator vs iterable

Body:
To understand this properly, first make sure you understand the relevant fundamentals: the Python iterator protocol and object identity versus equality.

print(list(zip(*[string] * 3)))

We compute the list [string] * 3, and pass each element from that list to zip, so it's the same as if we had written zip(string, string, string). Python implicitly creates a separate iterator for each of the arguments (even though it's the same string object in each case - not copies!), and each one iterates over the same string. The first time through, each iterator finds the 'A', and so on.

print(list(zip(*[iter(string)] * 3)))

Now we have made a single iterator for the string, and passed it to zip in three argument positions. Python's iteration logic attempts to "create an iterator" for that iterator in each case; but the iterator of an iterator is itself (not a copy of itself!). So once the iteration begins, zip will be using the same iterator object three times to create each of its outputs. And each time it grabs the next element from the iterator, it will be affected by the previous attempts. So the first time through, zip requests three elements from that same iterator, and gets 'A', 'B' and 'C'.


问:
php.ini Error Reporting problem
I get this error: Warning: date() [function.date]: It is not safe to rely on the system's timezone settings.

In php.ini I have error reporting set as error_reporting = E_ALL & ~E_NOTICE.

Any idea how I can get rid of those warnings?

EDIT:

I want to fix the Error Reporting as there's other kinds of Warnings showing up.

EDIT 2:

All warnings were date.timezone related.

Thank you.

答:
Look for:

```<code>[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
; date.timezone = America/Los_Angeles
</code>```

and Uncomment this line:

```<code>date.timezone = America/Los_Angeles
</code>```

And choose your time zone...

ContentLicense: CC BY-SA 3.0

Title: php.ini Error Reporting problem

Body:
Look for:

[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
; date.timezone = America/Los_Angeles

and Uncomment this line:

date.timezone = America/Los_Angeles

And choose your time zone...


问:
Azure Functions secured with Azure AD - Getting HTTP 401 when calling from native app
My goal is to secure my Azure Functions with Azure AD and call them from a WPF application.

I have an Azure Function with the following definition :

```<code>public IActionResult Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
        HttpRequest req,
        ILogger log,
        ExecutionContext context,
        ClaimsPrincipal claimsPrincipal)
</code>```

I registered an Azure AD App and configured the settings for Native App Authentication :

I configured my app in the "Expose an API" bladd

I also added an API Permissions

I associated my app in my Azure Functions App in the Authentication / Authorization blade.

I am getting a token from Azure AD like this in a WPF app (using the Microsoft.Identity.Client library)

```<code>            string applicationID = "***"; // My AppID Guid
            PublicClientApp = PublicClientApplicationBuilder.Create(applicationID)
                .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
                .Build();

            var listScopes = new List<string>
            {
                //"user.read" - Removed based on @tony-yu recommendation
                $"api://{applicationID}/MyScope"
            };

            var authResult = await PublicClientApp.AcquireTokenInteractive(listScopes)
                                      .ExecuteAsync();

            var myToken = authResult.AccessToken;
</code>```

I can authenticate without any problem and I am successfully getting a token but whenever I call my function and I provide my token in the Authorization header (Authorization = Bearer ****), I get :

401 - You do not have permission to view this directory or page.

Here's how I call it (Postman) :

Here is the WWW-Authenticate header content when the call returns

When I check the token I got, it seems legit

Any idea what I am doing wrong?

答:
The scope is not correct. As you want to access your function which is protected by ad, you need to use

```<code>var listScopes = new List<string>
            {
                "{applicationID}/.default"
            };
</code>```

instead.

user.read is the permission for Microsoft Graph API.

Body:
My goal is to secure my Azure Functions with Azure AD and call them from a WPF application.

I have an Azure Function with the following definition :

public IActionResult Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
        HttpRequest req,
        ILogger log,
        ExecutionContext context,
        ClaimsPrincipal claimsPrincipal)

I registered an Azure AD App and configured the settings for Native App Authentication :

I configured my app in the "Expose an API" bladd

I also added an API Permissions

I associated my app in my Azure Functions App in the Authentication / Authorization blade.

I am getting a token from Azure AD like this in a WPF app (using the Microsoft.Identity.Client library)

            string applicationID = "***"; // My AppID Guid
            PublicClientApp = PublicClientApplicationBuilder.Create(applicationID)
                .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
                .Build();

            var listScopes = new List<string>
            {
                //"user.read" - Removed based on @tony-yu recommendation
                $"api://{applicationID}/MyScope"
            };

            var authResult = await PublicClientApp.AcquireTokenInteractive(listScopes)
                                      .ExecuteAsync();

            var myToken = authResult.AccessToken;

I can authenticate without any problem and I am successfully getting a token but whenever I call my function and I provide my token in the Authorization header (Authorization = Bearer ****), I get :

401 - You do not have permission to view this directory or page.

Here's how I call it (Postman) :

Here is the WWW-Authenticate header content when the call returns

When I check the token I got, it seems legit

Any idea what I am doing wrong?

Body:
The scope is not correct. As you want to access your function which is protected by ad, you need to use

var listScopes = new List<string>
            {
                "{applicationID}/.default"
            };

instead.

user.read is the permission for Microsoft Graph API.


问:
Filtering the dataFrame based on when condition
Hi i am trying to filter the dataframe based on when condition and then apply schema if it matches else leave it as it is.

```<code>val schema = ArrayType(StructType(StructField("packQty",FloatType,true):: StructField("gtin",StringType,true) :: Nil))

+--------------+---------+-----------+-----+--------------------------------------+
|orderupcnumber|enrichqty|allocoutqty|allocatedqty|gtins
|
+--------------+---------+-----------+--------------------------------------------+
|5203754   |15.0     |1.0        |5.0         |[{"packQty":120.0,"gtin":"00052000042276"}]|
|5203754   |15.0     |1.0        |2.0         |[{"packQty":120.0,"gtin":"00052000042276"}|
|5243700   |25.0     |1.0        |2.0         |na
|
+--------------+---------+-----------+------------+-------------------------------+
</code>```

i am tryin to add a column based on schema if the gtins column is not "na" if it is  i am adding 0, but it is throwing the error saying

```<code> df.withColumn("jsonData",when($"gtins"=!="na",from_json($"gtins",schema)).otherwise(0))

 Exception in thread "main" org.apache.spark.sql.AnalysisException: cannot resolve 'CASE
 WHEN contains(`gtins`, 'na') THEN 0 ELSE jsontostructs(`gtins`) END' due to data type
 mismatch: THEN and ELSE expressions should all be same type or coercible to a common type;;

 df.select($"orderupcnumber",$"enrichqty",$"allocoutqty",$"allocatedqty",explode($"jsonData").as("jsonData"))

 +--------------+---------+-----------+-----+--------------+
 |orderupcnumber|enrichqty|allocoutqty|allocatedqty|gtins|JsonData
 +--------------+---------+-----------+--------------------+
 |5203754   |15.0|1.0|5.0|[{"packQty":120.0,"gtin":"00052000042276”}]|[120.0, 00052000042276]
 |5203754   |15.0|1.0 |2.0|[{"packQty":120.0,"gtin":"00052000042276”}|[120.0,00052000042276]
 |5243700   |25.0 |1.0|2.0  |na  |null
 +--------------+---------+-----------+------------+----+

 df.select($"orderupcnumber",$"enrichqty",$"allocoutqty",$"allocatedqty",$"jsonData.packQty".as("packQty"),$"jsonData.gtin".as("gtin")
</code>```

this select is only selecting data where jsonData is not null

```<code>+---------+-----------+------------+-------+--------------+
 orderupcnumber |enrichqty|allocoutqty|allocatedqty|packQty|gtin  |
 +-----------+------------+----------------+------------+
 5203754|15.0     |1.0        |5.0         |120.0  |00052000042276|
 5203754|15.0     |1.0        |5.0         |144.0  |00052000042283|
 5243700|25.0     |1.0        |5.0         |  | |
 +-----------+------------+----------------+------------+----------
</code>```

how can i include one with null as well.

Body:
Hi i am trying to filter the dataframe based on when condition and then apply schema if it matches else leave it as it is.

val schema = ArrayType(StructType(StructField("packQty",FloatType,true):: StructField("gtin",StringType,true) :: Nil))

+--------------+---------+-----------+-----+--------------------------------------+
|orderupcnumber|enrichqty|allocoutqty|allocatedqty|gtins
|
+--------------+---------+-----------+--------------------------------------------+
|5203754   |15.0     |1.0        |5.0         |[{"packQty":120.0,"gtin":"00052000042276"}]|
|5203754   |15.0     |1.0        |2.0         |[{"packQty":120.0,"gtin":"00052000042276"}|
|5243700   |25.0     |1.0        |2.0         |na
|
+--------------+---------+-----------+------------+-------------------------------+

i am tryin to add a column based on schema if the gtins column is not "na" if it is  i am adding 0, but it is throwing the error saying

 df.withColumn("jsonData",when($"gtins"=!="na",from_json($"gtins",schema)).otherwise(0))

 Exception in thread "main" org.apache.spark.sql.AnalysisException: cannot resolve 'CASE
 WHEN contains(`gtins`, 'na') THEN 0 ELSE jsontostructs(`gtins`) END' due to data type
 mismatch: THEN and ELSE expressions should all be same type or coercible to a common type;;

 df.select($"orderupcnumber",$"enrichqty",$"allocoutqty",$"allocatedqty",explode($"jsonData").as("jsonData"))

 +--------------+---------+-----------+-----+--------------+
 |orderupcnumber|enrichqty|allocoutqty|allocatedqty|gtins|JsonData
 +--------------+---------+-----------+--------------------+
 |5203754   |15.0|1.0|5.0|[{"packQty":120.0,"gtin":"00052000042276”}]|[120.0, 00052000042276]
 |5203754   |15.0|1.0 |2.0|[{"packQty":120.0,"gtin":"00052000042276”}|[120.0,00052000042276]
 |5243700   |25.0 |1.0|2.0  |na  |null
 +--------------+---------+-----------+------------+----+

 df.select($"orderupcnumber",$"enrichqty",$"allocoutqty",$"allocatedqty",$"jsonData.packQty".as("packQty"),$"jsonData.gtin".as("gtin")

this select is only selecting data where jsonData is not null

+---------+-----------+------------+-------+--------------+
 orderupcnumber |enrichqty|allocoutqty|allocatedqty|packQty|gtin  |
 +-----------+------------+----------------+------------+
 5203754|15.0     |1.0        |5.0         |120.0  |00052000042276|
 5203754|15.0     |1.0        |5.0         |144.0  |00052000042283|
 5243700|25.0     |1.0        |5.0         |  | |
 +-----------+------------+----------------+------------+----------

how can i include one with null as well.

Body:
Exception in thread "main" org.apache.spark.sql.AnalysisException: cannot resolve 'CASE
 WHEN contains(gtins, 'na') THEN 0 ELSE jsontostructs(gtins) END' due to data type
 mismatch: THEN and ELSE expressions should all be same type or coercible to a common type;

To Fix above exception

You have to convert na value to json array type to match other values.

Please check below code.

scala> df.withColumn("gtins",when($"gtins" === "na",to_json(array($"gtins"))).otherwise($"gtins")).withColumn("jsonData",from_json($"gtins",schema)).show(false)
+-------------------------------------------+-------------------------+
|gtins                                      |jsonData                 |
+-------------------------------------------+-------------------------+
|[{"packQty":120.0,"gtin":"00052000042276"}]|[[120.0, 00052000042276]]|
|[{"packQty":120.0,"gtin":"00052000042276"}]|[[120.0, 00052000042276]]|
|["na"]                                     |null                     |
+-------------------------------------------+-------------------------+

scala> df.withColumn("gtins",when($"gtins" === "na",to_json(array($"gtins"))).otherwise($"gtins")).withColumn("jsonData",from_json($"gtins",schema)).select($"gtins",$"jsonData.packQty".as("packQty"),$"jsonData.gtin".as("gtin")).show(false)
+-------------------------------------------+-------+----------------+
|gtins                                      |packQty|gtin            |
+-------------------------------------------+-------+----------------+
|[{"packQty":120.0,"gtin":"00052000042276"}]|[120.0]|[00052000042276]|
|[{"packQty":120.0,"gtin":"00052000042276"}]|[120.0]|[00052000042276]|
|["na"]                                     |null   |null            |
+-------------------------------------------+-------+----------------+


问:
Why does JFlap fail to build a usable LL(1) parser from my calculator grammar?
I entered the following grammar in JFlap:

E → TK
K → +TK
K → λ
T → FM
M → *FM
M → λ
F → i
F → (E)
```

and tried to parse i * (i + i). I am sure the LL(1) grammar is correct and the input string should be accepted but JFlap said that the string in rejected. (See screenshot). Why?

答:
The grammar is fine.

However, you somehow entered it incorrectly. Notice that your parsing table has a λ column. That means that JFlap interpreted the λ as a character, not as an empty right-hand side, probably because you typed a real λ rather than letting JFlap fill it in automatically. You should just leave the right-hand side empty if you want an empty right-hand side. JFlap will then show that as λ but it won't treat it as a symbol.

By way of illustration, here are screenshots for the correctly entered grammar (with empty right-hand sides) and a grammar where I typed a λ instead of leaving the right-hand side empty. I stopped the second parse one step earlier than the error message, so that you can see the problem being reported: since M does not have an empty production, it blocks the parser from recognising the + sign.

Here's the correctly entered grammar:

And here's the one which I generated the same way that you did (if my guess is right). Note that it has a λ column in the transition table. You would also see it being handled differently in the FIRST and FOLLOW sets.

As a postscript, JFlap seems to handle most Unicode characters in tokens, but using a λ character as a token triggers a variety of bugs. So you shouldn't do that even if you intended the λ to be a legitimate character.

Body:
I entered the following grammar in JFlap:

E → TK
K → +TK
K → λ
T → FM
M → *FM
M → λ
F → i
F → (E)

and tried to parse i * (i + i). I am sure the LL(1) grammar is correct and the input string should be accepted but JFlap said that the string in rejected. (See screenshot). Why?


答:
Find this section in the php.ini file:

```<code>[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = Some/Timezone
</code>```

Uncomment it (remove the ;) and change it to be the correct timezone. For a list of supported timezones: http://php.net/manual/en/timezones.php

Title: php.ini Error Reporting problem

Body:
I get this error: Warning: date() [function.date]: It is not safe to rely on the system's timezone settings.

In php.ini I have error reporting set as error_reporting = E_ALL & ~E_NOTICE.

Any idea how I can get rid of those warnings?

EDIT:

I want to fix the Error Reporting as there's other kinds of Warnings showing up.

EDIT 2:

All warnings were date.timezone related.

Thank you.

Body:
Find this section in the php.ini file:

[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = Some/Timezone

Uncomment it (remove the ;) and change it to be the correct timezone. For a list of supported timezones: http://php.net/manual/en/timezones.php


问:
Android App keeps on crashing upon new Intent
So I've got this error code: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

The line: Intent callMode = new Intent(MainActivity.this, IncallActivity.class);

What I'm trying to do is to set a new activity when I receive a call. The following function is what should "switch" to that activity.

public void callMode() {
    Intent callMode = new Intent(MainActivity.this, IncallActivity.class);
    startActivity(callMode);
}
```

<p>And it is located inside of the MainActivity class, outside of the onCreate function.
When I try to put it inside of the onCreate function (without <code>public void callMode()</code> of course) it works, but that's not the goal.</p>

<p>I'm trying to activate this new activity from another class, which listens for calls.</p>

<pre class="lang-java prettyprint-override"><code>public class CallReceiver extends BroadcastReceiver {
    IncallActivity incallActivity = new IncallActivity();
    public MainActivity mainActivity;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
            mainActivity.callMode();
        } else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE)) {
            incallActivity.endCallMode();
        }
    }
}
</code>```

So why does this error show up?

答:
I found a way to do it.

You need to add a public static Context context to your code, and then in onCreate, do context = getBaseContext();

From there you can launch the second activity from any class you'd like.

Body:
So I've got this error code: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

The line: Intent callMode = new Intent(MainActivity.this, IncallActivity.class);

What I'm trying to do is to set a new activity when I receive a call. The following function is what should "switch" to that activity.

public void callMode() {
    Intent callMode = new Intent(MainActivity.this, IncallActivity.class);
    startActivity(callMode);
}

And it is located inside of the MainActivity class, outside of the onCreate function.
When I try to put it inside of the onCreate function (without public void callMode() of course) it works, but that's not the goal.

I'm trying to activate this new activity from another class, which listens for calls.

public class CallReceiver extends BroadcastReceiver {
    IncallActivity incallActivity = new IncallActivity();
    public MainActivity mainActivity;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
            mainActivity.callMode();
        } else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE)) {
            incallActivity.endCallMode();
        }
    }
}

So why does this error show up?


问:
How to create multiple class objects with a loop in python?
Suppose you have to create 10 class objects in python, and do something with them, like:

```<code>obj_1 = MyClass()
other_object.add(obj_1)
obj_2 = MyClass()
other_object.add(obj_2)
.
.
.
obj_10 = MyClass()
other_object.add(obj_10)
</code>```

How would you do it with a loop, and assign a variable to each object (like obj_1), so that the code will be shorter? Each object should be accessible outside the loop

```<code>obj_1.do_sth()
</code>```

答:
Using a dictionary for unique names without a name list:

```<code>class MyClass:
    def __init__(self, name):
        self.name = name
        self.pretty_print_name()

    def pretty_print_name(self):
    print("This object's name is {}.".format(self.name))

my_objects = {}
for i in range(1,11):
    name = 'obj_{}'.format(i)
    my_objects[name] = my_objects.get(name, MyClass(name = name))
</code>```

Output:

```<code>"This object's name is obj_1."
"This object's name is obj_2."
"This object's name is obj_3."
"This object's name is obj_4."
"This object's name is obj_5."
"This object's name is obj_6."
"This object's name is obj_7."
"This object's name is obj_8."
"This object's name is obj_9."
"This object's name is obj_10."
</code>```

Body:
Suppose you have to create 10 class objects in python, and do something with them, like:

obj_1 = MyClass()
other_object.add(obj_1)
obj_2 = MyClass()
other_object.add(obj_2)
.
.
.
obj_10 = MyClass()
other_object.add(obj_10)

How would you do it with a loop, and assign a variable to each object (like obj_1), so that the code will be shorter? Each object should be accessible outside the loop

obj_1.do_sth()

Body:
Using a dictionary for unique names without a name list:

class MyClass:
    def __init__(self, name):
        self.name = name
        self.pretty_print_name()

    def pretty_print_name(self):
    print("This object's name is {}.".format(self.name))

my_objects = {}
for i in range(1,11):
    name = 'obj_{}'.format(i)
    my_objects[name] = my_objects.get(name, MyClass(name = name))

Output:

"This object's name is obj_1."
"This object's name is obj_2."
"This object's name is obj_3."
"This object's name is obj_4."
"This object's name is obj_5."
"This object's name is obj_6."
"This object's name is obj_7."
"This object's name is obj_8."
"This object's name is obj_9."
"This object's name is obj_10."


问:
Add additional records to local Realm database in published app
I would like to bundle a local realm database with an iOS app and publish it to the app store. The initial database will ship with about 500 data records in a table, named TableA.

Then, in an app update I would like to insert an additional 250 records to TableA.

What would be an optimal solution for this scenario?

I have thought about including a JSON file in the app update with the 250 new records, and writing the data from the JSON into the realm database. Can anyone provide feedback on this solution, or suggest a better one?

答: When user first open the app, check your condition, and then you can show a progress bar and do your job. I think it's fine.</p>


问:
Which performance issue can I have with the unnecessarily large field data types?
Let's suppose I create a table named student and here is the part of the query.

```<code>CREATE TABLE student (
    id INT(11) PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(40) NOT NULL,
    department VARCHAR(500) NOT NULL,
...
</code>```

The department field can contain up to 500 characters, but in reality it's not likely for a record to take the entire length ('political science' is 17 characters long and 'computer engineering' takes 20 characters). But what I wonder is, which performance issue might occur if I leave the field as it is and execute queries?

答:
Why don't you create a separate table for the department?
The performance will be better when you query for all students in a department.</p>

Body:
Let's suppose I create a table named student and here is the part of the query.

CREATE TABLE student (
    id INT(11) PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(40) NOT NULL,
    department VARCHAR(500) NOT NULL,
...

The department field can contain up to 500 characters, but in reality it's not likely for a record to take the entire length ('political science' is 17 characters long and 'computer engineering' takes 20 characters). But what I wonder is, which performance issue might occur if I leave the field as it is and execute queries?


问:
How do I display taxonomy info from a wp-query?
I've got a wp-query that works a treat on a small section of my website's dashboard - it displays a list of repeat jobs (CPTs) that are due in 6 weeks time - I'm having issues with displaying a taxonomy related to the post.

So far I've got

```<code><?php

// get posts
$before_date = date("Ymd", strtotime("+6 weeks"));

$posts = get_posts(array(
    'post_type'         => 'pre_jobs',
    'posts_per_page'        => -1,
    'meta_key'          => 'pre_job_due_date',
    'orderby'           => 'meta_value',
    'order'             => 'ASC',
   'meta_query' => array(
        'relation'      => 'AND',
        array(
     'key' => 'pre_job_due_date',
     'value' => $before_date,
     'compare' => '<',
     ),
   ),
    'tax_query' => array(
        array(
            'taxonomy' => 'pre_job_status',
            'field' => 'slug',
            'terms' => array( 'repeat' )
        ),
    ),
));

if( $posts ): ?>

    <hr>
    <div class="dashpanel">
    <div class="duedate-head">Due Date</div>
    <div class="jobnumber-head">Job Type</div>
    <div class="client-head">Client/Requestor</div>
    <div class="customer-head">Customer</div>
</div>
<hr>

    <?php foreach( $posts as $post ):

        setup_postdata( $post )

        ?>
        <?php $job_type = get_field('pre_job_job_type', $client->ID ); ?>
        <?php $customer = get_field('pre_job_customer', $client->ID ); ?>
        <?php $job_client = get_field('pre_job_requestor', $client->ID ); ?>

        <div class="dashpanel">
    <a href="<?php the_permalink(); ?>">
    <div class="duedate"><?php the_field('pre_job_due_date'); ?></div>
    <div class="jobnumber"><?php echo $job_type[0]->post_title; ?></div>
    <div class="client"><?php echo $job_client[0]->post_title; ?></div>
    <div class="customer"><?php echo $customer[0]->post_title; ?></div></a>
    </div>
    <hr>

    <?php endforeach; ?>

    <?php wp_reset_postdata(); ?>
<?php else : ?>
<p>No upcoming jobs to book in.</p>
<?php endif; ?>
</code>```

I'm not sure where I need to put the

```<code><?php
$pre_job_type = get_field('pre_job_job_type');
if( $term ): ?>
</code>```

Code - every time I add this code it breaks. Or am I going completely wrong somewhere?

答:
Have you created your expected taxonomy? If haven't at first create the taxonomy on your functions.php file or where you have created your custom post type.

Example:

```<code>/**
 * Register a private 'Genre' taxonomy for post type 'book'.
 *
 * @see register_post_type() for registering post types.
 */
function wpdocs_register_taxonomy() {
    $args = array(
        'label'        => __( 'Job Type', 'textdomain' ),
        'public'       => true,
        'rewrite'      => true,
        'hierarchical' => true
    );

    register_taxonomy( 'pre_job_job_type', 'pre_jobs', $args );
}
add_action( 'init', 'wpdocs_register_taxonomy', 0 );
</code>```

Or OOP approach:

```<code>public function wpdocs_register_taxonomy() {
        $args = array(
            'label'        => __( 'Job Type', 'textdomain' ),
            'public'       => true,
            'rewrite'      => true,
            'hierarchical' => true
        );

        register_taxonomy( 'pre_job_job_type', 'pre_jobs', $args );
    }

/**
* When class is instantiated
*/

public function __construct() {

    add_action('init', array($this, 'wpdocs_register_taxonomy'));// Register texonomy

}
</code>```

Now your taxonomies are ready to display. Place this code where ever you want to display the taxonomies.

```<code>$pre_job_types = get_categories('taxonomy=pre_job_job_type&post_type=pre_jobs');
foreach ($pre_job_types as $job_type ) : ?>
     <span> <?php echo $job_type->name; </span>
endforeach;
</code>```

If you want to query your custom post with the taxonomy, follow this:

```<code>               $args = array(
                    'post_type' => 'pre_jobs',
                    'status' => 'published',
                    'tax_query' => array(
                      array(
                        'taxonomy' => 'pre_job_job_type',
                        'field' => 'name',
                        'terms' => array( 'repeat' )
                      )
                    )
                  );
                  $query = new WP_Query( $args );
</code>```

And then continue as a normal query. This query only display the posts whose taxonomy is "repeat".

Body:
I've got a wp-query that works a treat on a small section of my website's dashboard - it displays a list of repeat jobs (CPTs) that are due in 6 weeks time - I'm having issues with displaying a taxonomy related to the post.

So far I've got

<?php

// get posts
$before_date = date("Ymd", strtotime("+6 weeks"));

$posts = get_posts(array(
    'post_type'         => 'pre_jobs',
    'posts_per_page'        => -1,
    'meta_key'          => 'pre_job_due_date',
    'orderby'           => 'meta_value',
    'order'             => 'ASC',
   'meta_query' => array(
        'relation'      => 'AND',
        array(
     'key' => 'pre_job_due_date',
     'value' => $before_date,
     'compare' => '<',
     ),
   ),
    'tax_query' => array(
        array(
            'taxonomy' => 'pre_job_status',
            'field' => 'slug',
            'terms' => array( 'repeat' )
        ),
    ),
));

if( $posts ): ?>

Due Date

Job Type

Client/Requestor

Customer

    <?php foreach( $posts as $post ):

        setup_postdata( $post )

        ?>
        <?php $job_type = get_field('pre_job_job_type', $client->ID ); ?>
        <?php $customer = get_field('pre_job_customer', $client->ID ); ?>
        <?php $job_client = get_field('pre_job_requestor', $client->ID ); ?>

    <a href="<?php the_permalink(); ?>">

<?php the_field('pre_job_due_date'); ?>

<?php echo $job_type[0]->post_title; ?>

<?php echo $job_client[0]->post_title; ?>

<?php echo $customer[0]->post_title; ?>

    <?php endforeach; ?>

    <?php wp_reset_postdata(); ?>
<?php else : ?>

No upcoming jobs to book in.

<?php endif; ?>

I'm not sure where I need to put the

<?php
$pre_job_type = get_field('pre_job_job_type');
if( $term ): ?>

Code - every time I add this code it breaks. Or am I going completely wrong somewhere?

Body:
Have you created your expected taxonomy? If haven't at first create the taxonomy on your functions.php file or where you have created your custom post type.

Example:

/**
 * Register a private 'Genre' taxonomy for post type 'book'.
 *
 * @see register_post_type() for registering post types.
 */
function wpdocs_register_taxonomy() {
    $args = array(
        'label'        => __( 'Job Type', 'textdomain' ),
        'public'       => true,
        'rewrite'      => true,
        'hierarchical' => true
    );

    register_taxonomy( 'pre_job_job_type', 'pre_jobs', $args );
}
add_action( 'init', 'wpdocs_register_taxonomy', 0 );

Or OOP approach:

public function wpdocs_register_taxonomy() {
        $args = array(
            'label'        => __( 'Job Type', 'textdomain' ),
            'public'       => true,
            'rewrite'      => true,
            'hierarchical' => true
        );

        register_taxonomy( 'pre_job_job_type', 'pre_jobs', $args );
    }

/**
* When class is instantiated
*/

public function __construct() {

    add_action('init', array($this, 'wpdocs_register_taxonomy'));// Register texonomy

}

Now your taxonomies are ready to display. Place this code where ever you want to display the taxonomies.

$pre_job_types = get_categories('taxonomy=pre_job_job_type&post_type=pre_jobs');
foreach ($pre_job_types as $job_type ) : ?>
     <span> <?php echo $job_type->name; </span>
endforeach;

If you want to query your custom post with the taxonomy, follow this:

               $args = array(
                    'post_type' => 'pre_jobs',
                    'status' => 'published',
                    'tax_query' => array(
                      array(
                        'taxonomy' => 'pre_job_job_type',
                        'field' => 'name',
                        'terms' => array( 'repeat' )
                      )
                    )
                  );
                  $query = new WP_Query( $args );

And then continue as a normal query. This query only display the posts whose taxonomy is "repeat".


问:
Why does Tabulator subtract one day from the date entered when using moment.js as date formatter?
Please see the following fiddle: https://jsfiddle.net/rpowell6/adwu7x6e/22/.

A single day is being subtracted from any date entered, either manually or using the date picker.  The dateEditor function is taken from the Tabulator web site and makes use of moment.js for formatting.

Any assistance in determining why the day is being subtracted would be greatly appreciated.

答: The problem I was experiencing resulted from improperly copying a moment.js format() statement.  This issue has been resolved.