问:
What is the cause of artifacts on the Z axis in my 3D perlin noise?
I am currently working on a 3D Perlin noise implementation in C++, and there are strange block-like artifacts when I visualize it as a video of 2D slices through the 3D volume as defined by this code with just one octave:

```<code>#include <png++/png.hpp>
#include <memory>
#include <string>

#include "Octave.h"

constexpr unsigned IMAGE_SIZE = 512;

std::string numberToString(unsigned n, unsigned digits);

int main() {
    std::mt19937_64 rnd(0);
    auto octave = std::make_unique<Octave>(&rnd, 32, 1); //make_unique because Octave objects are too big to fit on the stack

    for(unsigned z=0;z<625;++z){
        std::cout << z << "/625" << std::endl;
        png::image<png::rgb_pixel> image(IMAGE_SIZE, IMAGE_SIZE);
        for(unsigned x=0;x<IMAGE_SIZE;++x){
            for(unsigned y=0;y<IMAGE_SIZE;++y){
                unsigned brightness = (octave->noise(x, z*(64.0/300.0), y)*.5+.5)*255;
                image[y][x] = png::rgb_pixel(brightness, brightness, brightness);
            }
        }
        image.write("output/perlin-" + numberToString(z, 4) + ".png");
    }

    return 0;
}

std::string numberToString(unsigned n, unsigned digits){
    std::string string = std::to_string(n);
    while(string.length() < digits){
        string = "0" + string;
    }
    return string;
}
</code>```

Each image from the above program is a single frame in a video. A video showing the output of this problem (converted to a video via ffmpeg) is available here: https://youtu.be/f7NxYo8U7TQ. Youtube added some compression artifacts in that video that are not present in the program's output.

As is clear in the above video, as the slice moves along the Z axis, square artifacts are present: . Depending on which plane slices are made in (eg. XZ or ZY), the artifacts slightly change in nature. It appears that they are worse just after a roll over in the frequency of the one rendered octave.

What is the cause of this?

Octave.h:

```<code>#pragma once

#include <array>
#include <random>

class Octave{
public:
    Octave(std::mt19937_64 *rnd, double frequency, double amplitude);
    double noise(double x, double y, double z);

private:
    static constexpr int PERMUTATION_TABLE_PART_SIZE = 1000000;
    static constexpr int PERMUTATION_TABLE_PART_COUNT = 3;
    static constexpr int PERMUTATION_TABLE_SIZE = PERMUTATION_TABLE_PART_SIZE*PERMUTATION_TABLE_PART_COUNT;
    std::array<int, PERMUTATION_TABLE_SIZE> m_permutationTable;
    double m_frequency, m_amplitude;

    double influence(int x, int y, int z, double distanceX, double distanceY, double distanceZ);

    inline static double square(double d) { return d*d; }
    inline static double vectorLength(double x, double y, double z);
    inline static double interpolate(double a, double b, double x);

};
</code>```

Octave.cpp:

```<code>#include "Octave.h"

#include <utility>
#include <cmath>
#include <iostream>

Octave::Octave(std::mt19937_64 *rnd, double frequency, double amplitude) : m_frequency(frequency), m_amplitude(amplitude) {
    //fill in basic array
    for(int i=0;i<PERMUTATION_TABLE_PART_SIZE;++i){
        for(int j=0;j<PERMUTATION_TABLE_PART_COUNT;++j){
            m_permutationTable[i+PERMUTATION_TABLE_PART_SIZE*j] = i;
        }
    }

    //shuffle array
    for(int i=0;i<PERMUTATION_TABLE_SIZE;++i){
        int swapWith = ((*rnd)() % (PERMUTATION_TABLE_SIZE-i))+i;
        std::swap(m_permutationTable[i], m_permutationTable[swapWith]);
    }
}

double Octave::noise(double x, double y, double z) {
    x /= m_frequency;
    y /= m_frequency;
    z /= m_frequency;

    int intX = std::floor(x);
    int intY = std::floor(y);
    int intZ = std::floor(z);

    double floatX = x - intX;
    double floatY = y - intY;
    double floatZ = z - intZ;

    double influence1 = influence(intX, intY, intZ, floatX, floatY, floatZ);
    double influence2 = influence(intX+1, intY, intZ, floatX-1, floatY, floatZ);
    double influence3 = influence(intX+1, intY+1, intZ, floatX-1, floatY-1, floatZ);
    double influence4 = influence(intX, intY+1, intZ, floatX, floatY-1, floatZ);
    double influence5 = influence(intX, intY, intZ+1, floatX, floatY, floatZ-1);
    double influence6 = influence(intX+1, intY, intZ+1, floatX-1, floatY, floatZ);
    double influence7 = influence(intX+1, intY+1, intZ+1, floatX-1, floatY-1, floatZ-1);
    double influence8 = influence(intX, intY+1, intZ+1, floatX, floatY-1, floatZ-1);

    double frontUpperInterpolatedValue = interpolate(influence4, influence3, floatX);
    double backUpperInterpolatedValue = interpolate(influence8, influence7, floatX);
    double frontLowerInterpolatedValue = interpolate(influence1, influence2, floatX);
    double backLowerInterpolatedValue = interpolate(influence5, influence6, floatX);

    double upperInterpolatedValue = interpolate(frontUpperInterpolatedValue, backUpperInterpolatedValue, floatZ);
    double lowerInterpolatedValue = interpolate(frontLowerInterpolatedValue, backLowerInterpolatedValue, floatZ);

    return interpolate(lowerInterpolatedValue, upperInterpolatedValue, floatY)*m_amplitude;
}

double Octave::influence(int x, int y, int z, double distanceX, double distanceY, double distanceZ) {
    //create un-normalized gradient vector
    //the ordering of x, y, and z is arbitrary but different to produce different x y and z
    double gradientX = (m_permutationTable[m_permutationTable[m_permutationTable[x]+y]+z]/static_cast<double>(PERMUTATION_TABLE_PART_SIZE))*2-1;
    double gradientY = (m_permutationTable[m_permutationTable[m_permutationTable[y]+x]+z]/static_cast<double>(PERMUTATION_TABLE_PART_SIZE))*2-1;
    double gradientZ = (m_permutationTable[m_permutationTable[m_permutationTable[y]+x]+z]/static_cast<double>(PERMUTATION_TABLE_PART_SIZE))*2-1;

    //normalize gradient vector
    double gradientVectorInverseLength = 1/vectorLength(gradientX, gradientY, gradientZ);
    gradientX *= gradientVectorInverseLength;
    gradientY *= gradientVectorInverseLength;
    gradientZ *= gradientVectorInverseLength;

    //compute dot product
    double dot = gradientX*distanceX+gradientY*distanceY+gradientZ*distanceZ;

    return dot;
}

double Octave::vectorLength(double x, double y, double z) {
    return std::sqrt(square(x)+square(y)+square(z));
}

double Octave::interpolate(double a, double b, double x) {
    return (b-a)*(6*x*x*x*x*x-15*x*x*x*x+10*x*x*x)+a;
}
</code>```

答: I determined the issue. I forgot to do floatZ-1 when calculating influence6.

Body:
I am currently working on a 3D Perlin noise implementation in C++, and there are strange block-like artifacts when I visualize it as a video of 2D slices through the 3D volume as defined by this code with just one octave:

#include <png++/png.hpp>
#include <memory>
#include <string>

#include "Octave.h"

constexpr unsigned IMAGE_SIZE = 512;

std::string numberToString(unsigned n, unsigned digits);

int main() {
    std::mt19937_64 rnd(0);
    auto octave = std::make_unique<Octave>(&rnd, 32, 1); //make_unique because Octave objects are too big to fit on the stack

    for(unsigned z=0;z<625;++z){
        std::cout << z << "/625" << std::endl;
        png::image<png::rgb_pixel> image(IMAGE_SIZE, IMAGE_SIZE);
        for(unsigned x=0;x<IMAGE_SIZE;++x){
            for(unsigned y=0;y<IMAGE_SIZE;++y){
                unsigned brightness = (octave->noise(x, z*(64.0/300.0), y)*.5+.5)*255;
                image[y][x] = png::rgb_pixel(brightness, brightness, brightness);
            }
        }
        image.write("output/perlin-" + numberToString(z, 4) + ".png");
    }

    return 0;
}

std::string numberToString(unsigned n, unsigned digits){
    std::string string = std::to_string(n);
    while(string.length() < digits){
        string = "0" + string;
    }
    return string;
}

Each image from the above program is a single frame in a video. A video showing the output of this problem (converted to a video via ffmpeg) is available here: https://youtu.be/f7NxYo8U7TQ. Youtube added some compression artifacts in that video that are not present in the program's output.

As is clear in the above video, as the slice moves along the Z axis, square artifacts are present: . Depending on which plane slices are made in (eg. XZ or ZY), the artifacts slightly change in nature. It appears that they are worse just after a roll over in the frequency of the one rendered octave.

What is the cause of this?

Octave.h:

#pragma once

#include <array>
#include <random>

class Octave{
public:
    Octave(std::mt19937_64 *rnd, double frequency, double amplitude);
    double noise(double x, double y, double z);

private:
    static constexpr int PERMUTATION_TABLE_PART_SIZE = 1000000;
    static constexpr int PERMUTATION_TABLE_PART_COUNT = 3;
    static constexpr int PERMUTATION_TABLE_SIZE = PERMUTATION_TABLE_PART_SIZE*PERMUTATION_TABLE_PART_COUNT;
    std::array<int, PERMUTATION_TABLE_SIZE> m_permutationTable;
    double m_frequency, m_amplitude;

    double influence(int x, int y, int z, double distanceX, double distanceY, double distanceZ);

    inline static double square(double d) { return d*d; }
    inline static double vectorLength(double x, double y, double z);
    inline static double interpolate(double a, double b, double x);

};

Octave.cpp:

#include "Octave.h"

#include <utility>
#include <cmath>
#include <iostream>

Octave::Octave(std::mt19937_64 *rnd, double frequency, double amplitude) : m_frequency(frequency), m_amplitude(amplitude) {
    //fill in basic array
    for(int i=0;i<PERMUTATION_TABLE_PART_SIZE;++i){
        for(int j=0;j<PERMUTATION_TABLE_PART_COUNT;++j){
            m_permutationTable[i+PERMUTATION_TABLE_PART_SIZE*j] = i;
        }
    }

    //shuffle array
    for(int i=0;i<PERMUTATION_TABLE_SIZE;++i){
        int swapWith = ((*rnd)() % (PERMUTATION_TABLE_SIZE-i))+i;
        std::swap(m_permutationTable[i], m_permutationTable[swapWith]);
    }
}

double Octave::noise(double x, double y, double z) {
    x /= m_frequency;
    y /= m_frequency;
    z /= m_frequency;

    int intX = std::floor(x);
    int intY = std::floor(y);
    int intZ = std::floor(z);

    double floatX = x - intX;
    double floatY = y - intY;
    double floatZ = z - intZ;

    double influence1 = influence(intX, intY, intZ, floatX, floatY, floatZ);
    double influence2 = influence(intX+1, intY, intZ, floatX-1, floatY, floatZ);
    double influence3 = influence(intX+1, intY+1, intZ, floatX-1, floatY-1, floatZ);
    double influence4 = influence(intX, intY+1, intZ, floatX, floatY-1, floatZ);
    double influence5 = influence(intX, intY, intZ+1, floatX, floatY, floatZ-1);
    double influence6 = influence(intX+1, intY, intZ+1, floatX-1, floatY, floatZ);
    double influence7 = influence(intX+1, intY+1, intZ+1, floatX-1, floatY-1, floatZ-1);
    double influence8 = influence(intX, intY+1, intZ+1, floatX, floatY-1, floatZ-1);

    double frontUpperInterpolatedValue = interpolate(influence4, influence3, floatX);
    double backUpperInterpolatedValue = interpolate(influence8, influence7, floatX);
    double frontLowerInterpolatedValue = interpolate(influence1, influence2, floatX);
    double backLowerInterpolatedValue = interpolate(influence5, influence6, floatX);

    double upperInterpolatedValue = interpolate(frontUpperInterpolatedValue, backUpperInterpolatedValue, floatZ);
    double lowerInterpolatedValue = interpolate(frontLowerInterpolatedValue, backLowerInterpolatedValue, floatZ);

    return interpolate(lowerInterpolatedValue, upperInterpolatedValue, floatY)*m_amplitude;
}

double Octave::influence(int x, int y, int z, double distanceX, double distanceY, double distanceZ) {
    //create un-normalized gradient vector
    //the ordering of x, y, and z is arbitrary but different to produce different x y and z
    double gradientX = (m_permutationTable[m_permutationTable[m_permutationTable[x]+y]+z]/static_cast<double>(PERMUTATION_TABLE_PART_SIZE))*2-1;
    double gradientY = (m_permutationTable[m_permutationTable[m_permutationTable[y]+x]+z]/static_cast<double>(PERMUTATION_TABLE_PART_SIZE))*2-1;
    double gradientZ = (m_permutationTable[m_permutationTable[m_permutationTable[y]+x]+z]/static_cast<double>(PERMUTATION_TABLE_PART_SIZE))*2-1;

    //normalize gradient vector
    double gradientVectorInverseLength = 1/vectorLength(gradientX, gradientY, gradientZ);
    gradientX *= gradientVectorInverseLength;
    gradientY *= gradientVectorInverseLength;
    gradientZ *= gradientVectorInverseLength;

    //compute dot product
    double dot = gradientX*distanceX+gradientY*distanceY+gradientZ*distanceZ;

    return dot;
}

double Octave::vectorLength(double x, double y, double z) {
    return std::sqrt(square(x)+square(y)+square(z));
}

double Octave::interpolate(double a, double b, double x) {
    return (b-a)*(6*x*x*x*x*x-15*x*x*x*x+10*x*x*x)+a;
}


来源: stackexchange

问:
How to change field name in collection result on Laravel
I'm working Laravel collection. I would like to change some eloquent output field name. Below is my query code.

```<code>$labdetails =LabDetailCustom::where('labcode',$request->labcode)->get(['id','name']);
</code>```

And resulted as below.

```<code>[
{
id: 65,
name: "Color"
},
{
id: 66,
name: "Apearance"
},
{
id: 67,
name: "Urobilinogen"
}
]
</code>```

But my need is to change 'id' to 'codename' instead. So result should be.

```<code>[
{
codename: 65,
name: "Color"
},
{
codename: 66,
name: "Apearance"
},
{
codename: 67,
name: "Urobilinogen"
}
]
</code>```

It may need to use 'map function' that I'm not familiar. Any advise or guidance would be greatly appreciated, Thanks.

答:
You can use AS MySQL query here.

```<code>$labdetails = LabDetailCustom::select('id AS codename', 'name')->where('labcode', $request->labcode)->get();

$labdetails->codename;
$labdetails->name;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm working Laravel collection. I would like to change some eloquent output field name. Below is my query code.

$labdetails =LabDetailCustom::where('labcode',$request->labcode)->get(['id','name']);

And resulted as below.

[
{
id: 65,
name: "Color"
},
{
id: 66,
name: "Apearance"
},
{
id: 67,
name: "Urobilinogen"
}
]

But my need is to change 'id' to 'codename' instead. So result should be.

[
{
codename: 65,
name: "Color"
},
{
codename: 66,
name: "Apearance"
},
{
codename: 67,
name: "Urobilinogen"
}
]

It may need to use 'map function' that I'm not familiar. Any advise or guidance would be greatly appreciated, Thanks.

Body:
You can use AS MySQL query here.

$labdetails = LabDetailCustom::select('id AS codename', 'name')->where('labcode', $request->labcode)->get();

$labdetails->codename;
$labdetails->name;


问:
C# logic question
I have those boolean values:

```<code>bool test = false && true || true; // true
bool test1 = false && (true || true); // false
</code>```

Now, can anybody explain why this is? Shouldnt those be the same?

Thanks :)

答:
bool test = false && true || true; // true

This first is true because the statement is testing whether the it is true or false.

bool test1 = false && (true || true); // false

The second one if false because the statement is testing whether it is true and false.

ContentLicense: CC BY-SA 3.0

Title: C# logic question

Body:
I have those boolean values:

bool test = false && true || true; // true
bool test1 = false && (true || true); // false

Now, can anybody explain why this is? Shouldnt those be the same?

Thanks :)


问:
Snake game, increasing length in processing
I am trying to recreate the snake game, right now i am stuck on adding a new section to the snake everything it collides with an apple

I tried to tell the program to draw a new rectangle but with the x axis slightly shifted and this "shifting" would slowly increase every time my snake eats an apple. My snake starts off with 2 sections, and when i move the snake towards the green apple, it only moves the second section instead of drawing a new one, I know i didn't tell my draw method to draw a new rectangle every time my snake eats an apple since i have no clue on how to do that

```<code>public void draw(PApplet p) {
    // clear area
    p.fill(255, 0, 0);

    // draw snake head
    p.rect(x, y, length, width);

    // draw snake body ?
    if (upIsDown == true ) {
        p.rect(x, y - section, length, width);
    } else if(downIsDown == true) {
        p.rect(x, y + section, length, width);
    } else if(RightIsDown == true) {
        p.rect(x - section, y, length, width);
    } else if(LeftIsDown == true) {
        RightIsDown = false;
        p.rect(x + section, y, length, width);
    }
}
</code>```

the section variable increases by 10 in my checkCollision method

The snake gets longer, but my program only draws the head and the tail of the snake

答:
I added comments to your code.

You code in draw clears the whole game area, then draws 2 rectangles. If you want to see 3 rectanges, you will need to call p.rect() 3 times in that method. If you want to see 10 rectanges, you will need to call it 10 times (so maybe a loop would be good). Else reconsider the call to p.fill() in the beginning.

For a loop, you would need to store the coordinates for each body segment in a structure like a LinkedList, with the coordinates for each segment, and in the draw method draw all segments.

Body:
I am trying to recreate the snake game, right now i am stuck on adding a new section to the snake everything it collides with an apple

I tried to tell the program to draw a new rectangle but with the x axis slightly shifted and this "shifting" would slowly increase every time my snake eats an apple. My snake starts off with 2 sections, and when i move the snake towards the green apple, it only moves the second section instead of drawing a new one, I know i didn't tell my draw method to draw a new rectangle every time my snake eats an apple since i have no clue on how to do that

public void draw(PApplet p) {
    // clear area
    p.fill(255, 0, 0);

    // draw snake head
    p.rect(x, y, length, width);

    // draw snake body ?
    if (upIsDown == true ) {
        p.rect(x, y - section, length, width);
    } else if(downIsDown == true) {
        p.rect(x, y + section, length, width);
    } else if(RightIsDown == true) {
        p.rect(x - section, y, length, width);
    } else if(LeftIsDown == true) {
        RightIsDown = false;
        p.rect(x + section, y, length, width);
    }
}

the section variable increases by 10 in my checkCollision method

The snake gets longer, but my program only draws the head and the tail of the snake


问:
Error: Could not load log4net assembly
I am looking to solve this error:

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The system cannot find the file specified." This error is located in the web.config file.

When I copy log4net.dll to the bin directory of my webapp, I get a

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.

This error also occurs in the web.config file.

It's easy enough to change the version and the public key token to match the file so that the assembly loads correctly. When I do that, my website runs perfectly, except for when a reportViewer object is initialized. Then it throws the original error at the reportViewer tag, not the web.config.

My hypothesis is that if I install the requested version of log4net.dll, my problems will be solved. But I have no clue which file that it, or where to find it. I've checked the obvious by downloading log4net 1.2.10 and trying out every dll in the download.

I should mention that the website runs without issues on my development machine, but not when published to my server.

I'm running an asp.net website, .NET 4.0, IIS 7, on a Server 2008 R2 OS. I've installed Crystal Reports 13.0.1 for 64bit (my machine is 64bit).

How can I resolve this issue?

EDIT:
In response to @Kevian's answer, I have made the change to my web.config file. I still get the error where the manifest definition doesn't match the assembly reference. The code that throws this error is:

```<code>Line 33:     <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server"   AutoDataBind="true"
Line 34:         BestFitPage="True" ToolPanelView="None" />
</code>```

答:
If your machine is 64bit and you install Crystal Report 32bit version, then this error will haunt you like anything. In this case, all the required assemblies are properly registered in GAC but still, it says "unable to load log4net assembly..."
The reason for this error is that you are trying to execute a 32bit application on a 64bit machine.

If you are implementing reporting on the server side the IIS will not allow executing this application. To resolve this you have to enable 32bit application in IIS.

Steps for this are:

Go to the app pool on which you are running your application

Right click and go to Advanced Settings

Here find "Enable 32-Bit Applications" and set it to true

Reset IIS (iisreset)

Title: Error: Could not load log4net assembly

Body:
I am looking to solve this error:

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The system cannot find the file specified." This error is located in the web.config file.

When I copy log4net.dll to the bin directory of my webapp, I get a

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.

This error also occurs in the web.config file.

It's easy enough to change the version and the public key token to match the file so that the assembly loads correctly. When I do that, my website runs perfectly, except for when a reportViewer object is initialized. Then it throws the original error at the reportViewer tag, not the web.config.

My hypothesis is that if I install the requested version of log4net.dll, my problems will be solved. But I have no clue which file that it, or where to find it. I've checked the obvious by downloading log4net 1.2.10 and trying out every dll in the download.

I should mention that the website runs without issues on my development machine, but not when published to my server.

I'm running an asp.net website, .NET 4.0, IIS 7, on a Server 2008 R2 OS. I've installed Crystal Reports 13.0.1 for 64bit (my machine is 64bit).

How can I resolve this issue?

EDIT:
In response to @Kevian's answer, I have made the change to my web.config file. I still get the error where the manifest definition doesn't match the assembly reference. The code that throws this error is:

Line 33:     <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server"   AutoDataBind="true"
Line 34:         BestFitPage="True" ToolPanelView="None" />


问:
how to run code in the background on ios unity
I have a waiting room in unity with photon and when there are enough players a countodown starts, only problem is if the master client is using IOS and they check notification or are not in the app then the game will never starts when it hits 0 until they come back in the game. Is there a way to run the code and force it to start while in the background?

If this is not possible can I use OnApplicationPause() to run code if the OnApplicationPause is more than a certain time(say 5 seconds). So basically if the user leaves for 5 seconds then I would kick them out of the scene and send them to another scene.

Thanks.

答:
I don't know about IOS Unity but in android, you can use a Service to run script in the background
Start android service from Unity3D code

I think this is another way to solve your problem:

When OnApplicationPause() is called, you can send a signal to your
server to run a timer.

When this timer reaching elapse time, your server will kick the pause
guy out of room.

It would better if you run a timer in server instead of client (user's device not work well, there is some case that you can't handle, etc)


问:
How can I finish "group" of Activities?
I have an operation in my Android app which includes a couple of activities. At the end of this operation, I need to close all of these activities and go back to the screen which starts this operation. Below is a diagram explaining how this should work. Are there are any options to do this?

P/S/ Fragments is not an option in my case

答:
you can use flag=Intent.FLAG_ACTIVITY_CLEAR_TASK to clear all previous activity . This flag is used to clear all previous activity .

try this code

```<code> //  go to login activity

Intent intent =newIntent(AddNewCardActivity.this,HomeNavigationActivity.class);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            finish();
</code>```

Title: How can I finish "group" of Activities?

Body:
you can use flag=Intent.FLAG_ACTIVITY_CLEAR_TASK to clear all previous activity . This flag is used to clear all previous activity .

try this code

 //  go to login activity

Intent intent =newIntent(AddNewCardActivity.this,HomeNavigationActivity.class);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            finish();


问:
What's the correct way to pause the entire script execution contingent on an asynchronous function in JavaScript?
A lot of my script is contingent on information first read from a .JSON file using fetch() and .json() so it's asynchronous. I need to delay the execution of the rest of my script until those functions finish, without sticking the rest of my code in a huge .then() or function block or something. I've done some searching around but I can't really find what I'm looking for.

```<code>let config;

fetch(chrome.runtime.getURL("../config.json"))
  .then(response => response.json())
  .then(json => config = json);

console.log(config);
// REST OF SCRIPT
</code>```

It should log the config JSON object or the promise but, obviously, it only returns undefined. Any help would be greatly appreciated!

答:
you can use this:

```<code>fetch(chrome.runtime.getURL("../config.json"))
    .then(response => response.json())
    .then(config => console.log(config));
</code>```

Or:

```<code>const response = await fetch(chrome.runtime.getURL("../config.json"));
const config = await response.json();
config => console.log(config)
</code>```

Body:
A lot of my script is contingent on information first read from a .JSON file using fetch() and .json() so it's asynchronous. I need to delay the execution of the rest of my script until those functions finish, without sticking the rest of my code in a huge .then() or function block or something. I've done some searching around but I can't really find what I'm looking for.

let config;

fetch(chrome.runtime.getURL("../config.json"))
  .then(response => response.json())
  .then(json => config = json);

console.log(config);
// REST OF SCRIPT

It should log the config JSON object or the promise but, obviously, it only returns undefined. Any help would be greatly appreciated!

Body:
you can use this:

fetch(chrome.runtime.getURL("../config.json"))
    .then(response => response.json())
    .then(config => console.log(config));

Or:

const response = await fetch(chrome.runtime.getURL("../config.json"));
const config = await response.json();
config => console.log(config)


问:
Why is the ::before pseudo element going on top on mobile menu?
I have a menu that has a png img as ::before pseudo-element, and instead of sticking next to menu items, it's going on top.

const menu_button = $('img');
const menu_nav = $('#myNav');

menu_button.click(function(){
  menu_nav.toggleClass('menu_open')
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.overlay {
  height: 0%;
  width: 100%;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #d6cece;
  overflow-y: auto;
  transition: 0.5s;
}

.overlay-content {
  position: relative;
  top: 10%;
  width: 100%;
  margin-top: 50px;
}

.overlay a {
  padding-left: 30px;
  padding-bottom: 5px;
  padding-top: 5px;
  text-decoration: none;
  font-size: 27px;
  display: block;
  transition: 0.3s;
  font-style: italic;
  color: black;
}

.overlay-content a:before {
  width: 6px;
  content: " ";
  background-image: url(https://picsum.photos/5);
  background-repeat: no-repeat;
  position: absolute;
  left: 18px;
  top: 18px;
  height: 20px;
}

.menu_open {
  height: 100%;
}</code>```

    Test
    Test
    Test
    Test

```

Why this behavior? It's working without the menu, but not when the elements are vertically aligned. Please check out the snippet I quickly made.

答:
it should probably be something like this

```<code>.overlay-content > a:before {
    content: "";
    display: block;
    background: url("https://picsum.photos/5") no-repeat;
    width: 20px;
    height: 20px;
    float: left;
    margin: 0 6px 0 0;
}
</code>```

and then change this to

```<code>.overlay-content a:before {
  width: 6px;
  content: " ";
  background-image: url(https://picsum.photos/5);
  background-repeat: no-repeat;
  position: absolute;
  left: 18px;
  top: 18px;
  height: 20px;
}
</code>```

Body:
I have a menu that has a png img as ::before pseudo-element, and instead of sticking next to menu items, it's going on top.

const menu_button = $('img');
const menu_nav = $('#myNav');

menu_button.click(function(){
  menu_nav.toggleClass('menu_open')
});

.overlay {
  height: 0%;
  width: 100%;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #d6cece;
  overflow-y: auto;
  transition: 0.5s;
}

.overlay-content {
  position: relative;
  top: 10%;
  width: 100%;
  margin-top: 50px;
}

.overlay a {
  padding-left: 30px;
  padding-bottom: 5px;
  padding-top: 5px;
  text-decoration: none;
  font-size: 27px;
  display: block;
  transition: 0.3s;
  font-style: italic;
  color: black;
}

.overlay-content a:before {
  width: 6px;
  content: " ";
  background-image: url(https://picsum.photos/5);
  background-repeat: no-repeat;
  position: absolute;
  left: 18px;
  top: 18px;
  height: 20px;
}

.menu_open {
  height: 100%;
}

    Test
    Test
    Test
    Test

Why this behavior? It's working without the menu, but not when the elements are vertically aligned. Please check out the snippet I quickly made.

Body:
it should probably be something like this

.overlay-content > a:before {
    content: "";
    display: block;
    background: url("https://picsum.photos/5") no-repeat;
    width: 20px;
    height: 20px;
    float: left;
    margin: 0 6px 0 0;
}

and then change this to

.overlay-content a:before {
  width: 6px;
  content: " ";
  background-image: url(https://picsum.photos/5);
  background-repeat: no-repeat;
  position: absolute;
  left: 18px;
  top: 18px;
  height: 20px;
}


问:
Bootstrap modal hide not working with jquery ajax
I have a modal dialog made with bootstrap, like this:

```<code><div class="modal fade" id="myid">
  <div class="modal-dialog">
    <div class="modal-content">
       Loading...
    </div>
  </div>
</div>
</code>```

And I make a javascript function like this:

```<code>$(document)
            .ajaxStart(function () {
                $('#myid').modal('show');
            })
            .ajaxStop(function () {
                $('#myid').modal('hide');
            });
</code>```

But when I call some ajax function the modal appears but no hide. I put console.log in both functions (ajaxStart and ajaxStop) and it was called. when I replace ajaxStop as below, everything works, but not appears right.

```<code>$(document)
                .ajaxStart(function () {
                    $('#myid').modal('show');
                })
                .ajaxStop(function () {
                    $('#myid').hide();
                    $('.fade').hide();
                });
</code>```

The main problema is when I call another modal within ajax, then I click in link, loading ajax appears, request is send to server, response returns, modal with data from request appears, but loading modal not hide.

How can I fix it?

答:
You have to set a timeout.
That works for me:</p>

```<code>setTimeout(function () { $("#myid").modal("hide"); }, 500);
</code>```

Body:
I have a modal dialog made with bootstrap, like this:

       Loading...

And I make a javascript function like this:

$(document)
            .ajaxStart(function () {
                $('#myid').modal('show');
            })
            .ajaxStop(function () {
                $('#myid').modal('hide');
            });

But when I call some ajax function the modal appears but no hide. I put console.log in both functions (ajaxStart and ajaxStop) and it was called. when I replace ajaxStop as below, everything works, but not appears right.

$(document)
                .ajaxStart(function () {
                    $('#myid').modal('show');
                })
                .ajaxStop(function () {
                    $('#myid').hide();
                    $('.fade').hide();
                });

The main problema is when I call another modal within ajax, then I click in link, loading ajax appears, request is send to server, response returns, modal with data from request appears, but loading modal not hide.

How can I fix it?

Body:
You have to set a timeout.
That works for me:

setTimeout(function () { $("#myid").modal("hide"); }, 500);


问:
How do I insert a website inside my html web page
How do I insert a youtube web page into my HTML web page using I frame,
and please I need a code snippet that I can run to see how it looks like.</p>

答:
There are multiple ways to start a video on the web page.

Below can work out.

```<code><iframe width="420" height="345" src="https://www.youtube.com/embed/tgbNymZ7vqY?autoplay=1">
</iframe>
</code>```

Body:
There are multiple ways to start a video on the web page.

Below can work out.

<iframe width="420" height="345" src="https://www.youtube.com/embed/tgbNymZ7vqY?autoplay=1">
</iframe>


问:
Integrity error in django foreign key field in django-rest-framework
I'm fairly new in django. I've had a foreignkey field as supervisor as shown below

```<code>class Site(models.Model):
sitename=models.CharField(max_length=255)
start_date=models.DateTimeField
supervisor=models.ForeignKey(User,on_delete=models.PROTECT)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

def __str__(self):
    return "{}".format(self.sitename)
</code>```

The serializer for this is:

```<code>class SiteSerializer(serializers.ModelSerializer):

supervisor = serializers.ReadOnlyField(source='supervisor.username')

class Meta:
    model = Site
    fields = ('sitename', 'start_date', 'supervisor')
</code>```

and the view for this is:

```<code>@csrf_exempt
def site_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        sites = Site.objects.all()
        serializer = SiteSerializer(sites, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':

    data = JSONParser().parse(request)

    serializer = SiteSerializer(data=data)

    if serializer.is_valid():
        serializer.save()
        return JsonResponse(serializer.data, status=201)
    return JsonResponse(serializer.errors, status=400)
</code>```

Whenever I post data from postman, it says IntegrityError at /sites/
(1048, "Column 'supervisor_id' cannot be null")

I named the model field as supervisor and the db field becomes supervisor_id as django does it. But,how do I sort this error out.
This might be a really little thing but I couldnt figure out where to make the nexessary adjustments.
Please help.

My post request is {
    "sitename" : "Tony Tower",
    "start_date" :"2019-5-5",
    "supervisor" : "1"
} OR

```<code>{
"sitename" : "Putalisadak",
"start_date" :"2019-5-5",
"supervisor_id" : "1"
}
</code>```

both yielding the same output

答:
I think the error is in the line: supervisor = serializers.ReadOnlyField(source='supervisor.username')
did you try remove it?</p>

Body:
I'm fairly new in django. I've had a foreignkey field as supervisor as shown below

class Site(models.Model):
sitename=models.CharField(max_length=255)
start_date=models.DateTimeField
supervisor=models.ForeignKey(User,on_delete=models.PROTECT)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

def __str__(self):
    return "{}".format(self.sitename)

The serializer for this is:

class SiteSerializer(serializers.ModelSerializer):

supervisor = serializers.ReadOnlyField(source='supervisor.username')

class Meta:
    model = Site
    fields = ('sitename', 'start_date', 'supervisor')

and the view for this is:

@csrf_exempt
def site_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        sites = Site.objects.all()
        serializer = SiteSerializer(sites, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':

    data = JSONParser().parse(request)

    serializer = SiteSerializer(data=data)

    if serializer.is_valid():
        serializer.save()
        return JsonResponse(serializer.data, status=201)
    return JsonResponse(serializer.errors, status=400)

Whenever I post data from postman, it says IntegrityError at /sites/
(1048, "Column 'supervisor_id' cannot be null")

I named the model field as supervisor and the db field becomes supervisor_id as django does it. But,how do I sort this error out.
This might be a really little thing but I couldnt figure out where to make the nexessary adjustments.
Please help.

My post request is {
    "sitename" : "Tony Tower",
    "start_date" :"2019-5-5",
    "supervisor" : "1"
} OR

{
"sitename" : "Putalisadak",
"start_date" :"2019-5-5",
"supervisor_id" : "1"
}

both yielding the same output


问:
SetText on Object not working for Calendar
So I'm using the following Java library: UmmalquraCalendar

I am using java.text.SimpleDateFormat to parse Ummalqura date.

MainActivity onCreate method taken from the library README.md file:

```<code>Locale en = Locale.ENGLISH;
UmmalquraCalendar uCal = new UmmalquraCalendar(en);

SimpleDateFormat dateFormat = new SimpleDateFormat("", en);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
dateFormat.setCalendar(uCal);
uCal.set(Calendar.YEAR, 1420);
dateFormat.set2DigitYearStart(uCal.getTime());

Calendar cal = new UmmalquraCalendar(en);

dateFormat.applyPattern("d/M/y");
cal.get(Calendar.YEAR);
cal.getDisplayName(Calendar.MONTH, Calendar.LONG, en);
cal.get(Calendar.DAY_OF_MONTH);
</code>```

My understanding is cal is an object so to display this in a TextView using setText, I would need to convert it to a string so I added the following to my code:

```<code>String islamicDate = cal.toString();
layoutDate.setText(islamicDate);
</code>```

OUTPUT:

Can someone please help me understand where I am going wrong here?

答:
your are setting your textview with the hole object , try this :

```<code>String year = String.valueOf(cal.get(Calendar.YEAR));
String month = String.valueOf(cal.getDisplayName(Calendar.MONTH, Calendar.LONG, en));
String day = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
layoutDate.setText(year + "-" + month +"-" + day);
</code>```

Body:
So I'm using the following Java library: UmmalquraCalendar

I am using java.text.SimpleDateFormat to parse Ummalqura date.

MainActivity onCreate method taken from the library README.md file:

Locale en = Locale.ENGLISH;
UmmalquraCalendar uCal = new UmmalquraCalendar(en);

SimpleDateFormat dateFormat = new SimpleDateFormat("", en);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
dateFormat.setCalendar(uCal);
uCal.set(Calendar.YEAR, 1420);
dateFormat.set2DigitYearStart(uCal.getTime());

Calendar cal = new UmmalquraCalendar(en);

dateFormat.applyPattern("d/M/y");
cal.get(Calendar.YEAR);
cal.getDisplayName(Calendar.MONTH, Calendar.LONG, en);
cal.get(Calendar.DAY_OF_MONTH);

My understanding is cal is an object so to display this in a TextView using setText, I would need to convert it to a string so I added the following to my code:

String islamicDate = cal.toString();
layoutDate.setText(islamicDate);

OUTPUT:

Can someone please help me understand where I am going wrong here?

Body:
your are setting your textview with the hole object , try this :

String year = String.valueOf(cal.get(Calendar.YEAR));
String month = String.valueOf(cal.getDisplayName(Calendar.MONTH, Calendar.LONG, en));
String day = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
layoutDate.setText(year + "-" + month +"-" + day);


问:
Error On Using Route53 ChangeResourceRecordSets
I'm currently using Grails 2.4.5 and used AmazonWebService plugin for grails 2.4.5

I'm trying to create a new recordset on route53 using this plugin.

On my BuildConfig.groovy I used this plugin fro aws web services.

compile ":aws-sdk:1.10.44"

I need your help guys regarding route53 change resource record sets.

I got an error below when I tried to change route53 resource record sets.

```<code>Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], or TrafficPolicyInstanceId], but found more than one in Change with [Action=CREATE, Name=app.sample.com., Type=A, SetIdentifier=null] (Service: AmazonRoute53; Status Code: 400; Error Code: InvalidInput; Request ID: 2ca80154-78a7-11e9-b5e7-f7bc7c79e5e6). Stacktrace follows:
Message: Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], or TrafficPolicyInstanceId], but found more than one in Change with [Action=CREATE, Name=app.sample.com., Type=A, SetIdentifier=null] (Service: AmazonRoute53; Status Code: 400; Error Code: InvalidInput; Request ID: 2ca80154-78a7-11e9-b5e7-f7bc7c79e5e6)
</code>```

This is my code.

```<code>import com.amazonaws.services.route53.AmazonRoute53Client
import com.amazonaws.services.route53.model.AliasTarget
import com.amazonaws.services.route53.model.Change
import com.amazonaws.services.route53.model.ChangeAction
import com.amazonaws.services.route53.model.ChangeBatch
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsRequest
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsResult
import com.amazonaws.services.route53.model.RRType
import com.amazonaws.services.route53.model.ResourceRecord
import com.amazonaws.services.route53.model.ResourceRecordSet
import grails.plugin.awssdk.AmazonWebService
import grails.transaction.Transactional

@Transactional
class AwsRoute53Service {

    AmazonWebService amazonWebService

    ChangeResourceRecordSetsResult changeRecordSet() {
        AmazonRoute53Client route53Client = amazonWebService.route53

        AliasTarget target = new AliasTarget('hostedZoneIDHere', 'app.sample.com.')

        target.setEvaluateTargetHealth(true)

        List<ResourceRecord> resourceRecords = new ArrayList<>()

        resourceRecords.add(new ResourceRecord('dNSNameHere'))

        ResourceRecordSet recordSet = new ResourceRecordSet('app.sample.com.', RRType.A)

        recordSet.setAliasTarget(target)
        recordSet.setResourceRecords(resourceRecords)
        recordSet.setTrafficPolicyInstanceId('simple')

        List<Change> changes = new ArrayList<>()

        changes.add(new Change(ChangeAction.CREATE, recordSet))

        ChangeBatch changeBatch = new ChangeBatch(changes)

        ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest('hostedZoneIDHere', changeBatch)

        return route53Client.changeResourceRecordSets(request)
    }
}
</code>```

Can you tell me what is the problem with the setup?

I would be glad if you can help me with my problem right now.
Thank you guys.

答:
I already solve this problem. below is the working code.</p>

```<code>import com.amazonaws.services.route53.AmazonRoute53Client
import com.amazonaws.services.route53.model.AliasTarget
import com.amazonaws.services.route53.model.Change
import com.amazonaws.services.route53.model.ChangeAction
import com.amazonaws.services.route53.model.ChangeBatch
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsRequest
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsResult
import com.amazonaws.services.route53.model.RRType
import com.amazonaws.services.route53.model.ResourceRecord
import com.amazonaws.services.route53.model.ResourceRecordSet
import grails.plugin.awssdk.AmazonWebService
import grails.transaction.Transactional

@Transactional
class AwsRoute53Service {

    private static final String DOMAIN_NAME_SERVER = "${System.env.DOMAIN_NAME_SERVER}"
    private static final String HOSTED_ZONE_ID = "${System.env.HOSTED_ZONE_ID}"

    AmazonWebService amazonWebService

    ChangeResourceRecordSetsResult changeRecordSet() {
        AmazonRoute53Client route53Client = amazonWebService.route53

        GetHostedZoneResult hostedZoneResult = route53Client.getHostedZone(new GetHostedZoneRequest(HOSTED_ZONE_ID))
        HostedZone hostedZone = hostedZoneResult.getHostedZone()

        ResourceRecordSet resourceRecordSet = new ResourceRecordSet()
            .withName('dNSName')
            .withType(RRType.CNAME)
            .withTTL(60)
            .withResourceRecords([
                new ResourceRecord().withValue(DOMAIN_NAME_SERVER)
            ])

        ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest()
            .withHostedZoneId(hostedZone.id)
            .withChangeBatch(
                new ChangeBatch()
                    .withChanges([
                        new Change()
                            .withAction(ChangeAction.CREATE)
                            .withResourceRecordSet(resourceRecordSet)
                    ])
            )

        return route53Client.changeResourceRecordSets(request)
    }
}
</code>```

OwnerDisplayName: Larry Montillano Borrero

Body:
I'm currently using Grails 2.4.5 and used AmazonWebService plugin for grails 2.4.5

I'm trying to create a new recordset on route53 using this plugin.

On my BuildConfig.groovy I used this plugin fro aws web services.

compile ":aws-sdk:1.10.44"

I need your help guys regarding route53 change resource record sets.

I got an error below when I tried to change route53 resource record sets.

Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], or TrafficPolicyInstanceId], but found more than one in Change with [Action=CREATE, Name=app.sample.com., Type=A, SetIdentifier=null] (Service: AmazonRoute53; Status Code: 400; Error Code: InvalidInput; Request ID: 2ca80154-78a7-11e9-b5e7-f7bc7c79e5e6). Stacktrace follows:
Message: Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], or TrafficPolicyInstanceId], but found more than one in Change with [Action=CREATE, Name=app.sample.com., Type=A, SetIdentifier=null] (Service: AmazonRoute53; Status Code: 400; Error Code: InvalidInput; Request ID: 2ca80154-78a7-11e9-b5e7-f7bc7c79e5e6)

This is my code.

import com.amazonaws.services.route53.AmazonRoute53Client
import com.amazonaws.services.route53.model.AliasTarget
import com.amazonaws.services.route53.model.Change
import com.amazonaws.services.route53.model.ChangeAction
import com.amazonaws.services.route53.model.ChangeBatch
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsRequest
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsResult
import com.amazonaws.services.route53.model.RRType
import com.amazonaws.services.route53.model.ResourceRecord
import com.amazonaws.services.route53.model.ResourceRecordSet
import grails.plugin.awssdk.AmazonWebService
import grails.transaction.Transactional

@Transactional
class AwsRoute53Service {

    AmazonWebService amazonWebService

    ChangeResourceRecordSetsResult changeRecordSet() {
        AmazonRoute53Client route53Client = amazonWebService.route53

        AliasTarget target = new AliasTarget('hostedZoneIDHere', 'app.sample.com.')

        target.setEvaluateTargetHealth(true)

        List<ResourceRecord> resourceRecords = new ArrayList<>()

        resourceRecords.add(new ResourceRecord('dNSNameHere'))

        ResourceRecordSet recordSet = new ResourceRecordSet('app.sample.com.', RRType.A)

        recordSet.setAliasTarget(target)
        recordSet.setResourceRecords(resourceRecords)
        recordSet.setTrafficPolicyInstanceId('simple')

        List<Change> changes = new ArrayList<>()

        changes.add(new Change(ChangeAction.CREATE, recordSet))

        ChangeBatch changeBatch = new ChangeBatch(changes)

        ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest('hostedZoneIDHere', changeBatch)

        return route53Client.changeResourceRecordSets(request)
    }
}

Can you tell me what is the problem with the setup?

I would be glad if you can help me with my problem right now.
Thank you guys.

Body:
I already solve this problem. below is the working code.

import com.amazonaws.services.route53.AmazonRoute53Client
import com.amazonaws.services.route53.model.AliasTarget
import com.amazonaws.services.route53.model.Change
import com.amazonaws.services.route53.model.ChangeAction
import com.amazonaws.services.route53.model.ChangeBatch
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsRequest
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsResult
import com.amazonaws.services.route53.model.RRType
import com.amazonaws.services.route53.model.ResourceRecord
import com.amazonaws.services.route53.model.ResourceRecordSet
import grails.plugin.awssdk.AmazonWebService
import grails.transaction.Transactional

@Transactional
class AwsRoute53Service {

    private static final String DOMAIN_NAME_SERVER = "${System.env.DOMAIN_NAME_SERVER}"
    private static final String HOSTED_ZONE_ID = "${System.env.HOSTED_ZONE_ID}"

    AmazonWebService amazonWebService

    ChangeResourceRecordSetsResult changeRecordSet() {
        AmazonRoute53Client route53Client = amazonWebService.route53

        GetHostedZoneResult hostedZoneResult = route53Client.getHostedZone(new GetHostedZoneRequest(HOSTED_ZONE_ID))
        HostedZone hostedZone = hostedZoneResult.getHostedZone()

        ResourceRecordSet resourceRecordSet = new ResourceRecordSet()
            .withName('dNSName')
            .withType(RRType.CNAME)
            .withTTL(60)
            .withResourceRecords([
                new ResourceRecord().withValue(DOMAIN_NAME_SERVER)
            ])

        ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest()
            .withHostedZoneId(hostedZone.id)
            .withChangeBatch(
                new ChangeBatch()
                    .withChanges([
                        new Change()
                            .withAction(ChangeAction.CREATE)
                            .withResourceRecordSet(resourceRecordSet)
                    ])
            )

        return route53Client.changeResourceRecordSets(request)
    }
}


问:
Kivy App (from buldozer) not displaying root screen
Trying to build a very simple Android App using:

Buildozer v 0.39

Python v3.7.1 or v2.7.15 (same problem for either)

Kivy v1.11.0.dev0

PythonForAndroid (Master as of May 26, 2019)

Cython v0.29.7

Ubuntu 18.04

Python code:

```<code>from kivy.app import App
from kivy.uix.button import Button
import logging

class StartUpBugApp(App):
    __version__ = '1.00'  # for buildozer

    def build(self):
        self.logger = logging.getLogger(__name__)
        return Button(text='button')

    def on_start(self):
        self.logger.critical('In on_start')
        print('In on_start', flush=True)

    def on_stop(self):
        self.logger.critical('In on_stop')
        print('In on_stop', flush=True)

    def on_pause(self):
        self.logger.critical('In on_pause')
        print('In on_pause', flush=True)
        return True

    def on_resume(self):
        self.logger.critical('In on_resume')
        print('In on_resume', flush=True)

if __name__ == '__main__':
    StartUpBugApp().run()
</code>```

buildozer.spec:

```<code>[app]

# (str) Title of your application
title = "StartupBug"

# (str) Package name
package.name = startupbug

# (str) Package domain (needed for android/ios packaging)
package.domain = org.jra

# (str) Source code where the main.py live
source.dir = /home/jra/PycharmProjects/StartUpBug

# (list) Source files to include (let empty to include all the files)
source.include_exts = py

# (list) List of inclusions using pattern matching
#source.include_patterns = assets/*,images/*.png

# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = spec
source.exclude_exts = spec, p4a, txt, csh, cvsignore, sh, exe, log, basis, tar, bak, directory

# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = tests, bin

# (list) List of exclusions using pattern matching
#source.exclude_patterns = license,images/*/*.jpg

# (str) Application versioning (method 1)
version = 1.00

# (str) Application versioning (method 2)
# version.regex = __version__ = ['"](.*)['"]
# version.filename = %(source.dir)s/main.py

# (list) Application requirements
# comma seperated e.g. requirements = sqlite3,kivy
requirements = python3, kivy

# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# requirements.source.kivy = ../../kivy

# (list) Garden requirements
#garden_requirements =
#garden_requirements = filebrowser

# (str) Presplash of the application
#presplash.filename = %(source.dir)s/data/presplash.png

# (str) Icon of the application
#icon.filename = %(source.dir)s/data/icon.png
#icon.filename = %(source.dir)s/resources/hearts48.png

# (str) Supported orientation (one of landscape, portrait or all)
orientation = landscape

# (list) List of service to declare
#services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY

#
# OSX Specific
#

#
# author = © Copyright Info

# change the major version of python used by the app
osx.python_version = 2

# Kivy version to use
osx.kivy_version = 1.9.1

#
# Android specific
#

# (bool) Indicate if the application should be fullscreen or not
fullscreen = 1

# (string) Presplash background color (for new android toolchain)
# Supported formats are: #RRGGBB #AARRGGBB or one of the following names:
# red, blue, green, black, white, gray, cyan, magenta, yellow, lightgray,
# darkgray, grey, lightgrey, darkgrey, aqua, fuchsia, lime, maroon, navy,
# olive, purple, silver, teal.
#android.presplash_color = #FFFFFF

# (list) Permissions
#android.permissions = INTERNET

# (int) Android API to use
# Samsung Galaxy Tab: Android 8.1.0, API 27
android.api = 27

# (int) Minimum API required
android.minapi = 24

# (int) Android SDK version to use
#android.sdk = 20

# (str) Android NDK version to use
#android.ndk = 9c

# (bool) Use --private data storage (True) or --dir public storage (False)
#android.private_storage = True

# (str) Android NDK directory (if empty, it will be automatically downloaded.)
#android.ndk_path = /home/jra/Android/android-ndk-r9c

# (str) Android SDK directory (if empty, it will be automatically downloaded.)
#android.sdk_path = /home/jra/Android/Sdk

# (str) ANT directory (if empty, it will be automatically downloaded.)
#android.ant_path =

# (bool) If True, then skip trying to update the Android sdk
# This can be useful to avoid excess Internet downloads or save time
# when an update is due and you just want to test/build your package
# android.skip_update = False

# (str) Android entry point, default is ok for Kivy-based app
#android.entrypoint = org.renpy.android.PythonActivity

# (list) Pattern to whitelist for the whole project
#android.whitelist =

# (str) Path to a custom whitelist file
#android.whitelist_src =

# (str) Path to a custom blacklist file
#android.blacklist_src =

# (list) List of Java .jar files to add to the libs so that pyjnius can access
# their classes. Don't add jars that you do not need, since extra jars can slow
# down the build process. Allows wildcards matching, for example:
# OUYA-ODK/libs/*.jar
#android.add_jars = foo.jar,bar.jar,path/to/more/*.jar

# (list) List of Java files to add to the android project (can be java or a
# directory containing the files)
#android.add_src =

# (list) Android AAR archives to add (currently works only with sdl2_gradle
# bootstrap)
#android.add_aars =

# (list) Gradle dependencies to add (currently works only with sdl2_gradle
# bootstrap)
# android.gradle_dependencies = 'com.android.support:appcompat-v7:26.1.0'

# (str) python-for-android branch to use, defaults to master
#p4a.branch = stable

# (str) OUYA Console category. Should be one of GAME or APP
# If you leave this blank, OUYA support will not be enabled
#android.ouya.category = GAME

# (str) Filename of OUYA Console icon. It must be a 732x412 png image.
#android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png

# (str) XML file to include as an intent filters in <activity> tag
#android.manifest.intent_filters =

# (str) launchMode to set for the main activity
#android.manifest.launch_mode = singleInstance

# (list) Android additionnal libraries to copy into libs/armeabi
#android.add_libs_armeabi = libs/android/*.so
#android.add_libs_armeabi_v7a = libs/android-v7/*.so
#android.add_libs_x86 = libs/android-x86/*.so
#android.add_libs_mips = libs/android-mips/*.so

# (bool) Indicate whether the screen should stay on
# Don't forget to add the WAKE_LOCK permission if you set this to True
android.wakelock = True

# (list) Android application meta-data to set (key=value format)
#android.meta_data =

# (list) Android library project to add (will be added in the
# project.properties automatically.)
#android.library_references =

# (str) Android logcat filters to use
#android.logcat_filters = *:S python:D

# (bool) Copy library instead of making a libpymodules.so
#android.copy_libs = 1

# (str) The Android arch to build for, choices: armeabi-v7a, arm64-v8a, x86
# Samsung Galaxy arch: armeabi-v7a, armeabi
android.arch = armeabi-v7a
#android.arch = x86

#
# Python for android (p4a) specific
#

# (str) python-for-android git clone directory (if empty, it will be automatically cloned from github)
p4a.source_dir = /home/jra/Downloads/Python4android_may_26_2019/python-for-android-master

# (str) The directory in which python-for-android should look for your own build recipes (if any)
#p4a.local_recipes =

# (str) Filename to the hook for p4a
#p4a.hook =

# (str) Bootstrap to use for android builds
# p4a.bootstrap = sdl2

#
# iOS specific
#

# (str) Path to a custom kivy-ios folder
#ios.kivy_ios_dir = ../kivy-ios

# (str) Name of the certificate to use for signing the debug version
# Get a list of available identities: buildozer ios list_identities
#ios.codesign.debug = "iPhone Developer: <lastname> <firstname> (<hexstring>)"

# (str) Name of the certificate to use for signing the release version
#ios.codesign.release = %(ios.codesign.debug)s

[buildozer]

# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output))
log_level = 2

# (int) Display warning if buildozer is run as root (0 = False, 1 = True)
warn_on_root = 1

# (str) Path to build artifact storage, absolute or relative to spec file
# build_dir = /build/hearts

# (str) Path to build output (i.e. .apk, .ipa) storage
# bin_dir = ./bin

#    -----------------------------------------------------------------------------
#    List as sections
#
#    You can define all the "list" as [section:key].
#    Each line will be considered as a option to the list.
#    Let's take [app] / source.exclude_patterns.
#    Instead of doing:
#
#[app]
#source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
#    This can be translated into:
#
#[app:source.exclude_patterns]
#license
#data/audio/*.wav
#data/images/original/*
#

#    -----------------------------------------------------------------------------
#    Profiles
#
#    You can extend section / key with a profile
#    For example, you want to deploy a demo version of your application without
#    HD content. You could first change the title to add "(demo)" in the name
#    and extend the excluded directories to remove the HD content.
#
#[app@demo]
#title = My Application (demo)
#
#[app:source.exclude_patterns@demo]
#images/hd/*
#
#    Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug
</code>```

I had to modify _android.pyx in the p4a master as described in this question: Kivy application does not work on Android in order to avoid the old bug about JAVA_NAMESPACE (bytes vs string). Replaced

```<code>python_act = autoclass(JAVA_NAMESPACE + u'.PythonActivity')
</code>```

with:

```<code>python_act = autoclass("org/kivy/android/PythonActivity")
</code>```

But now the app starts and does not display the Button. Here is some log output from logcat:

```<code>2019-05-26 14:51:59.695 30549-30899/org.jra.startupbug I/python:  In on_start
2019-05-26 14:51:59.695 30549-30899/org.jra.startupbug I/python: In on_start
2019-05-26 14:51:59.696 30549-30899/org.jra.startupbug I/python: [WARNING] [Base        ] Unknown <android> provider
2019-05-26 14:51:59.697 30549-30899/org.jra.startupbug I/python: [INFO   ] [Base        ] Start application main loop
2019-05-26 14:51:59.702 4090-4905/? V/WindowManager: Relayout Window{a2ee1a1 u0 org.jra.startupbug/org.kivy.android.PythonActivity}: viewVisibility=0 req=1920x1200 WM.LayoutParams{(0,0)(fillxfill) sim=#20 ty=1 fl=#1810500 pfl=0x20000 fmt=-3 wanim=0x1030001 vsysui=0x1706 sysuil=true needsMenuKey=2 colorMode=0 naviIconColor=0}
2019-05-26 14:51:59.704 30549-30899/org.jra.startupbug I/python: [INFO   ] [GL          ] NPOT texture support is available
2019-05-26 14:51:59.714 30549-30549/org.jra.startupbug D/ViewRootImpl@813b3af[PythonActivity]: Relayout returned: old=[0,0][1920,1200] new=[0,0][1920,1200] result=0x1 surface={valid=true 3357532160} changed=false
2019-05-26 14:51:59.730 2603-2603/? D/SurfaceFlinger:   Display[0] configurations (* current):
        * 0: 1200x1920, xdpi=225.776993, ydpi=225.776993, refresh=16666666
      numHwLayers=2, flags=00000000
        type   |  handle  | hint | flag | tr | blnd |   format    |     source crop (l,t,r,b)      |          frame         | name
    -----------+----------+------+------+----+------+-------------+--------------------------------+------------------------+------
          GLES | 00000000 | 0000 | 0220 | 04 | 0105 | ? ffffffff  |    0.0,    0.0,   -1.0,   -1.0 |    0,    0, 1200, 1920 | Background for - SurfaceView - org.jra.startupbug/org.kivy.android.PythonActivity@ec3983e@0[30549]#0
     FB TARGET | f5683600 | 0000 | 0000 | 00 | 0105 | RGBA_8888   |    0.0,    0.0, 1200.0, 1920.0 |    0,    0, 1200, 1920 | HWC_FRAMEBUFFER_TARGET
2019-05-26 14:51:59.761 2603-2603/? E/SurfaceFlinger: [SurfaceView - org.jra.startupbug/org.kivy.android.PythonActivity@ec3983e@0[30549]#0] rejecting buffer: bufWidth=1920, bufHeight=1164, front.active.{w=1920, h=1200}
</code>```

If I minimize the app, then enlarge it, I see the expected on_pause and on_resume, and then the app displays correctly. Any ideas/suggestions about how to get the app to disply correctly without having to minimize/maximize?

答:
I found an ugly hack that solved the problem. I just use ScreenManager, and create a dummy Screen that is of no actual use. I set the dummy Screen as the initial Screen, and use Clock.schedule_once() to switch to the real main screen. Seems to work fine (except for the SlideTransition effect). I suspect that I could use kivy.uix.screenmanager.NoTransition to minimize any transition effect.

Here is the modified code:

```<code>from kivy.app import App
from kivy.clock import Clock
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition

class StartUpBugApp(App):
    __version__ = '1.00'  # for buildozer

    def build(self):
        self.sm = ScreenManager(transition=NoTransition())

        # dummy screen (not actually used)
        screen1 = Screen(name='screen1')
        screen1.add_widget(Button(text='button1', on_release=self.switchToScreen2))
        self.sm.add_widget(screen1)

        # actual desired initial Screen
        screen2 = Screen(name='screen2')
        screen2.add_widget(Button(text='button2', on_release=self.switchToScreen1))
        self.sm.add_widget(screen2)

        # schedule changing to desired initial `Screen`
        Clock.schedule_once(self.switchToScreen2)
        return self.sm

    def switchToScreen2(self, *args):
        self.sm.current = 'screen2'

    def switchToScreen1(self, *args):
        self.sm.current = 'screen1'

    def on_start(self):
        print('In on_start')

    def on_stop(self):
        print('In on_stop')

    def on_pause(self):
        print('In on_pause')
        return True

    def on_resume(self):
        print('In on_resume')

if __name__ == '__main__':
    StartUpBugApp().run()
</code>```

Body:
Trying to build a very simple Android App using:

Buildozer v 0.39

Python v3.7.1 or v2.7.15 (same problem for either)

Kivy v1.11.0.dev0

PythonForAndroid (Master as of May 26, 2019)

Cython v0.29.7

Ubuntu 18.04

Python code:

from kivy.app import App
from kivy.uix.button import Button
import logging

class StartUpBugApp(App):
    __version__ = '1.00'  # for buildozer

    def build(self):
        self.logger = logging.getLogger(__name__)
        return Button(text='button')

    def on_start(self):
        self.logger.critical('In on_start')
        print('In on_start', flush=True)

    def on_stop(self):
        self.logger.critical('In on_stop')
        print('In on_stop', flush=True)

    def on_pause(self):
        self.logger.critical('In on_pause')
        print('In on_pause', flush=True)
        return True

    def on_resume(self):
        self.logger.critical('In on_resume')
        print('In on_resume', flush=True)

if __name__ == '__main__':
    StartUpBugApp().run()

buildozer.spec:

[app]

# (str) Title of your application
title = "StartupBug"

# (str) Package name
package.name = startupbug

# (str) Package domain (needed for android/ios packaging)
package.domain = org.jra

# (str) Source code where the main.py live
source.dir = /home/jra/PycharmProjects/StartUpBug

# (list) Source files to include (let empty to include all the files)
source.include_exts = py

# (list) List of inclusions using pattern matching
#source.include_patterns = assets/*,images/*.png

# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = spec
source.exclude_exts = spec, p4a, txt, csh, cvsignore, sh, exe, log, basis, tar, bak, directory

# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = tests, bin

# (list) List of exclusions using pattern matching
#source.exclude_patterns = license,images/*/*.jpg

# (str) Application versioning (method 1)
version = 1.00

# (str) Application versioning (method 2)
# version.regex = __version__ = ['"](.*)['"]
# version.filename = %(source.dir)s/main.py

# (list) Application requirements
# comma seperated e.g. requirements = sqlite3,kivy
requirements = python3, kivy

# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# requirements.source.kivy = ../../kivy

# (list) Garden requirements
#garden_requirements =
#garden_requirements = filebrowser

# (str) Presplash of the application
#presplash.filename = %(source.dir)s/data/presplash.png

# (str) Icon of the application
#icon.filename = %(source.dir)s/data/icon.png
#icon.filename = %(source.dir)s/resources/hearts48.png

# (str) Supported orientation (one of landscape, portrait or all)
orientation = landscape

# (list) List of service to declare
#services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY

#
# OSX Specific
#

#
# author = © Copyright Info

# change the major version of python used by the app
osx.python_version = 2

# Kivy version to use
osx.kivy_version = 1.9.1

#
# Android specific
#

# (bool) Indicate if the application should be fullscreen or not
fullscreen = 1

# (string) Presplash background color (for new android toolchain)
# Supported formats are: #RRGGBB #AARRGGBB or one of the following names:
# red, blue, green, black, white, gray, cyan, magenta, yellow, lightgray,
# darkgray, grey, lightgrey, darkgrey, aqua, fuchsia, lime, maroon, navy,
# olive, purple, silver, teal.
#android.presplash_color = #FFFFFF

# (list) Permissions
#android.permissions = INTERNET

# (int) Android API to use
# Samsung Galaxy Tab: Android 8.1.0, API 27
android.api = 27

# (int) Minimum API required
android.minapi = 24

# (int) Android SDK version to use
#android.sdk = 20

# (str) Android NDK version to use
#android.ndk = 9c

# (bool) Use --private data storage (True) or --dir public storage (False)
#android.private_storage = True

# (str) Android NDK directory (if empty, it will be automatically downloaded.)
#android.ndk_path = /home/jra/Android/android-ndk-r9c

# (str) Android SDK directory (if empty, it will be automatically downloaded.)
#android.sdk_path = /home/jra/Android/Sdk

# (str) ANT directory (if empty, it will be automatically downloaded.)
#android.ant_path =

# (bool) If True, then skip trying to update the Android sdk
# This can be useful to avoid excess Internet downloads or save time
# when an update is due and you just want to test/build your package
# android.skip_update = False

# (str) Android entry point, default is ok for Kivy-based app
#android.entrypoint = org.renpy.android.PythonActivity

# (list) Pattern to whitelist for the whole project
#android.whitelist =

# (str) Path to a custom whitelist file
#android.whitelist_src =

# (str) Path to a custom blacklist file
#android.blacklist_src =

# (list) List of Java .jar files to add to the libs so that pyjnius can access
# their classes. Don't add jars that you do not need, since extra jars can slow
# down the build process. Allows wildcards matching, for example:
# OUYA-ODK/libs/*.jar
#android.add_jars = foo.jar,bar.jar,path/to/more/*.jar

# (list) List of Java files to add to the android project (can be java or a
# directory containing the files)
#android.add_src =

# (list) Android AAR archives to add (currently works only with sdl2_gradle
# bootstrap)
#android.add_aars =

# (list) Gradle dependencies to add (currently works only with sdl2_gradle
# bootstrap)
# android.gradle_dependencies = 'com.android.support:appcompat-v7:26.1.0'

# (str) python-for-android branch to use, defaults to master
#p4a.branch = stable

# (str) OUYA Console category. Should be one of GAME or APP
# If you leave this blank, OUYA support will not be enabled
#android.ouya.category = GAME

# (str) Filename of OUYA Console icon. It must be a 732x412 png image.
#android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png

# (str) XML file to include as an intent filters in <activity> tag
#android.manifest.intent_filters =

# (str) launchMode to set for the main activity
#android.manifest.launch_mode = singleInstance

# (list) Android additionnal libraries to copy into libs/armeabi
#android.add_libs_armeabi = libs/android/*.so
#android.add_libs_armeabi_v7a = libs/android-v7/*.so
#android.add_libs_x86 = libs/android-x86/*.so
#android.add_libs_mips = libs/android-mips/*.so

# (bool) Indicate whether the screen should stay on
# Don't forget to add the WAKE_LOCK permission if you set this to True
android.wakelock = True

# (list) Android application meta-data to set (key=value format)
#android.meta_data =

# (list) Android library project to add (will be added in the
# project.properties automatically.)
#android.library_references =

# (str) Android logcat filters to use
#android.logcat_filters = *:S python:D

# (bool) Copy library instead of making a libpymodules.so
#android.copy_libs = 1

# (str) The Android arch to build for, choices: armeabi-v7a, arm64-v8a, x86
# Samsung Galaxy arch: armeabi-v7a, armeabi
android.arch = armeabi-v7a
#android.arch = x86

#
# Python for android (p4a) specific
#

# (str) python-for-android git clone directory (if empty, it will be automatically cloned from github)
p4a.source_dir = /home/jra/Downloads/Python4android_may_26_2019/python-for-android-master

# (str) The directory in which python-for-android should look for your own build recipes (if any)
#p4a.local_recipes =

# (str) Filename to the hook for p4a
#p4a.hook =

# (str) Bootstrap to use for android builds
# p4a.bootstrap = sdl2

#
# iOS specific
#

# (str) Path to a custom kivy-ios folder
#ios.kivy_ios_dir = ../kivy-ios

# (str) Name of the certificate to use for signing the debug version
# Get a list of available identities: buildozer ios list_identities
#ios.codesign.debug = "iPhone Developer: <lastname> <firstname> (<hexstring>)"

# (str) Name of the certificate to use for signing the release version
#ios.codesign.release = %(ios.codesign.debug)s

[buildozer]

# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output))
log_level = 2

# (int) Display warning if buildozer is run as root (0 = False, 1 = True)
warn_on_root = 1

# (str) Path to build artifact storage, absolute or relative to spec file
# build_dir = /build/hearts

# (str) Path to build output (i.e. .apk, .ipa) storage
# bin_dir = ./bin

#    -----------------------------------------------------------------------------
#    List as sections
#
#    You can define all the "list" as [section:key].
#    Each line will be considered as a option to the list.
#    Let's take [app] / source.exclude_patterns.
#    Instead of doing:
#
#[app]
#source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
#    This can be translated into:
#
#[app:source.exclude_patterns]
#license
#data/audio/*.wav
#data/images/original/*
#

#    -----------------------------------------------------------------------------
#    Profiles
#
#    You can extend section / key with a profile
#    For example, you want to deploy a demo version of your application without
#    HD content. You could first change the title to add "(demo)" in the name
#    and extend the excluded directories to remove the HD content.
#
#[app@demo]
#title = My Application (demo)
#
#[app:source.exclude_patterns@demo]
#images/hd/*
#
#    Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug

I had to modify _android.pyx in the p4a master as described in this question: Kivy application does not work on Android in order to avoid the old bug about JAVA_NAMESPACE (bytes vs string). Replaced

python_act = autoclass(JAVA_NAMESPACE + u'.PythonActivity')

with:

python_act = autoclass("org/kivy/android/PythonActivity")

But now the app starts and does not display the Button. Here is some log output from logcat:

2019-05-26 14:51:59.695 30549-30899/org.jra.startupbug I/python:  In on_start
2019-05-26 14:51:59.695 30549-30899/org.jra.startupbug I/python: In on_start
2019-05-26 14:51:59.696 30549-30899/org.jra.startupbug I/python: [WARNING] [Base        ] Unknown <android> provider
2019-05-26 14:51:59.697 30549-30899/org.jra.startupbug I/python: [INFO   ] [Base        ] Start application main loop
2019-05-26 14:51:59.702 4090-4905/? V/WindowManager: Relayout Window{a2ee1a1 u0 org.jra.startupbug/org.kivy.android.PythonActivity}: viewVisibility=0 req=1920x1200 WM.LayoutParams{(0,0)(fillxfill) sim=#20 ty=1 fl=#1810500 pfl=0x20000 fmt=-3 wanim=0x1030001 vsysui=0x1706 sysuil=true needsMenuKey=2 colorMode=0 naviIconColor=0}
2019-05-26 14:51:59.704 30549-30899/org.jra.startupbug I/python: [INFO   ] [GL          ] NPOT texture support is available
2019-05-26 14:51:59.714 30549-30549/org.jra.startupbug D/ViewRootImpl@813b3af[PythonActivity]: Relayout returned: old=[0,0][1920,1200] new=[0,0][1920,1200] result=0x1 surface={valid=true 3357532160} changed=false
2019-05-26 14:51:59.730 2603-2603/? D/SurfaceFlinger:   Display[0] configurations (* current):
        * 0: 1200x1920, xdpi=225.776993, ydpi=225.776993, refresh=16666666
      numHwLayers=2, flags=00000000
        type   |  handle  | hint | flag | tr | blnd |   format    |     source crop (l,t,r,b)      |          frame         | name
    -----------+----------+------+------+----+------+-------------+--------------------------------+------------------------+------
          GLES | 00000000 | 0000 | 0220 | 04 | 0105 | ? ffffffff  |    0.0,    0.0,   -1.0,   -1.0 |    0,    0, 1200, 1920 | Background for - SurfaceView - org.jra.startupbug/org.kivy.android.PythonActivity@ec3983e@0[30549]#0
     FB TARGET | f5683600 | 0000 | 0000 | 00 | 0105 | RGBA_8888   |    0.0,    0.0, 1200.0, 1920.0 |    0,    0, 1200, 1920 | HWC_FRAMEBUFFER_TARGET
2019-05-26 14:51:59.761 2603-2603/? E/SurfaceFlinger: [SurfaceView - org.jra.startupbug/org.kivy.android.PythonActivity@ec3983e@0[30549]#0] rejecting buffer: bufWidth=1920, bufHeight=1164, front.active.{w=1920, h=1200}

If I minimize the app, then enlarge it, I see the expected on_pause and on_resume, and then the app displays correctly. Any ideas/suggestions about how to get the app to disply correctly without having to minimize/maximize?

Body:
I found an ugly hack that solved the problem. I just use ScreenManager, and create a dummy Screen that is of no actual use. I set the dummy Screen as the initial Screen, and use Clock.schedule_once() to switch to the real main screen. Seems to work fine (except for the SlideTransition effect). I suspect that I could use kivy.uix.screenmanager.NoTransition to minimize any transition effect.

Here is the modified code:

from kivy.app import App
from kivy.clock import Clock
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition

class StartUpBugApp(App):
    __version__ = '1.00'  # for buildozer

    def build(self):
        self.sm = ScreenManager(transition=NoTransition())

        # dummy screen (not actually used)
        screen1 = Screen(name='screen1')
        screen1.add_widget(Button(text='button1', on_release=self.switchToScreen2))
        self.sm.add_widget(screen1)

        # actual desired initial Screen
        screen2 = Screen(name='screen2')
        screen2.add_widget(Button(text='button2', on_release=self.switchToScreen1))
        self.sm.add_widget(screen2)

        # schedule changing to desired initial `Screen`
        Clock.schedule_once(self.switchToScreen2)
        return self.sm

    def switchToScreen2(self, *args):
        self.sm.current = 'screen2'

    def switchToScreen1(self, *args):
        self.sm.current = 'screen1'

    def on_start(self):
        print('In on_start')

    def on_stop(self):
        print('In on_stop')

    def on_pause(self):
        print('In on_pause')
        return True

    def on_resume(self):
        print('In on_resume')

if __name__ == '__main__':
    StartUpBugApp().run()


问:
How to collect objects in row using vuetify data iterator?
I try to add Data iterator to my Vue app. When I create a CodePen example it works properly, but when I use it on my page I have all the items collectes in column, not side by side like in example. Anyone has any ideas what I did wrong?

```<code><template>
<div>
  <v-container fluid grid-list-md>
    <v-data-iterator :items="uploadItems" :pagination.sync="pagination" :rows-per-page-items="[4, 8, 12]" :loading="loading" content-tag="v-layout" row wrap>
      <v-flex slot="item" slot-scope="props" lg2>
        <v-card>
          <v-card-title>
            <h5>{{ props.item.filename }}</h5>
          </v-card-title>
          <v-divider></v-divider>
          <v-list dense>
            <v-list-tile>
              <v-list-tile-content>Status:</v-list-tile-content>
              <v-list-tile-content class="align-end">{{ props.item.status }}</v-list-tile-content>
            </v-list-tile>
            <v-list-tile>
              <h4 style="color: red;">{{ props.item.logs.IMPORTER.VERSION.MSG }}</h4>
            </v-list-tile>
            <v-list-tile>
              <h4>VALIDATOR</h4>
            </v-list-tile>
            <v-list-tile v-for="(value, key) in props.item.logs.VALIDATOR">
              <v-list-tile-content>{{ key }}:</v-list-tile-content>
              <v-list-tile-content class="align-end">{{ value }}</v-list-tile-content>
            </v-list-tile>
            <v-list-tile>
              <h4>LOGS</h4>
            </v-list-tile>
            <v-list-tile>
              <v-list-tile-content>Chnaged:</v-list-tile-content>
              <v-list-tile-content class="align-end">{{ props.item.logs.IMPORTER.CHANGED }}</v-list-tile-content>
            </v-list-tile>
            <v-list-tile>
              <v-list-tile-content>Conflicts:</v-list-tile-content>
              <v-list-tile-content class="align-end">{{ props.item.logs.IMPORTER.CONFLICTS }}</v-list-tile-content>
            </v-list-tile>
            <v-list-tile>
              <v-list-tile-content>Correct version:</v-list-tile-content>
              <v-list-tile-content class="align-end">{{ props.item.logs.IMPORTER.VERSION.CORRECT_VERSION }}</v-list-tile-content>
            </v-list-tile>
          </v-list>
        </v-card>
      </v-flex>
    </v-data-iterator>
  </v-container>
</div>
</template>
</code>```

I thought it could be older version of Vue or Vuetify, but I have the same as on CodePen (Vue.js v2.5.17 and Vuetify v1.3.11). I even try to crerate a new Vue project and copy example to App.vue, but the elements are still in the column, but not in the row.

答:
I don't know why this is necessary, but I managed to get around this by adding the d-inline-flex class, as seen below:

```<code>    <v-data-iterator
      :items="products"
      content-tag="v-layout"
      content-class="d-inline-flex"
</code>```

Body:
I try to add Data iterator to my Vue app. When I create a CodePen example it works properly, but when I use it on my page I have all the items collectes in column, not side by side like in example. Anyone has any ideas what I did wrong?

<template>

  <v-container fluid grid-list-md>
    <v-data-iterator :items="uploadItems" :pagination.sync="pagination" :rows-per-page-items="[4, 8, 12]" :loading="loading" content-tag="v-layout" row wrap>
      <v-flex slot="item" slot-scope="props" lg2>
        <v-card>
          <v-card-title>

{{ props.item.filename }}

          </v-card-title>
          <v-divider></v-divider>
          <v-list dense>
            <v-list-tile>
              <v-list-tile-content>Status:</v-list-tile-content>
              <v-list-tile-content class="align-end">{{ props.item.status }}</v-list-tile-content>
            </v-list-tile>
            <v-list-tile>

{{ props.item.logs.IMPORTER.VERSION.MSG }}

            </v-list-tile>
            <v-list-tile>

VALIDATOR

            </v-list-tile>
            <v-list-tile v-for="(value, key) in props.item.logs.VALIDATOR">
              <v-list-tile-content>{{ key }}:</v-list-tile-content>
              <v-list-tile-content class="align-end">{{ value }}</v-list-tile-content>
            </v-list-tile>
            <v-list-tile>

LOGS

            </v-list-tile>
            <v-list-tile>
              <v-list-tile-content>Chnaged:</v-list-tile-content>
              <v-list-tile-content class="align-end">{{ props.item.logs.IMPORTER.CHANGED }}</v-list-tile-content>
            </v-list-tile>
            <v-list-tile>
              <v-list-tile-content>Conflicts:</v-list-tile-content>
              <v-list-tile-content class="align-end">{{ props.item.logs.IMPORTER.CONFLICTS }}</v-list-tile-content>
            </v-list-tile>
            <v-list-tile>
              <v-list-tile-content>Correct version:</v-list-tile-content>
              <v-list-tile-content class="align-end">{{ props.item.logs.IMPORTER.VERSION.CORRECT_VERSION }}</v-list-tile-content>
            </v-list-tile>
          </v-list>
        </v-card>
      </v-flex>
    </v-data-iterator>
  </v-container>

</template>

I thought it could be older version of Vue or Vuetify, but I have the same as on CodePen (Vue.js v2.5.17 and Vuetify v1.3.11). I even try to crerate a new Vue project and copy example to App.vue, but the elements are still in the column, but not in the row.

Body:
I don't know why this is necessary, but I managed to get around this by adding the d-inline-flex class, as seen below:

    <v-data-iterator
      :items="products"
      content-tag="v-layout"
      content-class="d-inline-flex"


问:
Angular 5 custom pipe
I am new to Angular and facing this issue.

I want to create a custom pipe for convert decimal codes into the base64 image then displaying them in views. I have complete code for this issue but don't know how to use it for the custom pipe.

This is my code:

my-component.ts

```<code>this.imgIn = "";
var chars1 = dataParkir.pictstart.data; // array of decimal codes
for (var k = 0; k < chars1.length; k++) {
  var convert = String.fromCharCode(chars1[k]); // convert into base64
  this.imgIn = this.imgIn + convert;
}

this.base64ImageIn = this.sanitizer.bypassSecurityTrustResourceUrl('data:image/png;base64,' + this.imgIn);
</code>```

Has anyone else experienced this, please help me?

答: I highly suggest you to take a look at the docs, it's really easy to understand and gives you a good amount of information that you might need to create your custom pipe, Here's the link to the official docs: Angular - Pipes</p>

Title: Angular 5 custom pipe

Body:
I am new to Angular and facing this issue.

I want to create a custom pipe for convert decimal codes into the base64 image then displaying them in views. I have complete code for this issue but don't know how to use it for the custom pipe.

This is my code:

my-component.ts

this.imgIn = "";
var chars1 = dataParkir.pictstart.data; // array of decimal codes
for (var k = 0; k < chars1.length; k++) {
  var convert = String.fromCharCode(chars1[k]); // convert into base64
  this.imgIn = this.imgIn + convert;
}

this.base64ImageIn = this.sanitizer.bypassSecurityTrustResourceUrl('data:image/png;base64,' + this.imgIn);

Has anyone else experienced this, please help me?


问:
Trying to add Discord alerts/hooks to an existing python code
So i want to monitor a webpage, and if a change occurs, i would like to be notified of that via Discord.

Searching google, i landed on this page https://www.adventuresintechland.com/detect-when-a-webpage-changes-with-python/

and it seems to work when i test it on my website.
But i would like to add Discord alerts to this code but seem to be stuck

i have looked into Dhooks on github and have been stuck trying to implement it

```<code># Hunter Thornsberry
# http://www.adventuresintechland.com

# WebChange.py
# Alerts you when a webpage has changed it's content by comparing checksums of the html.

import hashlib
import urllib2
import random
import time

# url to be scraped
url = "http://raw.adventuresintechland.com/freedom.html"

# time between checks in seconds
sleeptime = 60

def getHash():
    # random integer to select user agent
    randomint = random.randint(0,7)

    # User_Agents
    # This helps skirt a bit around servers that detect repeaded requests from the same machine.
    # This will not prevent your IP from getting banned but will help a bit by pretending to be different browsers
    # and operating systems.
    user_agents = [
        'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
        'Opera/9.25 (Windows NT 5.1; U; en)',
        'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
        'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
        'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.142 Safari/535.19',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:8.0.1) Gecko/20100101 Firefox/8.0.1',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.151 Safari/535.19'
    ]

    opener = urllib2.build_opener()
    opener.addheaders = [('User-agent', user_agents[randomint])]
    response = opener.open(url)
    the_page = response.read()

    return hashlib.sha224(the_page).hexdigest()

current_hash = getHash() # Get the current hash, which is what the website is now

while 1: # Run forever
    if getHash() == current_hash: # If nothing has changed
        print "Not Changed"
    else: # If something has changed
        print "Changed"
        break
    time.sleep(sleeptime)
</code>```

答:
You will need to use the discord API connection: with python, use discord.py.

Have a look at the discord.py docs and learn how to use it, then connect the two - just add the required discord.py imports and setup to the file in the appropriate places and add a prompt to send a message whenever the webpage changes (in this case, replacing the print("changed") with yourChannel.send("webpage has changed!)".

Body:
So i want to monitor a webpage, and if a change occurs, i would like to be notified of that via Discord.

Searching google, i landed on this page https://www.adventuresintechland.com/detect-when-a-webpage-changes-with-python/

and it seems to work when i test it on my website.
But i would like to add Discord alerts to this code but seem to be stuck

i have looked into Dhooks on github and have been stuck trying to implement it

# Hunter Thornsberry
# http://www.adventuresintechland.com

# WebChange.py
# Alerts you when a webpage has changed it's content by comparing checksums of the html.

import hashlib
import urllib2
import random
import time

# url to be scraped
url = "http://raw.adventuresintechland.com/freedom.html"

# time between checks in seconds
sleeptime = 60

def getHash():
    # random integer to select user agent
    randomint = random.randint(0,7)

    # User_Agents
    # This helps skirt a bit around servers that detect repeaded requests from the same machine.
    # This will not prevent your IP from getting banned but will help a bit by pretending to be different browsers
    # and operating systems.
    user_agents = [
        'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
        'Opera/9.25 (Windows NT 5.1; U; en)',
        'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
        'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
        'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.142 Safari/535.19',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:8.0.1) Gecko/20100101 Firefox/8.0.1',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.151 Safari/535.19'
    ]

    opener = urllib2.build_opener()
    opener.addheaders = [('User-agent', user_agents[randomint])]
    response = opener.open(url)
    the_page = response.read()

    return hashlib.sha224(the_page).hexdigest()

current_hash = getHash() # Get the current hash, which is what the website is now

while 1: # Run forever
    if getHash() == current_hash: # If nothing has changed
        print "Not Changed"
    else: # If something has changed
        print "Changed"
        break
    time.sleep(sleeptime)


问:
Matching Patterns for list of tuples
I'm trying to write a fcn that takes in a list of tuple and an expression (I am working on a postfix expression eval). This function should loop through the expression and find the same letter in the tuple. If it's a match then it returns the int value corresponding to that letter in the tuple. When I ran the code below, my program compiled and run but then it was hanging during execution. What did I do wrong?</p>

```<code>    let rec getVar ls exp =

        match ls with
       |head::tl when (fst head) = exp -> printfn "%d" (snd head)
       | _  -> getVar ls exp

    let ls = [("a",5);("b",2);("c",3)]

    let exp = "ab+"
    getVar ls exp
</code>```

答:
Your match expression has a final catch-all clause (the _ clause) that just calls getVar again with the same parameters. If the when (fst head) = exp condition fails, then code falls through to the catch-all clause, so getVar gets called again with the same parameters, so the first condition will fail, so code falls through to the catch-all clause, so getVar gets called again... It's an infinite loop.

What you probably meant to do was call getVar again on the tail of the list if your when condition failed:

```<code>match ls with
|head::tail when (fst head) = exp -> printfn "%d" (snd head)
|head::tail -> getVar tail exp
</code>```

You also need to think about what you'll do if the list is empty (i.e., you need a match condition that matches against []). I'll leave that one up to you, since there are many things you could want to do with an empty list and it's not obvious which one you'd want.

Title: Matching Patterns for list of tuples

Body:
I'm trying to write a fcn that takes in a list of tuple and an expression (I am working on a postfix expression eval). This function should loop through the expression and find the same letter in the tuple. If it's a match then it returns the int value corresponding to that letter in the tuple. When I ran the code below, my program compiled and run but then it was hanging during execution. What did I do wrong?

    let rec getVar ls exp =

        match ls with
       |head::tl when (fst head) = exp -> printfn "%d" (snd head)
       | _  -> getVar ls exp

    let ls = [("a",5);("b",2);("c",3)]

    let exp = "ab+"
    getVar ls exp

Body:
Your match expression has a final catch-all clause (the _ clause) that just calls getVar again with the same parameters. If the when (fst head) = exp condition fails, then code falls through to the catch-all clause, so getVar gets called again with the same parameters, so the first condition will fail, so code falls through to the catch-all clause, so getVar gets called again... It's an infinite loop.

What you probably meant to do was call getVar again on the tail of the list if your when condition failed:

match ls with
|head::tail when (fst head) = exp -> printfn "%d" (snd head)
|head::tail -> getVar tail exp

You also need to think about what you'll do if the list is empty (i.e., you need a match condition that matches against []). I'll leave that one up to you, since there are many things you could want to do with an empty list and it's not obvious which one you'd want.


答:
```<code><div id="player"></div>
</code>```

```<code>var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        height: '390',
        width: '640',
        videoId: 'M7lc1UVf-VE',
        events: {
            'onReady': onPlayerReady
        }
    });
}

// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
    player.setPlaybackRate(2);
    event.target.playVideo();
}
</code>```

Title: How do I insert a website inside my html web page

Body:
How do I insert a youtube web page into my HTML web page using I frame,
and please I need a code snippet that I can run to see how it looks like.

Body:
<div id="player"></div>

var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        height: '390',
        width: '640',
        videoId: 'M7lc1UVf-VE',
        events: {
            'onReady': onPlayerReady
        }
    });
}

// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
    player.setPlaybackRate(2);
    event.target.playVideo();
}