问:
FlutterError: Unable to load asset
This is the folder structure of my app

```<code>.idea
.vscode
android
build
fonts
 Oxygen-Bold.tff
 Oxygen-Light.tff
 Oxygen-Regular.tff
images
 pizza0.png
 pizza1.png
ios
lib
 ui
  home.dart
 main.dart
test
.gitignore
.metadata
.packages
app_widgets.iml
pubspec.lock
pubspec.yaml
README.md
</code>```

In my pubspec.yaml file, I load the fonts and assets like this

```<code>flutter:

uses-material-design: true

assets:
  - images/pizza0.png
  - images/pizza1.png

fonts:
  - family: Oxygen
    fonts:
      - asset: fonts/Oxygen-Regular.ttf
      - asset: fonts/Oxygen-Bold.ttf
        weight: 700
      - asset: fonts/Oxygen-Light.ttf
        weight: 300
</code>```

I'm not getting any errors for this pubspec.yaml, and running flutter packages get gives an exit code of 0.

In my home.dart I have the following class:

```<code>class PizzaImageWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    AssetImage pizzaAsset = AssetImage('images/pizza0.png');
    Image image = Image(image: pizzaAsset, width: 400, height: 400);
    return Container(
      child: image,
    );
  }
}
</code>```

Which I use elsewhere, in order to show the image (code omitted):

```<code>        ),
        PizzaImageWidget(),
      ],
</code>```

The building gives no errors. Flutter Doctor -v doesn't give any errors, neither does Flutter Analyze -v. The .apk seems to build just fine but when the app opens up on my phone I get the following error in asset_bundle.dart:

Exception has occurred. FlutterError (Unable to load asset:
images/pizza0.png)

The error is thrown by this class in the asset_bundle.dart file:

```<code>/// An [AssetBundle] that loads resources using platform messages.
class PlatformAssetBundle extends CachingAssetBundle {
  @override
  Future<ByteData> load(String key) async {
    final Uint8List encoded = utf8.encoder.convert(Uri(path: Uri.encodeFull(key)).path);
    final ByteData asset =
        await BinaryMessages.send('flutter/assets', encoded.buffer.asByteData());
    if (asset == null)
      throw FlutterError('Unable to load asset: $key');
    return asset;
  }
}
</code>```

This happens both for the pizza0.png file as well as the pizza1.png file. The files are visible in the tree structure, both in Windows Explorer as in VS Code. The font assets load without issue.

This is the output I am getting when running Flutter Run -v:

[+1068 ms] I/flutter ( 6489): ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE
SERVICE ╞════════════════════════════════════════════════════ [   +9
ms] I/flutter ( 6489): The following assertion was thrown resolving an
image codec: [   +2 ms] I/flutter ( 6489): Unable to load asset:
images/pizza0.png [   +2 ms] I/flutter ( 6489): [   +1 ms] I/flutter (
6489): When the exception was thrown, this was the stack: [   +2 ms]
I/flutter ( 6489): #0      PlatformAssetBundle.load
(package:flutter/src/services/asset_bundle.dart:221:7) [   +1 ms]
I/flutter ( 6489):  [   +1 ms] I/flutter (
6489): #1      AssetBundleImageProvider._loadAsync
(package:flutter/src/painting/image_provider.dart:429:44) [   +1 ms]
I/flutter ( 6489):  [   +1 ms] I/flutter (
6489): #2      AssetBundleImageProvider.load
(package:flutter/src/painting/image_provider.dart:414:14) [   +1 ms]
I/flutter ( 6489): #3      ImageProvider.resolve..
(package:flutter/src/painting/image_provider.dart:267:86) [   +4 ms]
I/flutter ( 6489): #4      ImageCache.putIfAbsent
(package:flutter/src/painting/image_cache.dart:143:20) [   +3 ms]
I/flutter ( 6489): #5      ImageProvider.resolve.
(package:flutter/src/painting/image_provider.dart:267:63) [   +3 ms]
I/flutter ( 6489): (elided 8 frames from package dart:async) [   +1
ms] I/flutter ( 6489): [   +1 ms] I/flutter ( 6489): Image provider:
AssetImage(bundle: null, name: "images/pizza0.png") [   +3 ms]
I/flutter ( 6489): Image key: AssetBundleImageKey(bundle:
PlatformAssetBundle#20fc8(), name: "images/pizza0.png", [   +1 ms]
I/flutter ( 6489): scale: 1.0) [   +2 ms] I/flutter ( 6489):
════════════════════════════════════════════════════════════════════════════════════════════════════

答:
I was also facing the same issue . The issue on my side was that the image name was having the space in between its name so I updated the image name with the new name that does not have any space.

Image name creating the error was  comboclr emtpy no circle.png

I updated this name to  comboclr_emtpy_no_circle.png

Title: FlutterError: Unable to load asset

Body:
This is the folder structure of my app

.idea
.vscode
android
build
fonts
 Oxygen-Bold.tff
 Oxygen-Light.tff
 Oxygen-Regular.tff
images
 pizza0.png
 pizza1.png
ios
lib
 ui
  home.dart
 main.dart
test
.gitignore
.metadata
.packages
app_widgets.iml
pubspec.lock
pubspec.yaml
README.md

In my pubspec.yaml file, I load the fonts and assets like this

flutter:

uses-material-design: true

assets:
  - images/pizza0.png
  - images/pizza1.png

fonts:
  - family: Oxygen
    fonts:
      - asset: fonts/Oxygen-Regular.ttf
      - asset: fonts/Oxygen-Bold.ttf
        weight: 700
      - asset: fonts/Oxygen-Light.ttf
        weight: 300

I'm not getting any errors for this pubspec.yaml, and running flutter packages get gives an exit code of 0.

In my home.dart I have the following class:

class PizzaImageWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    AssetImage pizzaAsset = AssetImage('images/pizza0.png');
    Image image = Image(image: pizzaAsset, width: 400, height: 400);
    return Container(
      child: image,
    );
  }
}

Which I use elsewhere, in order to show the image (code omitted):

        ),
        PizzaImageWidget(),
      ],

The building gives no errors. Flutter Doctor -v doesn't give any errors, neither does Flutter Analyze -v. The .apk seems to build just fine but when the app opens up on my phone I get the following error in asset_bundle.dart:

Exception has occurred. FlutterError (Unable to load asset:
images/pizza0.png)

The error is thrown by this class in the asset_bundle.dart file:

/// An [AssetBundle] that loads resources using platform messages.
class PlatformAssetBundle extends CachingAssetBundle {
  @override
  Future<ByteData> load(String key) async {
    final Uint8List encoded = utf8.encoder.convert(Uri(path: Uri.encodeFull(key)).path);
    final ByteData asset =
        await BinaryMessages.send('flutter/assets', encoded.buffer.asByteData());
    if (asset == null)
      throw FlutterError('Unable to load asset: $key');
    return asset;
  }
}

This happens both for the pizza0.png file as well as the pizza1.png file. The files are visible in the tree structure, both in Windows Explorer as in VS Code. The font assets load without issue.

This is the output I am getting when running Flutter Run -v:

[+1068 ms] I/flutter ( 6489): ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE
SERVICE ╞════════════════════════════════════════════════════ [   +9
ms] I/flutter ( 6489): The following assertion was thrown resolving an
image codec: [   +2 ms] I/flutter ( 6489): Unable to load asset:
images/pizza0.png [   +2 ms] I/flutter ( 6489): [   +1 ms] I/flutter (
6489): When the exception was thrown, this was the stack: [   +2 ms]
I/flutter ( 6489): #0      PlatformAssetBundle.load
(package:flutter/src/services/asset_bundle.dart:221:7) [   +1 ms]
I/flutter ( 6489):  [   +1 ms] I/flutter (
6489): #1      AssetBundleImageProvider._loadAsync
(package:flutter/src/painting/image_provider.dart:429:44) [   +1 ms]
I/flutter ( 6489):  [   +1 ms] I/flutter (
6489): #2      AssetBundleImageProvider.load
(package:flutter/src/painting/image_provider.dart:414:14) [   +1 ms]
I/flutter ( 6489): #3      ImageProvider.resolve..
(package:flutter/src/painting/image_provider.dart:267:86) [   +4 ms]
I/flutter ( 6489): #4      ImageCache.putIfAbsent
(package:flutter/src/painting/image_cache.dart:143:20) [   +3 ms]
I/flutter ( 6489): #5      ImageProvider.resolve.
(package:flutter/src/painting/image_provider.dart:267:63) [   +3 ms]
I/flutter ( 6489): (elided 8 frames from package dart:async) [   +1
ms] I/flutter ( 6489): [   +1 ms] I/flutter ( 6489): Image provider:
AssetImage(bundle: null, name: "images/pizza0.png") [   +3 ms]
I/flutter ( 6489): Image key: AssetBundleImageKey(bundle:
PlatformAssetBundle#20fc8(), name: "images/pizza0.png", [   +1 ms]
I/flutter ( 6489): scale: 1.0) [   +2 ms] I/flutter ( 6489):
════════════════════════════════════════════════════════════════════════════════════════════════════


来源: stackexchange

问:
How do videos autoplay on iOS at youtube.com
When I set autoplay to true for a YouTube video (IFrame API) on my site, it doesn't work. All the documentation says apple disables autoplay on ios for bandwidth reasons.

However, I see that videos play automatically (without clicking on the video element) on youtube.com on iPad. How did YouTube make it work? It would be hard to imagine Apple does something special just for YouTube.

答:
I stumbled into similar but more complicated issue/requirement.

I need to show YouTube video on a modal popup. Popup is shown on a click.
Have taken YouTube API code (From https://developers.google.com/youtube/iframe_api_reference) and modified a bit to work with Bootstrap popup.

Below is my code

```<code>    <div class="modal" id="videoModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="videoWrapper">
                    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
                    <div id="player"> </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    // 2. This code loads the IFrame Player API code asynchronously.
    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: '360',
            width: '640',
            videoId: 'YOUR VIDEO ID',
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }

    // 4. The API will call this function when the video player is ready.
    function onPlayerReady(event) {
        //event.target.playVideo();// Nullifying the action otherwise the video will play as soon as page loads

    }

    // 5. The API calls this function when the player's state changes.
    //    The function indicates that when playing a video (state=1),
    //    the player should play for six seconds and then stop.
    var done = false;
    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
            setTimeout(stopVideo, 6000);
            done = true;
        }
    }
    function stopVideo() {
        player.stopVideo();
    }

    function ShowPopup() {
        $('#videoModal').modal('show');
        player.playVideo();
    }
    //Stop video when bootstrap popup is closed
    $("#videoModal").on('hide.bs.modal', function () {
        player.stopVideo();
    });

</script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I stumbled into similar but more complicated issue/requirement.

I need to show YouTube video on a modal popup. Popup is shown on a click.
Have taken YouTube API code (From https://developers.google.com/youtube/iframe_api_reference) and modified a bit to work with Bootstrap popup.

Below is my code

    <div class="modal" id="videoModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="videoWrapper">
                    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
                    <div id="player"> </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    // 2. This code loads the IFrame Player API code asynchronously.
    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: '360',
            width: '640',
            videoId: 'YOUR VIDEO ID',
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }

    // 4. The API will call this function when the video player is ready.
    function onPlayerReady(event) {
        //event.target.playVideo();// Nullifying the action otherwise the video will play as soon as page loads

    }

    // 5. The API calls this function when the player's state changes.
    //    The function indicates that when playing a video (state=1),
    //    the player should play for six seconds and then stop.
    var done = false;
    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
            setTimeout(stopVideo, 6000);
            done = true;
        }
    }
    function stopVideo() {
        player.stopVideo();
    }

    function ShowPopup() {
        $('#videoModal').modal('show');
        player.playVideo();
    }
    //Stop video when bootstrap popup is closed
    $("#videoModal").on('hide.bs.modal', function () {
        player.stopVideo();
    });

</script>

ContentLicense: CC BY-SA 4.0


问:
Path-based authorization for microservices in kubernetes
I am tasked with migrating AWS lambda microservices to Kubernetes. For simplicity, there are two service endpoints: /admin and /user where you can GET or POST a request to get something done.

You have to be in admin group (defined in an external authZ provider) to hit /admin endpoint, or otherwise, you get 401. You have to be in user group to have access to /user endpoint.

I will have each endpoint exposed as a service running in a docker container. The question is - what is the correct way to add routing and path-based authorization in Kubernetes?

Like, if I go to /admin in the browser, I need Kubernetes to check if I am in admin group and then route me to admin service; otherwise, it should return 401.

I can write this router myself, but I want to check if there is a built-in solution in Kubernetes for that.

答:
check if there is a built-in solution in Kubernetes

Nope, there's no built-in solution for L7 network policies. Network Policies in Kubernetes are at L4 level, so things like rate limiting, path based firewall rules etc are not possible. Although you could look into a Service Mesh, like Linkerd, Istio or even using a different CNI plugin based on eBPF such as Cilium.

Cilium has a CRD CiliumNetworkPolicy which would help you with your usecase. You can put any proxy like Nginx/Caddy/HAProxy in front of it or an API Gateway like Kong, if you want to offload the authentication/authorization process. You can apply the following network policy, which would restrict the /admin endpoint on any pod with label app: customapp and would only allow it from a pod with label app: proxyapp.

```<code>apiVersion: "cilium.io/v2"
kind: CiliumNetworkPolicy
metadata:
  name: "allow-from-proxy"
specs:
  - endpointSelector:
      matchLabels:
        app: customapp
    ingress:
    - fromEndpoints:
      - matchLabels:
          app: proxyapp
      toPorts:
      - ports:
        - port: "8080"
          protocol: "TCP"
        rules:
          http:
          - method: "GET"
            path: "/admin"
</code>```

Body:
check if there is a built-in solution in Kubernetes

Nope, there's no built-in solution for L7 network policies. Network Policies in Kubernetes are at L4 level, so things like rate limiting, path based firewall rules etc are not possible. Although you could look into a Service Mesh, like Linkerd, Istio or even using a different CNI plugin based on eBPF such as Cilium.

Cilium has a CRD CiliumNetworkPolicy which would help you with your usecase. You can put any proxy like Nginx/Caddy/HAProxy in front of it or an API Gateway like Kong, if you want to offload the authentication/authorization process. You can apply the following network policy, which would restrict the /admin endpoint on any pod with label app: customapp and would only allow it from a pod with label app: proxyapp.

apiVersion: "cilium.io/v2"
kind: CiliumNetworkPolicy
metadata:
  name: "allow-from-proxy"
specs:
  - endpointSelector:
      matchLabels:
        app: customapp
    ingress:
    - fromEndpoints:
      - matchLabels:
          app: proxyapp
      toPorts:
      - ports:
        - port: "8080"
          protocol: "TCP"
        rules:
          http:
          - method: "GET"
            path: "/admin"


问:
CountVectorizer is resulting in error in python
I am trying to convert to vectors for a dataset that has two columns, review and sentiment. Below is the code.

```<code>data = pd.read_csv('/content/IMDB Dataset_SM.csv')
review = data['review']
review= [review]
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer()
x= cv.fit_transform(review)
a=x.toarray()
col = cv.get_feature_names()
df = pd.DataFrame(data=a, columns=col)
df
I am getting error :
AttributeError: 'Series' object has no attribute 'lower'.
</code>```

Please help !!! Thanks

答:
you can try this :

```<code>review=data['review'].values #this will create list
cv = countVectorizer()
x= cv.fit_transform(review)
</code>```

CountVectorizer accepts list of string.

In your code you are extracting Series when you are doing review = data['review']
 and then adding that series to list when you are doing review= [review]

Also, you need to check if your dataframe or series has non-string type element or nan elements.

Hope it helps.

Body:
I am trying to convert to vectors for a dataset that has two columns, review and sentiment. Below is the code.

data = pd.read_csv('/content/IMDB Dataset_SM.csv')
review = data['review']
review= [review]
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer()
x= cv.fit_transform(review)
a=x.toarray()
col = cv.get_feature_names()
df = pd.DataFrame(data=a, columns=col)
df
I am getting error :
AttributeError: 'Series' object has no attribute 'lower'.

Please help !!! Thanks

Body:
you can try this :

review=data['review'].values #this will create list
cv = countVectorizer()
x= cv.fit_transform(review)

CountVectorizer accepts list of string.

In your code you are extracting Series when you are doing review = data['review']
 and then adding that series to list when you are doing review= [review]

Also, you need to check if your dataframe or series has non-string type element or nan elements.

Hope it helps.


问:
How to set labels on jointplot, pairplot, heatmap, catplot on python seaborn?
I am drawing graphs using seaborn on python and want to label x axis and y axis.

When I draw only one graph such as barplot, rugplot, histogram, etc, I could just use:

pyplot.xlabel('x') pyplot.ylabel('y')

But for graphs like jointplot, pairplot, heatmap, and catplot, outcome is different from what I expected.

Jointplot draws scatterplot inside and histogram outside. So when I use pyplot.xlabel('x') pyplot.ylabel('y'), labels are drawn on axes of histogram.

This code draws 4 catplot and using xlabel, ylabel only labels the bottom catplot.

```<code>import seaborn as sns
from matplotlib import pyplot
tips = sns.load_dataset("tips")

sns.catplot(x="sex", y="total_bill", hue="smoker",row="day",
            kind="violin", data=tips, split=True)
pyplot.suptitle("tip - catplot", y=1.01)
pyplot.xlabel('x')
pyplot.ylabel('y')
pyplot.show();
</code>```

How can I label the axes of the entire figure? or each of the graphs?

Thank you

答:
You can grab each axes object by first assigning the return of catplot to a variable. The axes are obtained using the axes attribute. Then set labels for these axes:

```<code>g = sns.catplot(x="sex", y="total_bill", hue="smoker",row="day",
            kind="violin", data=tips, split=True)
for ax, lbl in zip(g.axes.flatten(), 'abcd'):
    ax.set_xlabel(f'x axis {lbl}')
</code>```

Body:
I am drawing graphs using seaborn on python and want to label x axis and y axis.

When I draw only one graph such as barplot, rugplot, histogram, etc, I could just use:

pyplot.xlabel('x') pyplot.ylabel('y')

But for graphs like jointplot, pairplot, heatmap, and catplot, outcome is different from what I expected.

Jointplot draws scatterplot inside and histogram outside. So when I use pyplot.xlabel('x') pyplot.ylabel('y'), labels are drawn on axes of histogram.

This code draws 4 catplot and using xlabel, ylabel only labels the bottom catplot.

import seaborn as sns
from matplotlib import pyplot
tips = sns.load_dataset("tips")

sns.catplot(x="sex", y="total_bill", hue="smoker",row="day",
            kind="violin", data=tips, split=True)
pyplot.suptitle("tip - catplot", y=1.01)
pyplot.xlabel('x')
pyplot.ylabel('y')
pyplot.show();

How can I label the axes of the entire figure? or each of the graphs?

Thank you

Body:
You can grab each axes object by first assigning the return of catplot to a variable. The axes are obtained using the axes attribute. Then set labels for these axes:

g = sns.catplot(x="sex", y="total_bill", hue="smoker",row="day",
            kind="violin", data=tips, split=True)
for ax, lbl in zip(g.axes.flatten(), 'abcd'):
    ax.set_xlabel(f'x axis {lbl}')


问:
This works when HTML, JS and CSS are in one file but doesn't work when they are in different files
I'm creating an HTML, JS and CSS file, these files work together to create a subliminal test. This works when all the HTML, JS and CSS codes are in one file, but when I split them into separate files, and link them in HTML with

and

```<code><script src="filename.js"></script>
</code>```

It is not working.

You can find my code here: https://jsfiddle.net/2vasmch5/

function startTest(){

 var h = document.getElementById("bt");
 if (h.style.display === "none"){
  h.style.display = "block";
 } else {
  h.style.display = "none";
  }

var fourdigitsrandom  = Math.floor(1000 + Math.random() * 9000);

var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
var bgColor = "rgb(" + r + "," + g + "," + b + ")";

var rfd_rc = "rgb(" + (r-1) + "," + (g-1) + "," + (b-1) + ")";

document.querySelector('.rfd').style.color = rfd_rc;

function brColor() {
document.body.style.background = bgColor;
 }
brColor()
function rnColor() {
document.querySelector('.rfd').style.fontSize= "500%";
document.querySelector('.rfd').innerHTML=fourdigitsrandom;
 }
rnColor()

posChr();

const body = document.body;
const chr = document.querySelector('.rfd');
const prev = [0,0];

function posChr () {
  let x = Math.floor(Math.random() * body.offsetWidth);
  let y = Math.floor(Math.random() * body.offsetHeight);

  while (Math.sqrt((x - prev[0]) ** 2 + (y - prev[1]) ** 2) < 10) {
    x = Math.floor(Math.random() * body.offsetWidth);
   y = Math.floor(Math.random() * body.offsetHeight);
  }
  chr.style.left = `${x}px`;
  chr.style.top = `${y}px`;
  chr.textContent = fourdigitsrandom;
  prev[0] = x;
  prev[1] = y;

  setTimeout(posChr, 500);

}

setTimeout(posChr, 500)

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: 100vh;
}
.rfd {
  position: fixed;
}</code>```

<!DOCTYPE html>

<title>Subliminal Test</title>

Subliminal Test

<button id="bt" type="button" onclick="startTest();">Start Test</button>

```

(I made the JS code by gleaning other JS codes and some provided Stackoverflow users here)

What is the reason for this?

Also I'd like to know how can I run this JavaScript for two minutes and after that show a message like, test ended and provide users with multiple options to select one option from a five 4 digit random numbers. And when they select the chosen one, inform them that they have selected the chosen number.

Body:
I'm creating an HTML, JS and CSS file, these files work together to create a subliminal test. This works when all the HTML, JS and CSS codes are in one file, but when I split them into separate files, and link them in HTML with

and

It is not working.

You can find my code here: https://jsfiddle.net/2vasmch5/

function startTest(){

 var h = document.getElementById("bt");
 if (h.style.display === "none"){
  h.style.display = "block";
 } else {
  h.style.display = "none";
  }

var fourdigitsrandom  = Math.floor(1000 + Math.random() * 9000);

var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
var bgColor = "rgb(" + r + "," + g + "," + b + ")";

var rfd_rc = "rgb(" + (r-1) + "," + (g-1) + "," + (b-1) + ")";

document.querySelector('.rfd').style.color = rfd_rc;

function brColor() {
document.body.style.background = bgColor;
 }
brColor()
function rnColor() {
document.querySelector('.rfd').style.fontSize= "500%";
document.querySelector('.rfd').innerHTML=fourdigitsrandom;
 }
rnColor()

posChr();

const body = document.body;
const chr = document.querySelector('.rfd');
const prev = [0,0];

function posChr () {
  let x = Math.floor(Math.random() * body.offsetWidth);
  let y = Math.floor(Math.random() * body.offsetHeight);

  while (Math.sqrt((x - prev[0]) ** 2 + (y - prev[1]) ** 2) < 10) {
    x = Math.floor(Math.random() * body.offsetWidth);
   y = Math.floor(Math.random() * body.offsetHeight);
  }
  chr.style.left = `${x}px`;
  chr.style.top = `${y}px`;
  chr.textContent = fourdigitsrandom;
  prev[0] = x;
  prev[1] = y;

  setTimeout(posChr, 500);

}

setTimeout(posChr, 500)

}

body {
  height: 100vh;
}
.rfd {
  position: fixed;
}

<!DOCTYPE html>

<title>Subliminal Test</title>

Subliminal Test

<button id="bt" type="button" onclick="startTest();">Start Test</button>

(I made the JS code by gleaning other JS codes and some provided Stackoverflow users here)

What is the reason for this?

Also I'd like to know how can I run this JavaScript for two minutes and after that show a message like, test ended and provide users with multiple options to select one option from a five 4 digit random numbers. And when they select the chosen one, inform them that they have selected the chosen number.

Body:
If you open the console and click the button you'll get: ReferenceError: startTest is not defined

This happens because the onclick directive is being processed before your js code is parsed (simple explanation)

To make it work on JSFiddle you need to change the js settings to "No wrap - bottom of " or "No wrap - bottom of "

Check JSFiddle docs: https://docs.jsfiddle.net/panels-settings

To make it work on a real world context, with .html and .js files, you'll need to put everything in the correct place.
For example, including the <script> tag inside the <head> or the <body> you get different behaviors.

Please share your actual context to get real help

Also you may want to put all your code inside an event listener to be sure the page has been loaded completely as explained here: Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

If you're new to js, consider using jquery or a similar framework, it will simplify your learning process

Also I'd like to know how can I run this JavaScript for two minutes and after that show a message like, test ended and provide users with multiple options to select one option from a five 4 digit random numbers. And when they select the chosen one, inform them that they have selected the chosen number.

To run delayed code check the setTimeout function
To catch a change event on a select component, youl'll need to get the element with document.getElementById (or related functions) and then attach listener to the element with addEventListener, but I guess this is too much for a single topic


问:
GraphQL mutator with required args
I am writing a mutation for a GraphQL schema:

```<code>const Schema = new GraphQLSchema({
  mutation: new GraphQLObjectType({
    name: 'Mutation',
    fields: () => ({
      person: {
        type: GraphQLString,
        args: {
          name: {type: GraphQLString},
          school: {type: GraphQLString},
        },
        resolve: mutatePerson,
      },
    }),
  }),
});
</code>```

I want to ensure that mutatePerson will only work if both name and school arguments are present. How can I check that?

答:
it is better to do it as follow (in the model) if you want to reject empty Strings like "", it is different from Null, this way you can reject both Null and empty "".</p>

```<code>const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const buinessSchema = new Schema({
  name: { type: String, required: true, unique: true },
  address: { type: String, required: true },
  phone: { type: String, required: true },
  email: { type: String, required: true },
  website: { type: String, required: true },
  currency: { type: String, required: true },
  aboutus: { type: String, required: true },
  terms: String,
  slogan: String,
  logo: { type: String, required: true }
});

module.exports = mongoose.model("Buiness", buinessSchema);
</code>```

Title: GraphQL mutator with required args

Body:
I am writing a mutation for a GraphQL schema:

const Schema = new GraphQLSchema({
  mutation: new GraphQLObjectType({
    name: 'Mutation',
    fields: () => ({
      person: {
        type: GraphQLString,
        args: {
          name: {type: GraphQLString},
          school: {type: GraphQLString},
        },
        resolve: mutatePerson,
      },
    }),
  }),
});

I want to ensure that mutatePerson will only work if both name and school arguments are present. How can I check that?

Body:
it is better to do it as follow (in the model) if you want to reject empty Strings like "", it is different from Null, this way you can reject both Null and empty "".

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const buinessSchema = new Schema({
  name: { type: String, required: true, unique: true },
  address: { type: String, required: true },
  phone: { type: String, required: true },
  email: { type: String, required: true },
  website: { type: String, required: true },
  currency: { type: String, required: true },
  aboutus: { type: String, required: true },
  terms: String,
  slogan: String,
  logo: { type: String, required: true }
});

module.exports = mongoose.model("Buiness", buinessSchema);


问:
Integrity Error at /blog/2 NOT NULL constraint failed: blog_comment.post_id
I get an error when I try to add comments to my app.

my form is:

```<code>from django import forms
from .models import Comment

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = [
            'content'
        ]
</code>```

And the model is:

```<code>class Post(models.Model):
    title = models.CharField(max_length=50)
    content = models.TextField()
    author = models.ForeignKey(User , on_delete=models.CASCADE)
    image = models.ImageField(upload_to='blog/'  , blank=True, null=True)
    # tags
    category = models.ForeignKey('Category'  ,null=True, on_delete=models.SET_NULL)
    created  = models.DateTimeField(default=timezone.now)

    tags = TaggableManager(blank=True)

    class Meta:
        verbose_name = ' post'
        verbose_name_plural = 'posts'

    def __str__(self):
        return self.title

class Category(models.Model):
    category_name = models.CharField(max_length=50)

    class Meta:
        verbose_name = ' category'
        verbose_name_plural = 'catogires'

    def __str__(self):
        return self.category_name

class Comment(models.Model):
    user = models.ForeignKey(User , on_delete=models.CASCADE)
    post = models.ForeignKey(Post , on_delete=models.CASCADE)
    content = models.TextField()
    created = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return str(self.content)
</code>```

my views are:

```<code>from django.shortcuts import render
from .models import Post , Category , Comment
from taggit.models import Tag
from .forms import CommentForm
def post_detail(request , id):
    post_detail = Post.objects.get(id=id)
    categories = Category.objects.all()
    all_tags = Tag.objects.all()
    comments = Comment.objects.filter(post=post_detail)

    if request.method == 'POST' :
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.user = request.user
            new_comment.post = post_detail
            new_comment.save()

    else:
        comment_form = CommentForm()

    context = {
        'post_detail' : post_detail ,
        'categories' : categories ,
        'all_tags' : all_tags ,
        'comments' : comments ,
        'comment_form' : comment_form
    }

    return render(request , 'Post/post_detail.html' , context)

def post_by_tag(request , tag):
    post_by_tag = Post.objects.filter(tags__name__in=[tag])
    context = {
        'post_list' : post_by_tag ,
    }

    return render(request , 'Post/post_list.html' , context)
</code>```

Please help me to solve the problem. I have checked several sources but I couldn't solve it. I found some similar codes that had written to add comments to posts specially in blogs and tried to use their method on my own code. But I couldn't solve it.

答:
Basically your method name and variable name are same:

```<code>def post_detail(request , id): # <-- Here
    post_detail = Post.objects.get(id=id) # <-- Here
</code>```

Change the variable name to something else, like post

```<code>def post_detail(request , id):
    post = Post.objects.get(id=id)
    categories = Category.objects.all()
    all_tags = Tag.objects.all()
    comments = Comment.objects.filter(post=post)

    if request.method == 'POST' :
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.user = request.user
            new_comment.post = post

    else:
        comment_form = CommentForm()

    context = {
        'post_detail' : post ,
    # rest of the code
</code>```

Body:
I get an error when I try to add comments to my app.

my form is:

from django import forms
from .models import Comment

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = [
            'content'
        ]

And the model is:

class Post(models.Model):
    title = models.CharField(max_length=50)
    content = models.TextField()
    author = models.ForeignKey(User , on_delete=models.CASCADE)
    image = models.ImageField(upload_to='blog/'  , blank=True, null=True)
    # tags
    category = models.ForeignKey('Category'  ,null=True, on_delete=models.SET_NULL)
    created  = models.DateTimeField(default=timezone.now)

    tags = TaggableManager(blank=True)

    class Meta:
        verbose_name = ' post'
        verbose_name_plural = 'posts'

    def __str__(self):
        return self.title

class Category(models.Model):
    category_name = models.CharField(max_length=50)

    class Meta:
        verbose_name = ' category'
        verbose_name_plural = 'catogires'

    def __str__(self):
        return self.category_name

class Comment(models.Model):
    user = models.ForeignKey(User , on_delete=models.CASCADE)
    post = models.ForeignKey(Post , on_delete=models.CASCADE)
    content = models.TextField()
    created = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return str(self.content)

my views are:

from django.shortcuts import render
from .models import Post , Category , Comment
from taggit.models import Tag
from .forms import CommentForm
def post_detail(request , id):
    post_detail = Post.objects.get(id=id)
    categories = Category.objects.all()
    all_tags = Tag.objects.all()
    comments = Comment.objects.filter(post=post_detail)

    if request.method == 'POST' :
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.user = request.user
            new_comment.post = post_detail
            new_comment.save()

    else:
        comment_form = CommentForm()

    context = {
        'post_detail' : post_detail ,
        'categories' : categories ,
        'all_tags' : all_tags ,
        'comments' : comments ,
        'comment_form' : comment_form
    }

    return render(request , 'Post/post_detail.html' , context)

def post_by_tag(request , tag):
    post_by_tag = Post.objects.filter(tags__name__in=[tag])
    context = {
        'post_list' : post_by_tag ,
    }

    return render(request , 'Post/post_list.html' , context)

Please help me to solve the problem. I have checked several sources but I couldn't solve it. I found some similar codes that had written to add comments to posts specially in blogs and tried to use their method on my own code. But I couldn't solve it.

Body:
Basically your method name and variable name are same:

def post_detail(request , id): # <-- Here
    post_detail = Post.objects.get(id=id) # <-- Here

Change the variable name to something else, like post

def post_detail(request , id):
    post = Post.objects.get(id=id)
    categories = Category.objects.all()
    all_tags = Tag.objects.all()
    comments = Comment.objects.filter(post=post)

    if request.method == 'POST' :
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.user = request.user
            new_comment.post = post

    else:
        comment_form = CommentForm()

    context = {
        'post_detail' : post ,
    # rest of the code


问:
Docker DB Migration/Deployment to DigitalOcean
Warning: I am fairly new to docker and cloud hosting, this is likely a dumb question.

I have a local web app which has 3 images associated with it, the app itself, the db and a phpmyadmin image. All works well locally, and if I transfer all the files to my digital ocean droplet and bring up my containers it works fine there as well, but this is not how I want to deploy having every file from every library residing in my droplet.

I have been experimenting with creating a docker-machine on my droplet and deploying my containers remotely to it. This seems to work fine other than the fact that my db image does not reference my database and is simply an empty db. I tried to migrate the db in this fashion which I saw in a tutorial:

```<code>docker-compose run --rm web db:create db:migrate
</code>```

But got the following error, I assume this is because my dev machine is running Windows 10 not Linux, but I cannot find anywhere what the equivalent command would be for a Windows machine.

```<code>Error response from daemon: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"db:create\": executable file not found in $PATH": unknown
</code>```

I know I am probably missing something really stupid and easy but I am having difficulties figuring out how to migrate the data for my db image. Thanks in advance.

UPDATE:
As requested here is my docker-compose:

```<code>    version: "3.4"

services:
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    environment:
      - PMA_ARBITRARY=1
      - PMA_HOST=db
    restart: always
    ports:
      - 80:80
    volumes:
      - /sessions
    depends_on:
      - db
  db:
    image: mysql:latest
    environment:
      MYSQL_ROOT_PASSWORD: mypass
      MYSQL_DATABASE: mydb
    ports:
      - "3306:3306"
    volumes:
      - ./data:/docker-entrypoint-initdb.d
    restart: always
  web:
    depends_on:
      - db
    build: .
    ports:
      - "8080:8080"
    restart: always
volumes:
  data:
</code>```

UPDATE #2:
transfered db file to /docker-entrypoint-initdb.d (I tried this yesterday too but couldn't get it working) and created a new production docker-compose-prod.yml I must be missing something still though as the DB is still empty. Below is my new docker-compose-prod.yml:

```<code>version: "3.4"

services:
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    environment:
      - PMA_ARBITRARY=1
      - PMA_HOST=db
    restart: always
    ports:
      - 80:80
    volumes:
      - /sessions
    depends_on:
      - db
  db:
    image: mysql:latest
    environment:
      MYSQL_ROOT_PASSWORD: mypass
      MYSQL_DATABASE: mydb
    ports:
      - "3306:3306"
    volumes:
      - /docker-entrypoint-initdb.d
    restart: always
  web:
    depends_on:
      - db
    build: .
    ports:
      - "8080:8080"
    restart: always
</code>```

答:
Your strategy is sound.

Actually, you can take it a further step by automating the Droplet provisioning to e.g. use a container-oriented OS and access your Compose file. But that's not this question ;-)

I think it is not relevant that you're using Windows and probably makes little difference; it may require some answer tweaks but that's about it.

The challenge is that you need to move (or recreate) the database state on the remote machine. There are several ways that the DB state could be persisted: in-container (not ideal); using volume mounts (good), other.

Each is "moveable" but it would help if you could add your Compose file to your question so that we may see which approach is being used.

In full-disclosure Im not familiar with the approach that you referencesd but that does not mean that it's inaccurate; I'm just not familiar with it.

Update: docker-entrypoint-initdb.d

See: "Initializing a fresh instance" on MySQL

So, any files within that directory are run to initialize the database container when it's created from the image.

In your Compose file you mount your host's ./data directory into this file. Presumably that directory contains >=1 file that performs your intended initialization.

NB The section volumes: data: at the end of the Compose file appears redundant. You're actually using a host-mounted directory ./data not this volume.

When you run the Compose file on the Droplet, those files aren't present and you'll need to copy them.

The simplest way to do this is to use scp and this provides 2 alternatives:

Either retain the data directory:

IP=[DROPLET-IP]
scp -r ./data root@${IP}:/data
```
<blockquote>
<p><strong>NB</strong> The remote destination is <code>/data</code> not <code>./data</code>. You will need to revise the Compose file on the Droplet (!) too:<br/><br/><code>volumes: - /data:/docker-entrypoint-initdb.d</code></p>
</blockquote>
<p><strong>Or</strong> move the files directly to the Droplet's <code>/docker-entrypoint-initdb.d</code>:</p>
<pre class="lang-sh prettyprint-override"><code>scp -r ./data root@${IP}/docker-entrypointy-initdb.d
</code>```

NB Now there's no need for the volume mapping. You may remove:

    volumes: - ./data:/docker-entrypoint-initdb.d

Update: repro (works)

I used a tweaked docker-compose.yaml but it's essentially the same:

```<code>version: "3.4"

services:
  db:
    image: mysql:latest
    environment:
      MYSQL_ROOT_PASSWORD: mypass
      MYSQL_DATABASE: mydb
    ports:
      - "3306:3306"
    volumes:
      - ${PWD}/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d
    restart: always

  adminer:
    image: adminer
    restart: always
    ports:
      - 8080:8080
</code>```

Then mkdir ${PWD}/docker-entrypoint-initdb.d and created a file in it called freddie.sql:

```<code>create database if not exists frederik;

use frederik;

create table treats (
 TreatID INT NOT NULL AUTO_INCREMENT,
 TreatName VARCHAR(255) NOT NULL,
 PRIMARY KEY (TreatId));

insert into treats (TreatName)
values
 ("Dried Salmon"),
 ("Meatballs");
</code>```

Then docker-compose rm --force && docker-compose up

I was able to browse the adminer UI (:8080), login (root|mypass) and browse the database frederik:

Body:
Warning: I am fairly new to docker and cloud hosting, this is likely a dumb question.

I have a local web app which has 3 images associated with it, the app itself, the db and a phpmyadmin image. All works well locally, and if I transfer all the files to my digital ocean droplet and bring up my containers it works fine there as well, but this is not how I want to deploy having every file from every library residing in my droplet.

I have been experimenting with creating a docker-machine on my droplet and deploying my containers remotely to it. This seems to work fine other than the fact that my db image does not reference my database and is simply an empty db. I tried to migrate the db in this fashion which I saw in a tutorial:

docker-compose run --rm web db:create db:migrate

But got the following error, I assume this is because my dev machine is running Windows 10 not Linux, but I cannot find anywhere what the equivalent command would be for a Windows machine.

Error response from daemon: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"db:create\": executable file not found in $PATH": unknown

I know I am probably missing something really stupid and easy but I am having difficulties figuring out how to migrate the data for my db image. Thanks in advance.

UPDATE:
As requested here is my docker-compose:

    version: "3.4"

services:
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    environment:
      - PMA_ARBITRARY=1
      - PMA_HOST=db
    restart: always
    ports:
      - 80:80
    volumes:
      - /sessions
    depends_on:
      - db
  db:
    image: mysql:latest
    environment:
      MYSQL_ROOT_PASSWORD: mypass
      MYSQL_DATABASE: mydb
    ports:
      - "3306:3306"
    volumes:
      - ./data:/docker-entrypoint-initdb.d
    restart: always
  web:
    depends_on:
      - db
    build: .
    ports:
      - "8080:8080"
    restart: always
volumes:
  data:

UPDATE #2:
transfered db file to /docker-entrypoint-initdb.d (I tried this yesterday too but couldn't get it working) and created a new production docker-compose-prod.yml I must be missing something still though as the DB is still empty. Below is my new docker-compose-prod.yml:

version: "3.4"

services:
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    environment:
      - PMA_ARBITRARY=1
      - PMA_HOST=db
    restart: always
    ports:
      - 80:80
    volumes:
      - /sessions
    depends_on:
      - db
  db:
    image: mysql:latest
    environment:
      MYSQL_ROOT_PASSWORD: mypass
      MYSQL_DATABASE: mydb
    ports:
      - "3306:3306"
    volumes:
      - /docker-entrypoint-initdb.d
    restart: always
  web:
    depends_on:
      - db
    build: .
    ports:
      - "8080:8080"
    restart: always

Body:
Your strategy is sound.

Actually, you can take it a further step by automating the Droplet provisioning to e.g. use a container-oriented OS and access your Compose file. But that's not this question ;-)

I think it is not relevant that you're using Windows and probably makes little difference; it may require some answer tweaks but that's about it.

The challenge is that you need to move (or recreate) the database state on the remote machine. There are several ways that the DB state could be persisted: in-container (not ideal); using volume mounts (good), other.

Each is "moveable" but it would help if you could add your Compose file to your question so that we may see which approach is being used.

In full-disclosure Im not familiar with the approach that you referencesd but that does not mean that it's inaccurate; I'm just not familiar with it.

Update: docker-entrypoint-initdb.d

See: "Initializing a fresh instance" on MySQL

So, any files within that directory are run to initialize the database container when it's created from the image.

In your Compose file you mount your host's ./data directory into this file. Presumably that directory contains >=1 file that performs your intended initialization.

NB The section volumes: data: at the end of the Compose file appears redundant. You're actually using a host-mounted directory ./data not this volume.

When you run the Compose file on the Droplet, those files aren't present and you'll need to copy them.

The simplest way to do this is to use scp and this provides 2 alternatives:

Either retain the data directory:

IP=[DROPLET-IP]
scp -r ./data root@${IP}:/data

NB The remote destination is /data not ./data. You will need to revise the Compose file on the Droplet (!) too:

volumes: - /data:/docker-entrypoint-initdb.d

Or move the files directly to the Droplet's /docker-entrypoint-initdb.d:

scp -r ./data root@${IP}/docker-entrypointy-initdb.d

NB Now there's no need for the volume mapping. You may remove:

    volumes: - ./data:/docker-entrypoint-initdb.d

Update: repro (works)

I used a tweaked docker-compose.yaml but it's essentially the same:

version: "3.4"

services:
  db:
    image: mysql:latest
    environment:
      MYSQL_ROOT_PASSWORD: mypass
      MYSQL_DATABASE: mydb
    ports:
      - "3306:3306"
    volumes:
      - ${PWD}/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d
    restart: always

  adminer:
    image: adminer
    restart: always
    ports:
      - 8080:8080

Then mkdir ${PWD}/docker-entrypoint-initdb.d and created a file in it called freddie.sql:

create database if not exists frederik;

use frederik;

create table treats (
 TreatID INT NOT NULL AUTO_INCREMENT,
 TreatName VARCHAR(255) NOT NULL,
 PRIMARY KEY (TreatId));

insert into treats (TreatName)
values
 ("Dried Salmon"),
 ("Meatballs");

Then docker-compose rm --force && docker-compose up

I was able to browse the adminer UI (:8080), login (root|mypass) and browse the database frederik:


问:
Terraform variable to assign using function
```<code>variable "cidr" {
  type = map(string)
  default = {
      development = "x.1.0.0/16"
      qa = "x.1.0.0/16"
      default = "x.1.0.0/16"
  }
}
</code>```

```<code>variable "network_address_space" {
  default = lookup(var.cidr, var.environment_name,"default")
}
</code>```

<p>Am getting error that "Error: Function calls not allowed" </p>

```<code>variable "subnet_address_space": cidr_subnet2_address_space = cidrsubnet(var.network_address_space,8,1)
</code>```

答:
As stated in Interpolate variables inside .tfvars to define another variable by the Hashicorp person, it is intended to be constant by design.

Input variables are constant values passed into the root module, and so they cannot contain interpolations or other expressions that do not yield a constant value.

We cannot use variables in backend either as in Using variables in terraform backend config block.

These are the things we Terraform users tripped on at some point, I suppose.

Body:
variable "cidr" {
  type = map(string)
  default = {
      development = "x.1.0.0/16"
      qa = "x.1.0.0/16"
      default = "x.1.0.0/16"
  }
}

variable "network_address_space" {
  default = lookup(var.cidr, var.environment_name,"default")
}

Am getting error that "Error: Function calls not allowed"

variable "subnet_address_space": cidr_subnet2_address_space = cidrsubnet(var.network_address_space,8,1)


问:
Why use static_cast rather than dynamic_cast in here?
I copy the following text from the book More Effective C++.

Item 31:  Making functions virtual with respect to more than one object.

```<code>class GameObject { ... };
class SpaceShip: public GameObject { ... };
class SpaceStation: public GameObject { ... };
class Asteroid: public GameObject { ... };
</code>```

The most common approach to double-dispatching returns us to the unforgiving world of virtual function emulation via chains of if-then-elses. In this harsh world, we first discover the real type of otherObject, then we test it against all the possibilities:

```<code>void SpaceShip::collide(GameObject& otherObject)
{
  const type_info& objectType = typeid(otherObject);

  if (objectType == typeid(SpaceShip)) {
    SpaceShip& ss = static_cast<SpaceShip&>(otherObject);

    process a SpaceShip-SpaceShip collision;

  }
  else if (objectType == typeid(SpaceStation)) {
    SpaceStation& ss =
      static_cast<SpaceStation&>(otherObject);

    process a SpaceShip-SpaceStation collision;

  }
...
}
</code>```

Here is the question:

Q1> Why we use static_cast here rather than obvious dynamic_cast?

Q2>　Are they same in this case?

thank you

// updated //

In fact, I am more interested in question 2.

For example,

```<code>class base {};
class subclass : public base {};

base *pSubClass = new subclass;

subclass *pSubClass1 = static_cast<subClass*> (pSubClass);
</code>```

// does the static_cast do the job correctly in this case although I know we should use dynamic_cast here?

答:
Why they chose to implement it this way, instead of the more traditional dynamic_cast I can't say, but the behavior of the two options is not necessarily the same.  As written, that code only considers the actual type of the parameter, while dynamic_cast considers where the parameter falls in an inheritance tree.  Consider:

```<code>struct Base { virtual ~Base() { } };
struct Intermediate : Base { };
struct Derived : Intermediate { };

int main() {
    Intermediate i;
    Base* p_i = &i;

    Derived d;
    Base* p_d = &d;

    assert(typeid(*p_i) == typeid(Intermediate)); //1
    assert(dynamic_cast<Intermediate*>(p_i)); //2

    assert(typeid(*p_d) == typeid(Intermediate)); //3
    assert(dynamic_cast<Intermediate*>(p_d)); //4
}
</code>```

(1) and (2) both pass their assertions, but (3) fails while (4) succeeds.  p_d points to a Derived object, so type_id yields information for a Derived object, which will not compare equal to the information for an Intermediate object.  But Derived derives from Intermediate, so dynamic_cast will happily convert a pointer to Derived to a pointer to Intermediate.

To put it in terms used in the original question, if otherObject is a Frigate, which derives from SpaceShip, it will not use the "spaceship<->spaceship" collision routine.  There's a good chance this is not the intended behavior; you might want Frigate to use that code, but instead you have to manually add an explicit check for that new type.

Of course, if you're only checking against types that are never inherited from, this difference goes away.  Or if you just don't want polymorphic behavior (although that would make the heading somewhat misleading).  In that case, this might be more performant, but that's a giant implementation detail and I certainly wouldn't put money on it in practice.

Another small, and largely inconsequential, difference occurs if the types are not polymorphic.  In my above code, if you remove the virtual destructor from Base, (2) and (4) now exhibit undefined behavior.  (1) and (3) remain well defined, but are now worthless; both will fail because typeid(*p_i) will yield information about Base rather than Intermediate like it used to.

Body:
I copy the following text from the book More Effective C++.

Item 31:  Making functions virtual with respect to more than one object.

class GameObject { ... };
class SpaceShip: public GameObject { ... };
class SpaceStation: public GameObject { ... };
class Asteroid: public GameObject { ... };

The most common approach to double-dispatching returns us to the unforgiving world of virtual function emulation via chains of if-then-elses. In this harsh world, we first discover the real type of otherObject, then we test it against all the possibilities:

void SpaceShip::collide(GameObject& otherObject)
{
  const type_info& objectType = typeid(otherObject);

  if (objectType == typeid(SpaceShip)) {
    SpaceShip& ss = static_cast<SpaceShip&>(otherObject);

    process a SpaceShip-SpaceShip collision;

  }
  else if (objectType == typeid(SpaceStation)) {
    SpaceStation& ss =
      static_cast<SpaceStation&>(otherObject);

    process a SpaceShip-SpaceStation collision;

  }
...
}

Here is the question:

Q1> Why we use static_cast here rather than obvious dynamic_cast?

Q2>　Are they same in this case?

thank you

// updated //

In fact, I am more interested in question 2.

For example,

class base {};
class subclass : public base {};

base *pSubClass = new subclass;

subclass *pSubClass1 = static_cast<subClass*> (pSubClass);

// does the static_cast do the job correctly in this case although I know we should use dynamic_cast here?

Body:
Why they chose to implement it this way, instead of the more traditional dynamic_cast I can't say, but the behavior of the two options is not necessarily the same.  As written, that code only considers the actual type of the parameter, while dynamic_cast considers where the parameter falls in an inheritance tree.  Consider:

struct Base { virtual ~Base() { } };
struct Intermediate : Base { };
struct Derived : Intermediate { };

int main() {
    Intermediate i;
    Base* p_i = &i;

    Derived d;
    Base* p_d = &d;

    assert(typeid(*p_i) == typeid(Intermediate)); //1
    assert(dynamic_cast<Intermediate*>(p_i)); //2

    assert(typeid(*p_d) == typeid(Intermediate)); //3
    assert(dynamic_cast<Intermediate*>(p_d)); //4
}

(1) and (2) both pass their assertions, but (3) fails while (4) succeeds.  p_d points to a Derived object, so type_id yields information for a Derived object, which will not compare equal to the information for an Intermediate object.  But Derived derives from Intermediate, so dynamic_cast will happily convert a pointer to Derived to a pointer to Intermediate.

To put it in terms used in the original question, if otherObject is a Frigate, which derives from SpaceShip, it will not use the "spaceship<->spaceship" collision routine.  There's a good chance this is not the intended behavior; you might want Frigate to use that code, but instead you have to manually add an explicit check for that new type.

Of course, if you're only checking against types that are never inherited from, this difference goes away.  Or if you just don't want polymorphic behavior (although that would make the heading somewhat misleading).  In that case, this might be more performant, but that's a giant implementation detail and I certainly wouldn't put money on it in practice.

Another small, and largely inconsequential, difference occurs if the types are not polymorphic.  In my above code, if you remove the virtual destructor from Base, (2) and (4) now exhibit undefined behavior.  (1) and (3) remain well defined, but are now worthless; both will fail because typeid(*p_i) will yield information about Base rather than Intermediate like it used to.


问:
How to make while loop check if there are 16 digits in a string
How do I make the loop check if there is 16 digits in a string and reset the string if there is not enough. I am trying to make a credit card program that will calculate the check digit. I have everything else working I just cant get the program to check the number of digits in the user inputted string.Thanks for any and all help!</p>

```<code>import java.util.Scanner;

public class LuhnAlgorithm {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
        String nums = input.nextLine();

        int i = 0;
        char chk = nums.charAt(15);

        while(!nums .equals("") ) {

            if (nums.length()<16 || nums.length() > 15){ //How do I get this line to reset the while loop?
                System.out.println("ERROR! Number MUST have exactly 16 digits.");
            }

            int sum = 0;
            for( i = 0; i < 15; i++) {
                char numc = nums.charAt(i);
                int num = Character.getNumericValue(numc);
                if ( i % 2 == 0 ) {
                    num = num * 2;
                    if ( num >= 10) {
                        num = num - 9;
                    }
                }
                sum = num + sum;
            }

            int sum2 = sum % 10;
            if (sum2 > 0) {
                sum2 = 10 - sum2;
            }
            int chk2 = Character.getNumericValue(chk);
            System.out.println("The check digit should be: " + sum2);
            System.out.println("The check digit is: " + chk);
            if ( sum2 == chk2) {
                System.out.println("Number is valid.");
            }
            else {
                System.out.println("Number is not valid. ");
            }

            System.out.print("Enter a number credit card number (Enter a blank line to quit:) ");
            nums = input.nextLine();
        }

        System.out.println("Goodbye!");
        input.close();
    }
}
</code>```

答:
You can include your code that you only want done if the length ==16 in an if statement.

Meaning, instead of:

```<code>if (nums.length != 16) {
    //code if there is an error
}
//code if there is no error
</code>```

you can do:

```<code>if (nums.length == 16) {
    //code if there is no error
} else {
    //code if there is an error
}
</code>```

(I also want to point out that you set chk = nums.charAt(15) before your while loop, but you don't reset it in the while loop for the next time the user inputs a new credit card number.)

Body:
How do I make the loop check if there is 16 digits in a string and reset the string if there is not enough. I am trying to make a credit card program that will calculate the check digit. I have everything else working I just cant get the program to check the number of digits in the user inputted string.Thanks for any and all help!

import java.util.Scanner;

public class LuhnAlgorithm {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
        String nums = input.nextLine();

        int i = 0;
        char chk = nums.charAt(15);

        while(!nums .equals("") ) {

            if (nums.length()<16 || nums.length() > 15){ //How do I get this line to reset the while loop?
                System.out.println("ERROR! Number MUST have exactly 16 digits.");
            }

            int sum = 0;
            for( i = 0; i < 15; i++) {
                char numc = nums.charAt(i);
                int num = Character.getNumericValue(numc);
                if ( i % 2 == 0 ) {
                    num = num * 2;
                    if ( num >= 10) {
                        num = num - 9;
                    }
                }
                sum = num + sum;
            }

            int sum2 = sum % 10;
            if (sum2 > 0) {
                sum2 = 10 - sum2;
            }
            int chk2 = Character.getNumericValue(chk);
            System.out.println("The check digit should be: " + sum2);
            System.out.println("The check digit is: " + chk);
            if ( sum2 == chk2) {
                System.out.println("Number is valid.");
            }
            else {
                System.out.println("Number is not valid. ");
            }

            System.out.print("Enter a number credit card number (Enter a blank line to quit:) ");
            nums = input.nextLine();
        }

        System.out.println("Goodbye!");
        input.close();
    }
}

Body:
You can include your code that you only want done if the length ==16 in an if statement.

Meaning, instead of:

if (nums.length != 16) {
    //code if there is an error
}
//code if there is no error

you can do:

if (nums.length == 16) {
    //code if there is no error
} else {
    //code if there is an error
}

(I also want to point out that you set chk = nums.charAt(15) before your while loop, but you don't reset it in the while loop for the next time the user inputs a new credit card number.)


问:
How to fix ValueError in fitting GMM using sklearn.mixture.GaussianMixture?
I am trying to use GaussianMixture model for image segmetation, so I used 2 components, covariance matrix type="full" and tried to run using Spyder3.6 which comes with anaconda. Here's the code:

```<code>from scipy.misc import imread, imshow
from sklearn.mixture import GaussianMixture as GMM
import graph_tool.all as gt
from graph_tool.all import *

X=imread('2.jpg')
old=X.shape
X=X.reshape(-1,3)
gmm=GMM(covariance_type='full', n_components=2)
gmm.fit(X)
clusters=gmm.predict(X)
clusters=clusters.reshape(old[0],old[1])
</code>```

But it shows ValueError and positive definite exception and I can't figure out why? Here's the trace of error.

`

Traceback (most recent call last):

File "/home/madhur/anaconda3/lib/python3.6/site-packages/sklearn/mixture/gaussian_mixture.py", line 318, in _compute_precision_cholesky
      cov_chol = linalg.cholesky(covariance, lower=True)

    File "/home/madhur/anaconda3/lib/python3.6/site-packages/scipy/linalg/decomp_cholesky.py", line 81, in cholesky
      check_finite=check_finite)

    File "/home/madhur/anaconda3/lib/python3.6/site-packages/scipy/linalg/decomp_cholesky.py", line 30, in _cholesky

          raise LinAlgError("%d-th leading minor not positive definite" % info)

  numpy.linalg.linalg.LinAlgError: 2-th leading minor not positive definite

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

    File "/home/madhur/Desktop/Project/graphcutmaterials/test.py", line 19, in
      gmm.fit(X)

  File "/home/madhur/anaconda3/lib/python3.6/site-packages/sklearn/mixture/base.py", line 207, in fit
      self._initialize_parameters(X, random_state)

  File "/home/madhur/anaconda3/lib/python3.6/site-packages/sklearn/mixture/base.py", line 157, in _initialize_parameters
      self._initialize(X, resp)

    File "/home/madhur/anaconda3/lib/python3.6/site-packages/sklearn/mixture/gaussian_mixture.py", line 643, in _initialize
      covariances, self.covariance_type)

    File "/home/madhur/anaconda3/lib/python3.6/site-packages/sklearn/mixture/gaussian_mixture.py", line 320, in _compute_precision_cholesky

          raise ValueError(estimate_precision_error_message)

ValueError: Fitting the mixture model failed because some components have ill-defined empirical covariance (for instance caused by singleton or collapsed samples). Try to decrease the number of components, or increase reg_covar.

`

答:
I think the reason has already been presented in the ErrorInformation, which is "because some components have ill-defined empirical covariance (for instance caused by singleton or collapsed samples)". Since you set the number of components to 2, it can not be decreased, so I suggest you to increase the parameter "reg_covar" to 1e-5 (default to 1e-6).

more information about GMM's parameters can be found in: https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html

Body:
I am trying to use GaussianMixture model for image segmetation, so I used 2 components, covariance matrix type="full" and tried to run using Spyder3.6 which comes with anaconda. Here's the code:

from scipy.misc import imread, imshow
from sklearn.mixture import GaussianMixture as GMM
import graph_tool.all as gt
from graph_tool.all import *

X=imread('2.jpg')
old=X.shape
X=X.reshape(-1,3)
gmm=GMM(covariance_type='full', n_components=2)
gmm.fit(X)
clusters=gmm.predict(X)
clusters=clusters.reshape(old[0],old[1])

But it shows ValueError and positive definite exception and I can't figure out why? Here's the trace of error.

`

Traceback (most recent call last):

File "/home/madhur/anaconda3/lib/python3.6/site-packages/sklearn/mixture/gaussian_mixture.py", line 318, in _compute_precision_cholesky
      cov_chol = linalg.cholesky(covariance, lower=True)

    File "/home/madhur/anaconda3/lib/python3.6/site-packages/scipy/linalg/decomp_cholesky.py", line 81, in cholesky
      check_finite=check_finite)

    File "/home/madhur/anaconda3/lib/python3.6/site-packages/scipy/linalg/decomp_cholesky.py", line 30, in _cholesky

          raise LinAlgError("%d-th leading minor not positive definite" % info)

  numpy.linalg.linalg.LinAlgError: 2-th leading minor not positive definite

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

    File "/home/madhur/Desktop/Project/graphcutmaterials/test.py", line 19, in
      gmm.fit(X)

  File "/home/madhur/anaconda3/lib/python3.6/site-packages/sklearn/mixture/base.py", line 207, in fit
      self._initialize_parameters(X, random_state)

  File "/home/madhur/anaconda3/lib/python3.6/site-packages/sklearn/mixture/base.py", line 157, in _initialize_parameters
      self._initialize(X, resp)

    File "/home/madhur/anaconda3/lib/python3.6/site-packages/sklearn/mixture/gaussian_mixture.py", line 643, in _initialize
      covariances, self.covariance_type)

    File "/home/madhur/anaconda3/lib/python3.6/site-packages/sklearn/mixture/gaussian_mixture.py", line 320, in _compute_precision_cholesky

          raise ValueError(estimate_precision_error_message)

ValueError: Fitting the mixture model failed because some components have ill-defined empirical covariance (for instance caused by singleton or collapsed samples). Try to decrease the number of components, or increase reg_covar.

`


问:
Uncaught ReferenceError: Cannot access 'CONFIG' before initialization
The project created by CRA.

utils/config.js

```<code>   CONFIG={
    test:'test
   }
</code>```

Then I imported at my src/index.js(which is root of project)

```<code>    <Provider store={store}>
            <Router>
                <Switch>
                    <Route path='/' exact>
                        <MainContainer title={'Welcome to something'} />
                    </Route>
                    <Route path='/dummy' exact>
                        <DummyContainer />
                    </Route>
                    <Route path='/pop/:topicId' exact>
                        <Popup />
                    </Route>
                    <Route path='/app' exact>
                        <App />
                    </Route>
                </Switch>
            </Router>
        </Provider>,
</code>```

import 'utils/config';

I can access CONFIG from my component which is called from src/index.js

but error occurred that cannot access to CONFIG.

Is there anyway to put CONFIG in very first state?

THANK you.

答:
make sure you exported it correctly. It should be either default or named export.
try changes below

utils/config.js

```<code>export default {
  test:'test'
}
</code>```

src/index.js(which is the root of the project)

```<code>import config from 'utils/config'
</code>```

now you can use your config object as you want

Body:
The project created by CRA.

utils/config.js

   CONFIG={
    test:'test
   }

Then I imported at my src/index.js(which is root of project)

    <Provider store={store}>
            <Router>
                <Switch>
                    <Route path='/' exact>
                        <MainContainer title={'Welcome to something'} />
                    </Route>
                    <Route path='/dummy' exact>
                        <DummyContainer />
                    </Route>
                    <Route path='/pop/:topicId' exact>
                        <Popup />
                    </Route>
                    <Route path='/app' exact>
                        <App />
                    </Route>
                </Switch>
            </Router>
        </Provider>,

import 'utils/config';

I can access CONFIG from my component which is called from src/index.js

but error occurred that cannot access to CONFIG.

Is there anyway to put CONFIG in very first state?

THANK you.

Body:
make sure you exported it correctly. It should be either default or named export.
try changes below

utils/config.js

export default {
  test:'test'
}

src/index.js(which is the root of the project)

import config from 'utils/config'

now you can use your config object as you want


问:
Inheriting and overriding ostream operator in C++
I've been trying to find an answer to this, but no one seems to have exactly the same problem as I do.

I am working with several derived classes. The ostream operator << for each of these should print out some things common to each, and some things specific to each.  Later on, I would like to further derive from these derived classes, and again the new derived classes need to print out some things that are in the "generations" above them.

For example:

The Base class .h file

```<code>class Base

{

 int FirstClassNumber;

//The declaration I'm currently working with, that a friend gave me
//I'm pretty sure my problem lies here.

public:

friend ostream& operator << (ostream& os, const Base &base)
{
    base << os ;

    return os;
}

virtual void operator << (ostream& os) const = 0;

};
</code>```

The Base.cpp file includes these lines:

```<code>void Base::operator << (ostream& os)
{
  os << FirstClassNumber;
}
</code>```

Then I derive: (FirstDerived.h)

```<code>class FirstDerived : Public Base

{

int SecondClassNumber;

};
</code>```

FirstDerived.cpp:

```<code>FirstDerived::operator << (ostream& os)
{
  os <<

  "The first Number is:

 //This is the line that isn't working - someone else gave me this syntax

  << Base::operator<<

  << "The second number is"

  << SecondClassNumber;
}
</code>```

Then I want to derive:

```<code>class SecondDerived: Public FirstDerived
{

int ThirdClassNumber;

};
</code>```

Second.cpp:

```<code>FirstDerived::operator << (ostream& os)
{
  os <<

 FirstDerived::operator<<

 << "The third number is "

 << ThirdClassNumber;

 }
</code>```

I think the problem is most likely either the declaration in the very start of the program, or the lines like Base::operator<<.

Another possibility is that I'm not redeclaring it in the .h file of every inherited class.  Should I be, and if so what syntax should I use?

It was suggested to me to use the static_cast method, but my professor (the one who wrote the assignment, and therefore won't give us too much help with it) said that there's a better way to do it.  Any suggestions?

答:
You cannot implement operator<< for ostreams as a class member - it has to be a free (possibly friend) function. This is because in the expression:

```<code>os << x;
</code>```

the thing on the left-hand side of the << will not be an instance of your class, which it would have to be if it were a member function.

To call the parent from the child - do a static_cast:

```<code>ostream & operator << ( ostream & os, const Child & c ) {
      os << static_cast <const Parent &>( c );
      // child stuff here
}
</code>```

which I think is the "best" solution. Alternatively, give your classes a a named function call Print() which takes an ostream as a parameter and use this to implement your operator<<. This will result in much cleaer code.

Body:
I've been trying to find an answer to this, but no one seems to have exactly the same problem as I do.

I am working with several derived classes. The ostream operator << for each of these should print out some things common to each, and some things specific to each.  Later on, I would like to further derive from these derived classes, and again the new derived classes need to print out some things that are in the "generations" above them.

For example:

The Base class .h file

class Base

{

 int FirstClassNumber;

//The declaration I'm currently working with, that a friend gave me
//I'm pretty sure my problem lies here.

public:

friend ostream& operator << (ostream& os, const Base &base)
{
    base << os ;

    return os;
}

virtual void operator << (ostream& os) const = 0;

};

The Base.cpp file includes these lines:

void Base::operator << (ostream& os)
{
  os << FirstClassNumber;
}

Then I derive: (FirstDerived.h)

class FirstDerived : Public Base

{

int SecondClassNumber;

};

FirstDerived.cpp:

FirstDerived::operator << (ostream& os)
{
  os <<

  "The first Number is:

 //This is the line that isn't working - someone else gave me this syntax

  << Base::operator<<

  << "The second number is"

  << SecondClassNumber;
}

Then I want to derive:

class SecondDerived: Public FirstDerived
{

int ThirdClassNumber;

};

Second.cpp:

FirstDerived::operator << (ostream& os)
{
  os <<

 FirstDerived::operator<<

 << "The third number is "

 << ThirdClassNumber;

 }

I think the problem is most likely either the declaration in the very start of the program, or the lines like Base::operator<<.

Another possibility is that I'm not redeclaring it in the .h file of every inherited class.  Should I be, and if so what syntax should I use?

It was suggested to me to use the static_cast method, but my professor (the one who wrote the assignment, and therefore won't give us too much help with it) said that there's a better way to do it.  Any suggestions?

Body:
You cannot implement operator<< for ostreams as a class member - it has to be a free (possibly friend) function. This is because in the expression:

os << x;

the thing on the left-hand side of the << will not be an instance of your class, which it would have to be if it were a member function.

To call the parent from the child - do a static_cast:

ostream & operator << ( ostream & os, const Child & c ) {
      os << static_cast <const Parent &>( c );
      // child stuff here
}

which I think is the "best" solution. Alternatively, give your classes a a named function call Print() which takes an ostream as a parameter and use this to implement your operator<<. This will result in much cleaer code.


问:
SilverStripe ModelAdmin number of records per page for pagination is not working
I am working on a SilverStripe project. In my project, I am building a model admin class to display the list of records within the CMS. I am trying to limit the number of records rendered per page. So I put $page_length field in my model admin class like this.

```<code>class OrderAdmin extends ModelAdmin
{
    private static $managed_models = [
        Order::class
    ];

    private static $url_segment = 'orders';

    private static $menu_title = 'Orders';

    private static $menu_icon_class = 'font-icon-checklist';

    private static $page_length = 25;

    //other code goes here
}
</code>```

As you can see, in the code above, I set the number of records per page to 25. Even though I set it to 25, it is still displaying 15 records per page within the CMS. I rebuilt and refreshed the project as well. What is missing in my code and how can I fix it?

答:
This was a bug in Silverstripe Admin module around version ~4.3. This has since been fixed:

https://github.com/silverstripe/silverstripe-admin/issues/971

Your code private static $page_length = 25; is the correct way to set the page length. This will now work correctly in Silverstripe 4.5

Body:
I am working on a SilverStripe project. In my project, I am building a model admin class to display the list of records within the CMS. I am trying to limit the number of records rendered per page. So I put $page_length field in my model admin class like this.

class OrderAdmin extends ModelAdmin
{
    private static $managed_models = [
        Order::class
    ];

    private static $url_segment = 'orders';

    private static $menu_title = 'Orders';

    private static $menu_icon_class = 'font-icon-checklist';

    private static $page_length = 25;

    //other code goes here
}

As you can see, in the code above, I set the number of records per page to 25. Even though I set it to 25, it is still displaying 15 records per page within the CMS. I rebuilt and refreshed the project as well. What is missing in my code and how can I fix it?


问:
Is there a way of downloading a file (such as PDF) and storing it on the device with Capacitor?
Is it possible to download and store files (accessing the file system) with Capacitor? I've only been able to find Cordova plugins, but would like to keep the app pure using Ionic and Capacitor.</p>

答:
You should simply use download() method like this:

```<code>this.pdfObj.download();
</code>```

Here you can find more info: https://forum.ionicframework.com/t/do-you-know-how-to-save-and-open-a-pdf-using-capacitor-and-ionic-4/158634/3

Body:
You should simply use download() method like this:

this.pdfObj.download();

Here you can find more info: https://forum.ionicframework.com/t/do-you-know-how-to-save-and-open-a-pdf-using-capacitor-and-ionic-4/158634/3


问:
Need Help Downloading Albow Library
I am trying to download a library called Albow. I tried using pip to install it, but it didn't work, so I went to the Albow website and it linked to a .zip file. Basically what I want to do is to make it so that when I type:

```<code>import albow
</code>```

Python recognizes it.

I'm using Python 3.5.3, on a Debian Linux VM. My PC's OS is using ChromeOS.

If I missed something that I should explain, I will edit the question.

答:
The Albow website you linked to (or this other one from the Pygame projects) only supports Python 2. It's not available in PyPi so pip install would not work.

Since you tagged this python3.5, I assume you want Python 3 support.

There is a ported version available from PyPi: https://pypi.org/project/python3-albow/.

This project is a port of Gregory Ewing's Albow project (https://www.pygame.org/project/338/4687) that is only compatible with Python 2 and is unsupported since 2014.

You should be able to install it using standard pip install

$ python3.5 -m pip install --user python3-albow
...
Installing collected packages: pygame, python3-albow
Successfully installed pygame-1.9.6 python3-albow-2.7.8

$ python3.5
Python 3.5.9 (default, Nov 24 2019, 01:35:13)
[GCC 7.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import albow
>>> albow.__path__
['/home/gino/.local/lib/python3.5/site-packages/albow']
>>>
```

Or, preferably, setup a virtual environment and install it there.

Title: Need Help Downloading Albow Library

Body:
I am trying to download a library called Albow. I tried using pip to install it, but it didn't work, so I went to the Albow website and it linked to a .zip file. Basically what I want to do is to make it so that when I type:

import albow

Python recognizes it.

I'm using Python 3.5.3, on a Debian Linux VM. My PC's OS is using ChromeOS.

If I missed something that I should explain, I will edit the question.

Body:
The Albow website you linked to (or this other one from the Pygame projects) only supports Python 2. It's not available in PyPi so pip install would not work.

Since you tagged this python3.5, I assume you want Python 3 support.

There is a ported version available from PyPi: https://pypi.org/project/python3-albow/.

This project is a port of Gregory Ewing's Albow project (https://www.pygame.org/project/338/4687) that is only compatible with Python 2 and is unsupported since 2014.

You should be able to install it using standard pip install

$ python3.5 -m pip install --user python3-albow
...
Installing collected packages: pygame, python3-albow
Successfully installed pygame-1.9.6 python3-albow-2.7.8

$ python3.5
Python 3.5.9 (default, Nov 24 2019, 01:35:13)
[GCC 7.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import albow
>>> albow.__path__
['/home/gino/.local/lib/python3.5/site-packages/albow']
>>>

Or, preferably, setup a virtual environment and install it there.


问:
How to make VS ignore code coverage for Test dll
Currently, when I run code coverage analysis the reported coverage is 90%. The thing is that the other 10% is the code for the actual test!

How can i make VS ignore that test code and only take into account the actual code?

答:
There is now the ExcludeFromCodeCoverage attribute with which excluded code can be decorated.  I've been using it with great success.

Placing this attribute on a class or a structure excludes all the members of that class or structure from the collection of code coverage information.


问:
Bootstrap 4 Navbar Toggler Button shifting to new line on small screens after adding logo to Navbar Brand
Below is the code for my Navbar:

```<code><nav class="navbar navbar-expand-lg navbar-dark custom-bg-primary text-white fixed-top mb-3 py-2">
  <div class="container">
    <a class="navbar-brand" href="{% url 'job-list' %}"><img src="{% static 'jobs/images/sirf-sarkari-naukri.png' %}" alt="Sirf Sarkari Naukri" height="25%" width="25%"></a>
    <!-- <a class="navbar-brand" href="{% url 'job-list' %}">Sirf Sarkari Naukri</a> -->
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarResponsive">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle py-0" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">SARKARI JOBS</a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
            <a class="dropdown-item" href="#">BY COMPANY</a>
            <hr />
            <a class="dropdown-item" href="#">BY QUALIFICATION</a>
            <a class="dropdown-item" href="#">BY PROFESSION</a>
            <hr />
            <a class="dropdown-item" href="#">BY STATE</a>
            <a class="dropdown-item" href="#">BY TOP CITIES</a>
          </div>
        </li>
      </ul>
    </div>
  </div>
</nav>
</code>```

After I added logo to my Navbar, on small screen the Navbar Toggler button is getting shifted to new line and overlapping on the search bar.

Could anyone please help me fix this issue, thanks in advance!

答:
display:inline is causing this... use display:contents to resolve

nav {
  background-color: #229a44;
}

a.navbar-brand {
  display: contents;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous" />

<nav class="navbar navbar-expand-lg navbar-dark custom-bg-primary text-white fixed-top mb-3 py-2">
  <div class="container">

      <img src="https://i.stack.imgur.com/Jqd4Z.png" alt="Sirf Sarkari Naukri" height="25%" width="25%">
      <!--
    <img src="https://www.akberiqbal.com/favicon.ico" alt="Sirf Sarkari Naukri" height="25%" width="25%">
    -->

    <!-- Sirf Sarkari Naukri -->
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
      <i class="fas fa-thumbs-up"></i>
    </button>
    <div class="collapse navbar-collapse" id="navbarResponsive">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item dropdown">
          SARKARI JOBS
          <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
            BY COMPANY
            <hr />
            BY QUALIFICATION
            BY PROFESSION
            <hr />
            BY STATE
            BY TOP CITIES
          </div>
        </li>
      </ul>
    </div>
  </div>
</nav></code>```

Body:
Below is the code for my Navbar:

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          SARKARI JOBS

            BY COMPANY

            BY QUALIFICATION
            BY PROFESSION

            BY STATE
            BY TOP CITIES

After I added logo to my Navbar, on small screen the Navbar Toggler button is getting shifted to new line and overlapping on the search bar.

Could anyone please help me fix this issue, thanks in advance!

Body:
display:inline is causing this... use display:contents to resolve

nav {
  background-color: #229a44;
}

a.navbar-brand {
  display: contents;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous" />

<nav class="navbar navbar-expand-lg navbar-dark custom-bg-primary text-white fixed-top mb-3 py-2">
  <div class="container">
    <a class="navbar-brand" href="{% url 'job-list' %}">
      <img src="https://i.stack.imgur.com/Jqd4Z.png" alt="Sirf Sarkari Naukri" height="25%" width="25%">
      <!--
    <img src="https://www.akberiqbal.com/favicon.ico" alt="Sirf Sarkari Naukri" height="25%" width="25%">
    -->

    </a>
    <!-- <a class="navbar-brand" href="{% url 'job-list' %}">Sirf Sarkari Naukri</a> -->
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
      <i class="fas fa-thumbs-up"></i>
    </button>
    <div class="collapse navbar-collapse" id="navbarResponsive">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle py-0" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">SARKARI JOBS</a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
            <a class="dropdown-item" href="#">BY COMPANY</a>
            <hr />
            <a class="dropdown-item" href="#">BY QUALIFICATION</a>
            <a class="dropdown-item" href="#">BY PROFESSION</a>
            <hr />
            <a class="dropdown-item" href="#">BY STATE</a>
            <a class="dropdown-item" href="#">BY TOP CITIES</a>
          </div>
        </li>
      </ul>
    </div>
  </div>
</nav>


问:
php java batch processing
I work in Linux. I have 3 file (about 2Gb each containing human genome sequence). I have java codes to process those files via web interface developed in PHP. The processing time is about 24 hours or even more.

How can i run the Java code from PHP so that the processing does not terminate when I close the browser.

Since the processing time is so long, it is not practicable to keep the browser open until the process get completed.

I assume it requires batch processing.

答:
May I suggest that if you have access to the source code, you can actually make use of Java RMI and the launch all your processing from within RMI. That way you can remove PHP from the equation.

Then again, if you really need the PHP to set some variables or settings before you begin, you can write those to a file before you use Java RMI to begin your processing.

If you need a tutorial on how to get RMI working you can refer to:

http://download.oracle.com/javase/tutorial/rmi/index.html

Cheers!

Title: php java batch processing