问:
Overriding SASS variables inside create-react-app
So i'm using create-react-app, and am importing a custom component:

component.js:

```<code>import './component.scss'
</code>```

component.scss:

```<code>$primary-color: black;
</code>```

demo.js:

```<code>import Component from './Components/component.js'
import './demo.scss'
...
render() => {
  return <Component />
}
</code>```

and in demo.scss:

```<code>$primary-color: red;
</code>```

I would expect that the component would be rendered using $primary-color as red, but it keeps as black.

I also tried importing demo.scss before importing Component
so, in demo.js:

```<code>import './demo.scss'
import Component from './Components/component.js'
</code>```

but i'm getting the same result

答:
SASS uses top-down compilation, so it reads top-down and will compile css with whatever variable values it has at the time it gets to those lines in the scss files.

So in the first example with demo.scss imported after component.scss, the css for component.scss will compile first using the value it had at that time for $primary-color. Once it gets to demo.scss, the value changes, but the css for the component was already compiled with the old value.

Therefore, the second order is correct for overriding default variable values.

```<code>import './demo.scss'
import Component from './Components/component.js'
</code>```

However, the issue becomes that the line in component.scss where $primary-color: black; will override the red color. So here, we can use the !default flag, which means "Only default to black if no previous value for $primary-color has been previously defined."

```<code>$primary-color: black !default;
</code>```

More info on !default flag.

Body:
So i'm using create-react-app, and am importing a custom component:

component.js:

import './component.scss'

component.scss:

$primary-color: black;

demo.js:

import Component from './Components/component.js'
import './demo.scss'
...
render() => {
  return <Component />
}

and in demo.scss:

$primary-color: red;

I would expect that the component would be rendered using $primary-color as red, but it keeps as black.

I also tried importing demo.scss before importing Component
so, in demo.js:

import './demo.scss'
import Component from './Components/component.js'

but i'm getting the same result

Body:
SASS uses top-down compilation, so it reads top-down and will compile css with whatever variable values it has at the time it gets to those lines in the scss files.

So in the first example with demo.scss imported after component.scss, the css for component.scss will compile first using the value it had at that time for $primary-color. Once it gets to demo.scss, the value changes, but the css for the component was already compiled with the old value.

Therefore, the second order is correct for overriding default variable values.

import './demo.scss'
import Component from './Components/component.js'

However, the issue becomes that the line in component.scss where $primary-color: black; will override the red color. So here, we can use the !default flag, which means "Only default to black if no previous value for $primary-color has been previously defined."

$primary-color: black !default;

More info on !default flag.


来源: stackexchange

问:
How to create an instance that can not be destroyed
Imagine I have a class: TCantBeDestroyed

Some one knows how to create a kind of instance that can't be destroyed in both cases, directly:
 CantBeDestroyed.Free;
 CantBeDestroyed.Destroy;

And can't be destroyed by cast:
 TObject(CantBeDestroyed).Free;
 TObject(CantBeDestroyed).Destroy;

Tks.

答:
You can't stop anyone calling a destructor or Free, but you can make sure that doing so has no effect:

```<code>type
  TCannotBeDestroyed = class
  public
    destructor Destroy; override;
    procedure BeforeDestruction; override;
    procedure FreeInstance; override;
  end;

destructor TCannotBeDestroyed.Destroy;
begin
  //don't call inherited
end;

procedure TCannotBeDestroyed.BeforeDestruction;
begin
  //don't call inherited
end;

procedure TCannotBeDestroyed.FreeInstance;
begin
  //don't call inherited
end;
</code>```

I can't imagine why you would want to do this though!

ContentLicense: CC BY-SA 3.0

Body:
You can't stop anyone calling a destructor or Free, but you can make sure that doing so has no effect:

type
  TCannotBeDestroyed = class
  public
    destructor Destroy; override;
    procedure BeforeDestruction; override;
    procedure FreeInstance; override;
  end;

destructor TCannotBeDestroyed.Destroy;
begin
  //don't call inherited
end;

procedure TCannotBeDestroyed.BeforeDestruction;
begin
  //don't call inherited
end;

procedure TCannotBeDestroyed.FreeInstance;
begin
  //don't call inherited
end;

I can't imagine why you would want to do this though!


问:
Capture Macro in Catia 5
I need to write a macro in Catia 5. My aim is to convert cgm files to png at the desired background color and at desired resolution. Manually I am doing it by Capture->image->options(setting resolution and background color)-> save as .

I need to do it by macro.

I can open the Capture window with CATIA.StartCommand "Capture"
but can not proceed furthermore. How can I proceed?

Thanks in advance.

HOW WE CAN USE COMMANDS WHICH ARE GIVEN IN OBJECT BROWSER IN MACRO? I AM DIRECTLY WRITING IT BUT DOES NOT WORK.

答:
Unfortunately, the Capture command does not seem to be available through the macro API. I've successfully used this workaround, however:

Sub CaptureViewport(strFileName As String, Optional intWidth As Integer = 1024, Optional intHeight As Integer = 1024)
    Dim objWindow As SpecsAndGeomWindow
    Dim objViewer As Variant ' Viewer3D
    Dim objCamera As Camera3D
    Dim objViewpoint As Variant ' Viewpoint3D
    Dim arrOldBackgroundColor(2) As Variant
    Dim intOldRenderingMode As CatRenderingMode
    Dim intOldLayout As CatSpecsAndGeomWindowLayout

    Set objWindow = CATIA.ActiveWindow
    Set objCamera = CATIA.ActiveDocument.Cameras.Item(1)
    Set objViewer = objWindow.ActiveViewer
    Set objViewpoint = objViewer.Viewpoint3D

    objViewer.GetBackgroundColor arrOldBackgroundColor
    intOldRenderingMode = objViewer.RenderingMode
    intOldLayout = objWindow.Layout
    ' This might be extended to record the old window dimensions as well

    objViewer.FullScreen = False
    objViewer.PutBackgroundColor Array(1, 1, 1) ' White
    objViewer.RenderingMode = catRenderShadingWithEdges
    objWindow.Layout = catWindowGeomOnly
    objWindow.Width = intWidth
    objWindow.Height = intHeight

    objViewpoint.PutSightDirection Array(-1, -1, -1) ' Isometric
    objViewpoint.PutUpDirection Array(0, 0, 1)
    objViewpoint.ProjectionMode = catProjectionCylindric ' Parallel projection
    objViewer.Reframe

    ' Without this, the picture is not always sized correctly
    CATIA.RefreshDisplay = True
    objViewer.Update
    objViewer.CaptureToFile catCaptureFormatBMP, strFileName
    CATIA.RefreshDisplay = False

    objViewer.PutBackgroundColor arrOldBackgroundColor
    objViewer.RenderingMode = intOldRenderingMode
    objWindow.Layout = intOldLayout
    ' This might be extended to restore the old window dimensions as well
End Sub
```

It works by temporarily changing the background color (among other things, such as spec. tree visibility, rendering mode and camera settings) and by using the CaptureToFile method. By changing the window size, you also change the dimensions of the captured image. Unfortunately, it cannot capture to PNG format (even though the interactive Capture tool can). This version instead captures to BMP. The JPEG mode compresses the picture beyond reason and is unusable. The compass will be visible in the pictures captured with this macro, if it is enabled in the interactive session.

ContentLicense: CC BY-SA 4.0

Title: Capture Macro in Catia 5

Body:
Unfortunately, the Capture command does not seem to be available through the macro API. I've successfully used this workaround, however:

Sub CaptureViewport(strFileName As String, Optional intWidth As Integer = 1024, Optional intHeight As Integer = 1024)
    Dim objWindow As SpecsAndGeomWindow
    Dim objViewer As Variant ' Viewer3D
    Dim objCamera As Camera3D
    Dim objViewpoint As Variant ' Viewpoint3D
    Dim arrOldBackgroundColor(2) As Variant
    Dim intOldRenderingMode As CatRenderingMode
    Dim intOldLayout As CatSpecsAndGeomWindowLayout

    Set objWindow = CATIA.ActiveWindow
    Set objCamera = CATIA.ActiveDocument.Cameras.Item(1)
    Set objViewer = objWindow.ActiveViewer
    Set objViewpoint = objViewer.Viewpoint3D

    objViewer.GetBackgroundColor arrOldBackgroundColor
    intOldRenderingMode = objViewer.RenderingMode
    intOldLayout = objWindow.Layout
    ' This might be extended to record the old window dimensions as well

    objViewer.FullScreen = False
    objViewer.PutBackgroundColor Array(1, 1, 1) ' White
    objViewer.RenderingMode = catRenderShadingWithEdges
    objWindow.Layout = catWindowGeomOnly
    objWindow.Width = intWidth
    objWindow.Height = intHeight

    objViewpoint.PutSightDirection Array(-1, -1, -1) ' Isometric
    objViewpoint.PutUpDirection Array(0, 0, 1)
    objViewpoint.ProjectionMode = catProjectionCylindric ' Parallel projection
    objViewer.Reframe

    ' Without this, the picture is not always sized correctly
    CATIA.RefreshDisplay = True
    objViewer.Update
    objViewer.CaptureToFile catCaptureFormatBMP, strFileName
    CATIA.RefreshDisplay = False

    objViewer.PutBackgroundColor arrOldBackgroundColor
    objViewer.RenderingMode = intOldRenderingMode
    objWindow.Layout = intOldLayout
    ' This might be extended to restore the old window dimensions as well
End Sub

It works by temporarily changing the background color (among other things, such as spec. tree visibility, rendering mode and camera settings) and by using the CaptureToFile method. By changing the window size, you also change the dimensions of the captured image. Unfortunately, it cannot capture to PNG format (even though the interactive Capture tool can). This version instead captures to BMP. The JPEG mode compresses the picture beyond reason and is unusable. The compass will be visible in the pictures captured with this macro, if it is enabled in the interactive session.


问:
Loop through files with extension also takes the next letters
For example, instead of get only .mid files, i get also .midi file and i want avoid this:

If possible, I would like to avoid using an If condition in the DO statement.

I need to use this simple for loop because it doesn't cycle in the subfolders and it's the behavior I want.

答:
Unfortunately, most commands treat *.ext as any extension beginning with .ext so as you've seen, that would include, *.extn too:

You can therefore change that first line at the command-line to either:

FOR %i IN ('Dir /B/A-D *.mid^|FindStr /IEC:".mid"') DO @ECHO %~nxi
```

<p>Or:</p>

<pre class="lang-dos prettyprint-override"><code>FOR %i IN ("*.mid") DO @IF /I "%~xi"  == ".mid" ECHO %~nxi
</code>```

You could also use a command which treats the extension properly, where.exe:

For /F Delims^=^ EOL^= %A In ('Where .:*.mid 2^>Nul') Do @Echo %~nxA
```

From a batch-file you'd double up the % characters.

Body:
Unfortunately, most commands treat *.ext as any extension beginning with .ext so as you've seen, that would include, *.extn too:

You can therefore change that first line at the command-line to either:

FOR %i IN ('Dir /B/A-D *.mid^|FindStr /IEC:".mid"') DO @ECHO %~nxi

Or:

FOR %i IN ("*.mid") DO @IF /I "%~xi"  == ".mid" ECHO %~nxi

You could also use a command which treats the extension properly, where.exe:

For /F Delims^=^ EOL^= %A In ('Where .:*.mid 2^>Nul') Do @Echo %~nxA

From a batch-file you'd double up the % characters.


问:
Are there any technical reasons that MP4 is more popular than Webm?
Not looking for opinions. I'm searching for data.

As it is now, I want to become a webM evangelist. However, I assume there are some actual technical reasons why mp4 is preferred over webm in the bigger picture. I want to know them so I can be accurate in my assessments.

I'm working on developing a broadcast video messaging graphics engine (think chyron) and using the Chromium engine like OBS does for messaging. So far the results have been excellent.

One of the best features I've found is using webm for video. I should note I am using small (640x480 max) videos as graphics that are on top off a larger full HD video.

Not only does it seem to have a better compression:quality ratio than mp4 for my use case, the most important thing is that it has full alpha support, which allows for excellent layering of video objects on top of each other in the HTML DOM, in real time, with no noticable performance hits.

Aside from it's predecessor, FLV, I can't think of another high quality, high compression codec that also supports alpha. I feel like you are stuck using pro-res 4444 or the ancient animation codec to reliable distribute video with an alpha.

So, that said, are there technical reasons why webM isn't more adopted than mp4?

I already know the obvious, that there is dedicated hardware to decode mp4. But, is there any technicality that would prevent a hardware webM decoder? I really want to understand more what the benefits of mp4 are over webM, which i assume is why it is more widely used than webM.

Thanks!

答:
You are confused. mp4 and webm (and flv) are containers, but you are comparing the attributes of the codecs they contain. For the most part, mp4 can contain every codec webm can, and dozens more. It’s also decades older, making it more accessible and more supported.

If you are trying to compare avc to vp9, the different is availability of h264 decoders in devices is much greater. Vp9 is also often decoded in software, reducing battery life. And for encoding, avc is much (much much) faster, hence much cheaper.  So the only justification is if you can encode vp9 once, and send the same copy to thousands of viewers to make up the cost in reduced bandwidth. If only a couple hundred people download the video, vp9 cost more than it saved.

Finally, change is expensive and time consuming. There must be clear and justifiable reasons to do so.


问:
Questions about the order of execution of this code snippet
So I been reading a tutorial about Javascript promises these days.

here is an example from it used to explain the macrotask queue(i.e. the event loop) and the microtask queue.

```<code>let promise = Promise.reject(new Error("Promise Failed!"));
promise.catch(err => alert('caught'));

// no error, all quiet
window.addEventListener('unhandledrejection', event => alert(event.reason));
</code>```

It says that because promise.catch catches the error so the last line, the event handler never gets to run. I can understand this. But then he tweaked this example a little bit.

```<code>let promise = Promise.reject(new Error("Promise Failed!"));
setTimeout(() => promise.catch(err => alert('caught')));

// Error: Promise Failed!
window.addEventListener('unhandledrejection', event => alert(event.reason));
</code>```

This time he says the event handler is gonna run first and catch the error and after this the promise.catch catches the error eventually.

What I do not understand about the second example is, why did the event handler run before the promise.catch?

My understanding is,

Line one, we first encounter a promise, and we put it on the microtask queue.

Line two, we have a setTimeout, we put it on the macrotask queue,

Line three, we have an event handler, and we put the handler on the macrotask queue waiting to be fired

Then, because microtask has higher priority than macrotask. We run the promise first. After it, we dequeue the first task on macrotask queue, which is the setTimeout. So from my understanding, the error should be caught by the function inside setTimeout.

Please correct me.

答:
You are wrong about step 3). The handler will be added synchronously. Then the microtask queue gets run, and the promise rejects. As no .catch handler was added yet, an unhandled rejection gets thrown.

And I think you are mixing between when a callback gets added and when a callback gets executed. Consider this case:

```<code>  (new Promise).then(function callback() { });
</code>```

The callback will be added synchronously, but it will never be called as the promise never resolves. In this case:

```<code>  Promise.resolve().then(function callback() { });
</code>```

the callback again gets added synchronously, but the promise resolution happens in a microtask, so the callback will be executed a tick later.

Body:
So I been reading a tutorial about Javascript promises these days.

here is an example from it used to explain the macrotask queue(i.e. the event loop) and the microtask queue.

let promise = Promise.reject(new Error("Promise Failed!"));
promise.catch(err => alert('caught'));

// no error, all quiet
window.addEventListener('unhandledrejection', event => alert(event.reason));

It says that because promise.catch catches the error so the last line, the event handler never gets to run. I can understand this. But then he tweaked this example a little bit.

let promise = Promise.reject(new Error("Promise Failed!"));
setTimeout(() => promise.catch(err => alert('caught')));

// Error: Promise Failed!
window.addEventListener('unhandledrejection', event => alert(event.reason));

This time he says the event handler is gonna run first and catch the error and after this the promise.catch catches the error eventually.

What I do not understand about the second example is, why did the event handler run before the promise.catch?

My understanding is,

Line one, we first encounter a promise, and we put it on the microtask queue.

Line two, we have a setTimeout, we put it on the macrotask queue,

Line three, we have an event handler, and we put the handler on the macrotask queue waiting to be fired

Then, because microtask has higher priority than macrotask. We run the promise first. After it, we dequeue the first task on macrotask queue, which is the setTimeout. So from my understanding, the error should be caught by the function inside setTimeout.

Please correct me.

Body:
You are wrong about step 3). The handler will be added synchronously. Then the microtask queue gets run, and the promise rejects. As no .catch handler was added yet, an unhandled rejection gets thrown.

And I think you are mixing between when a callback gets added and when a callback gets executed. Consider this case:

  (new Promise).then(function callback() { });

The callback will be added synchronously, but it will never be called as the promise never resolves. In this case:

  Promise.resolve().then(function callback() { });

the callback again gets added synchronously, but the promise resolution happens in a microtask, so the callback will be executed a tick later.


问:
Connect to BACnet devices with javascript through internet
I would like to have advice or resource about a project under study. The goal is to create a BMS (Building Management System) to manage some devices in a BACnet network.

Is it possible to create a web application (using javascript) which performs some ajax calls to BACnet devices through internet by sending xml requests ?

I can't find anything concrete on google. Have you ever heard about something like that ? Reading the device specifications it looks possible but what about security ? Can it be as simple as sending a POST HTTP request on a public IP address with a xml message inside ?

Thanks for your time !

答:
You can write a back-end (Web-API) web-service, to proxy your JScript (BACnet) calls, as BACnet 'service'-calls to the relevant BMS devices; in other words, it will act as your BACnet client/'A-side', with the JScript delegating all BMS calls to it, to execute (on behalf of the JScript/front-end tier).

(E.g.  The underlying C#/.NET based API of 'YABE' has been forked/separated out as it's own project, and I'd also come across a NuGet package providing another C# API, as well as there been (/still being?) the C# based husk that is 'BACnetSharp', and Java & NodeJS based offerings too.)


答:
```<code>for /f %i in ( ' dir /b *.mid^|findstr /e /i /L /c:".mid" ' ) do @echo %i
</code>```

not simple, but avoids the if statement. A simple dir filtered by findstr to find lines that /e end with /i case-insensitive, /L literal /c: constant string.

"doesn't even" implies that you actually want to scan subdirectories. To do that, add the /s switch to the dir command. Also might be advisable to add /on to the dir command to cater for FAT filesystems.

Title: Loop through files with extension also takes the next letters

Body:
For example, instead of get only .mid files, i get also .midi file and i want avoid this:

If possible, I would like to avoid using an If condition in the DO statement.

I need to use this simple for loop because it doesn't cycle in the subfolders and it's the behavior I want.

Body:
for /f %i in ( ' dir /b *.mid^|findstr /e /i /L /c:".mid" ' ) do @echo %i

not simple, but avoids the if statement. A simple dir filtered by findstr to find lines that /e end with /i case-insensitive, /L literal /c: constant string.

"doesn't even" implies that you actually want to scan subdirectories. To do that, add the /s switch to the dir command. Also might be advisable to add /on to the dir command to cater for FAT filesystems.


问:
Prolog: Creating a frequency list of another list
So, I've written a program that reads input from a .txt file in the form of 2 integers and a list of integers: the first integer is the length of the list, the second is the number of different elements, and the list is the list in question.

I then want to create a list of frequencies for the elements, like so:

```<code>List = [1, 2, 3, 1, 3, 2, 3, 1],
FreqList = [3, 2, 3].
</code>```

Here is my code:

```<code>% Create random list
createList(List) :-
length(List, 10),
maplist(random(0,4), List).

% Count the frequency of an element:
countElement(_, [], 0) :- !.
countElement(_, [], _).
countElement(Element, [Element|Tail], Counter) :-
    countElement(Element, Tail, Counter2),
    Counter is Counter2 + 1.
countElement(Element, [_|Tail], Counter) :-
    countElement(Element, Tail, Counter).

% Create frequency list:
createFreqList(_, _, Numbers, [], CurrentNumber) :-
    Numbers = CurrentNumber.
createFreqList(List, Length, Numbers, [Head|Tail], CurrentNumber) :-
    Numbers \= CurrentNumber,
    countElement(CurrentNumber, List, Head),
    CurrentNumber2 is CurrentNumber + 1,
    createFreqList(List, Length, Numbers, Tail, CurrentNumber2).

frequency(List, FreqList) :-
    createList(List),
    Numbers2 is 4,
    createFreqList(List, 10, Numbers2, FreqList, 1).
</code>```

So, on first execution the program runs ok, and it outputs the correct frequency list. However, if I input ';', instead of giving me 'false' it runs again, outputing a wrong frequency list, and that just repeats for as long as I press ';'.

答:
I would probably do something like this:

```<code>frequencies(Xs, Fs) :-
  msort(Xs,Sorted),
  glob( Sorted, [], Fs ).

glob( [], Fs, Fs ).
glob( [X|Xs], [X:N|Ts], Fs ) :-
  !,
  N1 is N+1,
  glob(Xs, [X:N1|Ts], Fs ).
glob( [X|Xs], Ts, Fs ) :-
  glob(Xs, [X:1|Ts], Fs).
</code>```

That used msort/2 to put the list in sequence.The resulting list is in descending sequence by key value — [ 3:123, 2:25, 1:321 ].

You could also do something like this:

```<code>frequencies(Xs, Fs) :- frequencies( Xs, [], Fs ).

frequencies( [],     Fs, Fs ).
frequencies( [X|Xs], Ts, Fs ) :-
  tote( X, Ts, T1),
  frequencies(Xs, T1, Fs).

tote( X, Ts, Fs ) :-
  append( Pfx, [X:N|Sfx], Ts),
  !,
  N1 is N+1,
  append( Pfx, [X:N1|Sfx], Fs).
tote( X, Ts, [X:1|Ts] ).
</code>```

I suspect that a one-time sort of the original list is probably going to be faster than repeated scans of the accumulator list.

Body:
So, I've written a program that reads input from a .txt file in the form of 2 integers and a list of integers: the first integer is the length of the list, the second is the number of different elements, and the list is the list in question.

I then want to create a list of frequencies for the elements, like so:

List = [1, 2, 3, 1, 3, 2, 3, 1],
FreqList = [3, 2, 3].

Here is my code:

% Create random list
createList(List) :-
length(List, 10),
maplist(random(0,4), List).

% Count the frequency of an element:
countElement(_, [], 0) :- !.
countElement(_, [], _).
countElement(Element, [Element|Tail], Counter) :-
    countElement(Element, Tail, Counter2),
    Counter is Counter2 + 1.
countElement(Element, [_|Tail], Counter) :-
    countElement(Element, Tail, Counter).

% Create frequency list:
createFreqList(_, _, Numbers, [], CurrentNumber) :-
    Numbers = CurrentNumber.
createFreqList(List, Length, Numbers, [Head|Tail], CurrentNumber) :-
    Numbers \= CurrentNumber,
    countElement(CurrentNumber, List, Head),
    CurrentNumber2 is CurrentNumber + 1,
    createFreqList(List, Length, Numbers, Tail, CurrentNumber2).

frequency(List, FreqList) :-
    createList(List),
    Numbers2 is 4,
    createFreqList(List, 10, Numbers2, FreqList, 1).

So, on first execution the program runs ok, and it outputs the correct frequency list. However, if I input ';', instead of giving me 'false' it runs again, outputing a wrong frequency list, and that just repeats for as long as I press ';'.

Body:
I would probably do something like this:

frequencies(Xs, Fs) :-
  msort(Xs,Sorted),
  glob( Sorted, [], Fs ).

glob( [], Fs, Fs ).
glob( [X|Xs], [X:N|Ts], Fs ) :-
  !,
  N1 is N+1,
  glob(Xs, [X:N1|Ts], Fs ).
glob( [X|Xs], Ts, Fs ) :-
  glob(Xs, [X:1|Ts], Fs).

That used msort/2 to put the list in sequence.The resulting list is in descending sequence by key value — [ 3:123, 2:25, 1:321 ].

You could also do something like this:

frequencies(Xs, Fs) :- frequencies( Xs, [], Fs ).

frequencies( [],     Fs, Fs ).
frequencies( [X|Xs], Ts, Fs ) :-
  tote( X, Ts, T1),
  frequencies(Xs, T1, Fs).

tote( X, Ts, Fs ) :-
  append( Pfx, [X:N|Sfx], Ts),
  !,
  N1 is N+1,
  append( Pfx, [X:N1|Sfx], Fs).
tote( X, Ts, [X:1|Ts] ).

I suspect that a one-time sort of the original list is probably going to be faster than repeated scans of the accumulator list.


问:
How to fix "You must feed a value for placeholder tensor" when dealing with GAN framework?
I am trying to implement a GAN with Keras (Tensorflow backend) to colorize an image. My generator has a gray-scale input image whereas my discriminator has both the gray-scale and the colored image as inputs.

How can I train my generator without having the error

"InvalidArgumentError: You must feed a value for placeholder tensor
  'input_2' with dtype float and shape [?,128,128,1] [[{{node
  input_2}}]] [[{{node metrics/acc/Mean_2}}]]"

I have tried different ways to create the combined model (used to train the generator) without success. I am using Python 3.6.7 and Keras 2.2.4.

import numpy as np

from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D, BatchNormalization, Activation, AveragePooling2D, Dense, Dropout, Flatten, Lambda, MaxPool2D, Conv2DTranspose, UpSampling2D, Concatenate, Add
from tensorflow.keras import optimizers
from keras.preprocessing import image

def combine_generator(gen1, gen2):
    while True:
        yield(gen1.next(), gen2.next())

def generator_model(input_img):
    outputs = Conv2D(3, (1, 1), activation='sigmoid') (input_img)
    model = Model(inputs=[input_img], outputs=[outputs])
    return model

def discriminator_model(output_img, input_img):
    a1 = Concatenate()([output_img, input_img])
    f1 = Flatten()(a1)
    output = Dense(1, activation='sigmoid')(f1)
    model = Model(inputs=[output_img, input_img], outputs=[output])
    return model

def generator_containing_discriminator(input_img, generator, discriminator):
    goutput = generator(input_img)
    discriminator.trainable=False
    doutput = discriminator([goutput, input_img])
    model = Model(inputs=[input_img], outputs=[doutput])
    return model

seed = 123456
input_size = 128
batch_size = 8
learning_rate = 1e-3
optimizer = optimizers.Adam(lr=learning_rate)

dir_train_img = "flowers_train"
data_gen = dict(rescale=1./255)
image_datagen = image.ImageDataGenerator(**data_gen)

color_generator_train = image_datagen.flow_from_directory(dir_train_img, batch_size=batch_size, class_mode=None, target_size=(input_size, input_size), color_mode="rgb", seed=seed)
gray_generator_train = image_datagen.flow_from_directory(dir_train_img, batch_size=batch_size, class_mode=None, target_size=(input_size, input_size), color_mode="grayscale", seed=seed)
train_generator = combine_generator(color_generator_train, gray_generator_train)

dmodel = discriminator_model(Input((input_size, input_size, 3)), Input((input_size, input_size, 1)))
dmodel.compile(optimizer=optimizer, loss="binary_crossentropy", metrics=["accuracy"])
dmodel.summary()

gmodel = generator_model(Input((input_size, input_size, 1)))
gmodel.summary()

gdmodel = generator_containing_discriminator(Input((input_size, input_size, 1)), gmodel, dmodel)
gdmodel.compile(optimizer=optimizer, loss="binary_crossentropy", metrics=["accuracy"])
gdmodel.summary()

dmodel.trainable=False

train_batch = next(train_generator)
labels2 = np.array([1]*len(train_batch[1]))
gdmodel.train_on_batch(train_batch[1], labels2)
```

As shown in the summary, the input_2 corresponds to the gray-scale input image of the discriminator, but I don't know where the problem comes from.

答:
The problem disappears when I remove the parameter metrics=["accuracy"] from the line:

gdmodel.compile(optimizer=optimizer, loss="binary_crossentropy", metrics=["accuracy"])
```

I don't know why though.

Body:
I am trying to implement a GAN with Keras (Tensorflow backend) to colorize an image. My generator has a gray-scale input image whereas my discriminator has both the gray-scale and the colored image as inputs.

How can I train my generator without having the error

"InvalidArgumentError: You must feed a value for placeholder tensor
  'input_2' with dtype float and shape [?,128,128,1] [[{{node
  input_2}}]] [[{{node metrics/acc/Mean_2}}]]"

I have tried different ways to create the combined model (used to train the generator) without success. I am using Python 3.6.7 and Keras 2.2.4.

import numpy as np

from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D, BatchNormalization, Activation, AveragePooling2D, Dense, Dropout, Flatten, Lambda, MaxPool2D, Conv2DTranspose, UpSampling2D, Concatenate, Add
from tensorflow.keras import optimizers
from keras.preprocessing import image

def combine_generator(gen1, gen2):
    while True:
        yield(gen1.next(), gen2.next())

def generator_model(input_img):
    outputs = Conv2D(3, (1, 1), activation='sigmoid') (input_img)
    model = Model(inputs=[input_img], outputs=[outputs])
    return model

def discriminator_model(output_img, input_img):
    a1 = Concatenate()([output_img, input_img])
    f1 = Flatten()(a1)
    output = Dense(1, activation='sigmoid')(f1)
    model = Model(inputs=[output_img, input_img], outputs=[output])
    return model

def generator_containing_discriminator(input_img, generator, discriminator):
    goutput = generator(input_img)
    discriminator.trainable=False
    doutput = discriminator([goutput, input_img])
    model = Model(inputs=[input_img], outputs=[doutput])
    return model

seed = 123456
input_size = 128
batch_size = 8
learning_rate = 1e-3
optimizer = optimizers.Adam(lr=learning_rate)

dir_train_img = "flowers_train"
data_gen = dict(rescale=1./255)
image_datagen = image.ImageDataGenerator(**data_gen)

color_generator_train = image_datagen.flow_from_directory(dir_train_img, batch_size=batch_size, class_mode=None, target_size=(input_size, input_size), color_mode="rgb", seed=seed)
gray_generator_train = image_datagen.flow_from_directory(dir_train_img, batch_size=batch_size, class_mode=None, target_size=(input_size, input_size), color_mode="grayscale", seed=seed)
train_generator = combine_generator(color_generator_train, gray_generator_train)

dmodel = discriminator_model(Input((input_size, input_size, 3)), Input((input_size, input_size, 1)))
dmodel.compile(optimizer=optimizer, loss="binary_crossentropy", metrics=["accuracy"])
dmodel.summary()

gmodel = generator_model(Input((input_size, input_size, 1)))
gmodel.summary()

gdmodel = generator_containing_discriminator(Input((input_size, input_size, 1)), gmodel, dmodel)
gdmodel.compile(optimizer=optimizer, loss="binary_crossentropy", metrics=["accuracy"])
gdmodel.summary()

dmodel.trainable=False

train_batch = next(train_generator)
labels2 = np.array([1]*len(train_batch[1]))
gdmodel.train_on_batch(train_batch[1], labels2)

As shown in the summary, the input_2 corresponds to the gray-scale input image of the discriminator, but I don't know where the problem comes from.

Body:
The problem disappears when I remove the parameter metrics=["accuracy"] from the line:

gdmodel.compile(optimizer=optimizer, loss="binary_crossentropy", metrics=["accuracy"])

I don't know why though.


答:
What is the raw output of this Oracle command?

If it is a list, then use -Join and use the Csv cmdlets to export to convert to a csv file.

This also would indicate that you are new or never used PowerShell before since csv use case is a daily thing. That's OK, but jump on YouTube, MSDN Channel9 and go through the videos on PowerShell, beginning/intermediate/advanced, PowerShell and Databases, PowerShell and Csv files and get ramped up to limit/avoid, misconceptions, frustrations, bad habits, etc.

It should be straightforward as doing something like this ( of course don't put passwords in scripts)...

```<code>Add-Type -Path 'C:\oracle\instantclient_10_2\odp.net\managed\common\Oracle.ManagedDataAccess.dll'

$username = "USERID"
$password = "Password"
$datasource = "HOST:PORT/Instance"

$connectionString = "User Id = $username;Password = $password;Data Source = $datasource"

$query = "SELECT DATA1, DATA2, DATA3, DATA4, DATA5, DATA6, DATA7, DATA8
FROM TABLE WHERE NOT REGEXP_LIKE (EMAIL_ID, '@domain.com','i') order by DATA2"

$connection = New-Object Oracle.ManagedDataAccess.Client.OracleConnection("$connectionString")
$connection.open()

$command = New-Object Oracle.ManagedDataAccess.Client.OracleCommand
$command.Connection = $connection
$command.CommandText = $query

$ds = New-Object system.Data.DataSet
$da = New-Object Oracle.ManagedDataAccess.Client.OracleDataAdapter($command)

[void]$da.fill($ds)

return $ds.Tables[0] |
SELECT DATA1, DATA2, DATA3, DATA4, DATA5, DATA6, DATA7, DATA8 |
Export-CSV "C:\test.csv" -NoTypeInformation

$connection.Close()
</code>```

Title: Powershell - How to export to CSV file a query with Oracle Data Provider for .NET (ODP.NET)

Body:
In Powershell, I want to export the results of a query ODP.NET to a CSV file

This is my code:

$connection = New-Object Oracle.ManagedDataAccess.Client.OracleConnection($connectionString)
$connection.open()
$cmd  = New-Object Oracle.ManagedDataAccess.Client.OracleCommand -ArgumentList $query
$cmd.Connection = $connection
$reader = $cmd.ExecuteReader()

This code is working with the correct values of $connectionString and $query variables. If I add this code I can read the correct result of my query:

    while ($reader.Read()) {

     $col1 = $reader["Col1"]
     $col2 = $reader["Col2"]
     $col3 = $reader["Col3"]
     #Write-Host $col1, $col2, $col3
    }

Those 3 columns are an example, in my real case I have many more. Then I want to export directly to a CSV file, something like this:

XXXXXXX | export-csv -Delimiter ";" -Path "E:\export.csv"

How can I do this? The expected result is a CSV file similar than this:

"4581";"6";26867;"191057";"BH02 - 26867 - ";"30/05/2019";"";"2040";1991,04;"2040";2,4;"00";"";348;"";"1";"1";"";"";"BRL";2040;"";1
"4581";"4";28313;"747990";"BH02 - 28313 - ";"30/05/2019";"";"140";137,13;"140";2,05;"00";"";459;"";"1";"1";"";"";"BRL";140;"";1
"4581";"1";28316;"881411";"BH02 - 28316 - ";"30/05/2019";"";"140";137,13;"140";2,05;"00";"";460;"";"1";"1";"";"";"BRL";140;"";1
"4581";"1";;"878676";"BH02 -  - 275650/PF19";"28/05/2019";"";"103";100,8885;"103";2,05;"00";"";305;"";"1";"1";"";"";"BRL";103;"";1
"4581";"6";28168;"006778";"BH02 - 28168 - 275714/PF19";"30/05/2019";"";"848";828,92;"848";2,25;"00";"";429;"";"1";"1";"";"";"BRL";848;"";1
"4581";"3";29080;"641559";"BH02 - 29080 - ";"30/05/2019";"";"3424,14";3338,5365;"3424,14";2,5;"00";"";488;"";"1";"1";"";"";"BRL";3424,14;"";1
"4581";"4";;"602483";"BH02 -  - 23443";"28/05/2019";"";"157";153,7815;"157";2,05;"00";"";329;"";"1";"1";"";"";"BRL";157;"";1

Body:
What is the raw output of this Oracle command?

If it is a list, then use -Join and use the Csv cmdlets to export to convert to a csv file.

This also would indicate that you are new or never used PowerShell before since csv use case is a daily thing. That's OK, but jump on YouTube, MSDN Channel9 and go through the videos on PowerShell, beginning/intermediate/advanced, PowerShell and Databases, PowerShell and Csv files and get ramped up to limit/avoid, misconceptions, frustrations, bad habits, etc.

It should be straightforward as doing something like this ( of course don't put passwords in scripts)...

Add-Type -Path 'C:\oracle\instantclient_10_2\odp.net\managed\common\Oracle.ManagedDataAccess.dll'

$username = "USERID"
$password = "Password"
$datasource = "HOST:PORT/Instance"

$connectionString = "User Id = $username;Password = $password;Data Source = $datasource"

$query = "SELECT DATA1, DATA2, DATA3, DATA4, DATA5, DATA6, DATA7, DATA8
FROM TABLE WHERE NOT REGEXP_LIKE (EMAIL_ID, '@domain.com','i') order by DATA2"

$connection = New-Object Oracle.ManagedDataAccess.Client.OracleConnection("$connectionString")
$connection.open()

$command = New-Object Oracle.ManagedDataAccess.Client.OracleCommand
$command.Connection = $connection
$command.CommandText = $query

$ds = New-Object system.Data.DataSet
$da = New-Object Oracle.ManagedDataAccess.Client.OracleDataAdapter($command)

[void]$da.fill($ds)

return $ds.Tables[0] |
SELECT DATA1, DATA2, DATA3, DATA4, DATA5, DATA6, DATA7, DATA8 |
Export-CSV "C:\test.csv" -NoTypeInformation

$connection.Close()


问:
How to collapse pandas rows for select column values to minimal combinations and map back to original rows
Context:

I have a pandas dataframe with 7 columns (taste, color, temperature, texture, shape, age_of_participant, name_of_participant).

Of the 7 columns, taste, color, temperature, texture and shape can have overlapping values across multiple rows (i.e taste could be sour for more than one row)

I'm trying to collapse all the rows into the lowest number of combinations given
 taste,color,temperature,texture and shape values while ignoring NA's ( in other words, overwriting them). The next part is to map each of these rows to the original rows.

Mock data set:

data_set = [
   {'color':'brown', 'age_of_participant':23, 'name_of_participant':'feb'},
   {'taste': 'sour', 'color':'green', 'temperature': 'hot', 'age_of_participant':16,'name_of_participant': 'joe'},
   {'taste': 'sour', 'color':'green', 'texture':'soft', 'age_of_participant':17,'name_of_participant': 'jane'},
   {'color':'green','age_of_participant':18,'name_of_participant': 'jeff'},
   {'taste': 'sweet', 'color':'red', 'age_of_participant':19,'name_of_participant': 'joke'},
   {'taste': 'sweet', 'temperature': 'cold',  'age_of_participant':20,'name_of_participant': 'jolly'},
   {'taste': 'salty', 'color':'purple', 'texture':'soft', 'age_of_participant':21,'name_of_participant': 'jupyter'},
   {'taste': 'salty', 'color':'brown', 'age_of_participant':22,'name_of_participant': 'january'}

]

import pandas as pd
import random

data_set = random.sample(data_set, k=len(data_set))

data_frame = pd.DataFrame(data_set)

print(data_frame)

   age_of_participant   color name_of_participant  taste temperature texture
0                  16   green                 joe   sour         hot     NaN
1                  17   green                jane   sour         NaN    soft
2                  18   green                jeff    NaN         NaN     NaN
3                  19     red                joke  sweet         NaN     NaN
4                  20     NaN               jolly  sweet        cold     NaN
5                  21  purple             jupyter  salty         NaN    soft
6                  22   brown             january  salty         NaN     NaN

```

<p><strong>What I've attempted:</strong></p>

<pre class="lang-py prettyprint-override"><code>
# These columns are used to do the grouping since age_of_participant and name_of_participant are unique per row

values_that_can_be_grouped = ['taste', 'color','temperature','texture']

sub_set = data_frame[values_that_can_be_grouped].drop_duplicates().reset_index(drop=False)

my_unique_set = sub_set.groupby('taste', as_index=False).first()

print(my_unique_set)

   taste  index  color temperature texture
0             2  green
1  salty      6  brown
2   sour      1  green                soft
3  sweet      4               cold

</code>```

At this point I'm not quite sure how I can map the rows above to all original rows except for indices 2,6,1,4. I checked pandas code and doesn't look like the other indices are preserved anywhere?

What I'm trying to achieve:

```<code>
   age_of_participant   color name_of_participant  taste temperature texture
0                  16   green                 joe   sour         hot    soft
1                  17   green                jane   sour         hot    soft
2                  18   green                jeff   sour         hot    soft
3                  19     red                joke  sweet        cold     NaN
4                  20     red               jolly  sweet        cold     NaN
5                  21  purple             jupyter  salty         NaN    soft
6                  22   brown             january  salty         NaN     NaN

</code>```

答:
```<code>data_frame.assign(color=data_frame.color.ffill()).groupby('color').apply(lambda x: x.ffill().bfill())
Out[1089]:
   age_of_participant   color name_of_participant  taste temperature texture
0                  16   green                 joe   sour         hot    soft
1                  17   green                jane   sour         hot    soft
2                  18   green                jeff   sour         hot    soft
3                  19     red                joke  sweet        cold     NaN
4                  20     red               jolly  sweet        cold     NaN
5                  21  purple             jupyter  salty         NaN    soft
6                  22   brown             january  salty         NaN     NaN
</code>```

Body:
Context:

I have a pandas dataframe with 7 columns (taste, color, temperature, texture, shape, age_of_participant, name_of_participant).

Of the 7 columns, taste, color, temperature, texture and shape can have overlapping values across multiple rows (i.e taste could be sour for more than one row)

I'm trying to collapse all the rows into the lowest number of combinations given
 taste,color,temperature,texture and shape values while ignoring NA's ( in other words, overwriting them). The next part is to map each of these rows to the original rows.

Mock data set:

data_set = [
   {'color':'brown', 'age_of_participant':23, 'name_of_participant':'feb'},
   {'taste': 'sour', 'color':'green', 'temperature': 'hot', 'age_of_participant':16,'name_of_participant': 'joe'},
   {'taste': 'sour', 'color':'green', 'texture':'soft', 'age_of_participant':17,'name_of_participant': 'jane'},
   {'color':'green','age_of_participant':18,'name_of_participant': 'jeff'},
   {'taste': 'sweet', 'color':'red', 'age_of_participant':19,'name_of_participant': 'joke'},
   {'taste': 'sweet', 'temperature': 'cold',  'age_of_participant':20,'name_of_participant': 'jolly'},
   {'taste': 'salty', 'color':'purple', 'texture':'soft', 'age_of_participant':21,'name_of_participant': 'jupyter'},
   {'taste': 'salty', 'color':'brown', 'age_of_participant':22,'name_of_participant': 'january'}

]

import pandas as pd
import random

data_set = random.sample(data_set, k=len(data_set))

data_frame = pd.DataFrame(data_set)

print(data_frame)

   age_of_participant   color name_of_participant  taste temperature texture
0                  16   green                 joe   sour         hot     NaN
1                  17   green                jane   sour         NaN    soft
2                  18   green                jeff    NaN         NaN     NaN
3                  19     red                joke  sweet         NaN     NaN
4                  20     NaN               jolly  sweet        cold     NaN
5                  21  purple             jupyter  salty         NaN    soft
6                  22   brown             january  salty         NaN     NaN

What I've attempted:

# These columns are used to do the grouping since age_of_participant and name_of_participant are unique per row

values_that_can_be_grouped = ['taste', 'color','temperature','texture']

sub_set = data_frame[values_that_can_be_grouped].drop_duplicates().reset_index(drop=False)

my_unique_set = sub_set.groupby('taste', as_index=False).first()

print(my_unique_set)

   taste  index  color temperature texture
0             2  green
1  salty      6  brown
2   sour      1  green                soft
3  sweet      4               cold

At this point I'm not quite sure how I can map the rows above to all original rows except for indices 2,6,1,4. I checked pandas code and doesn't look like the other indices are preserved anywhere?

What I'm trying to achieve:

   age_of_participant   color name_of_participant  taste temperature texture
0                  16   green                 joe   sour         hot    soft
1                  17   green                jane   sour         hot    soft
2                  18   green                jeff   sour         hot    soft
3                  19     red                joke  sweet        cold     NaN
4                  20     red               jolly  sweet        cold     NaN
5                  21  purple             jupyter  salty         NaN    soft
6                  22   brown             january  salty         NaN     NaN


问:
Multiple Categorical Relative Frequency Bar PLot
I want to plot multiple frequency relative proportion bar plots. Here are my categories: hsdrunk, drunk, housing. It looks something like this：

```<code>housing： 1， 2， 3， 1， 4， 3， 1， 2
drunk: 1, 0, 1, 0, 0, 0, 0, 1
hsdrunk： 1， 0， 0， 1， 0， 0， 1， 1
</code>```

I want to plot the proportional frequency of drunk by housing category, but also separated by value of hsdrunk (1 or 0).

I have been able to create something where it is proportional by housing category, but am not sure how to add additional category of "hsdrunk”。

```<code>png("Graphs/Analysis_Figure1.png")

analysis %>%

 count(housing, drunk) %>%

group_by(housing) %>%

 mutate(freq = n/sum(n)) %>%

 filter(drunk == 1) %>%

ggplot(aes(x = housing, y = freq, fill = drunk)) +

geom_bar(stat="identity", position = 'dodge')

dev.off()
</code>```

Here is my desired output:

This is my result so far:

答:
I really don't think you want to be using position = "dodge" for this. You'll have troubles with bar width and spacing and even labeling. What's made for this in ggplot2 is facet_grid(). Then most of the magic of making it look the way you want it actually happens in theme().

I walk through a full solution below. I really want you to have a sense here of the way ggplot2 was built to handle this (using facets and theme elements). In the Grammar of Graphics, this way of thinking is meant to flow very naturally.

I built it out to the extent that I did to give you some inspiration of just how it can be done with theme(). Otherwise, frankly, how else can you be sure I'm pointing you in the right direction? The theme elements, and the rest of ggplot2, get more intuitive with use. Here's to many more hours of practice.

Here's the data you provided. I added keys to your factor levels as named vectors (guessing re: what means what, based on plot positioning). You'll notice I already baked in some line breaks (\n) to the housing levels to make the plotting easy and nice.

library(tidyverse)

analysis <- tribble(
  ~housing, ~drunk, ~hsdrunk,
         1,      1,        1,
         2,      0,        0,
         3,      1,        0,
         1,      0,        1,
         4,      0,        0,
         3,      0,        0,
         1,      0,        1,
         2,      1,        1
)
housing_levels <- c(
      `1` = "Not\nAlc.-Free",
      `2` = "Assigned"      ,
      `3` = "All\nAlc.-Free",
      `4` = "Requested"
)
hsdrunk_levels <- c(
      `0` = "Low HS Drinking",
      `1` = "High HS Drinking"
)
```

<p>This is a minor tweak, but your y-axis labels are pretty specific: 0 is expressed as "0," and decimals have no leading 0s. You can do this with a custom function like this one:</p>

<pre class="lang-r prettyprint-override"><code>label_y <- function(y) {
  y <- scales::number(y, accuracy = .1)
  y[y == "0.0"] <- "0"
  sub("0.", ".", y, fixed = TRUE)
}
</code>```

I set your bar color (why not) and I even took a look at your plot background color. There are nuances I wanted to make you aware of when you're specifying a background color. (See the theme() section below.)

darkslategrey <- "#1a476f"
whitesmoke <- "#eaf2f3"
```

<p>All right, let's get down to business.</p>

<ul>
<li><code>recode_factor()</code> is a vectorized <code>switch()</code> function; it magically turns those numbers into the actual character values you want plotted. You probably won't need this with your base data, but it was useful for me. <strong>Of note</strong> here is the fact that <em>the order of your factor levels</em> determines the order on the page. By using <code>recode_factor()</code> instead of <code>recode</code>, I'm asserting the order I set in my named vectors.</li>
<li>Then I <code>group_by()</code> high school drinking and housing. Since <code>drunk</code> is encoded as 1s and 0s, it's really easy to get the proportion; just use <code>mean(drunk)</code> (not that there are any mean drunks here).</li>
<li>In the call to <code>facet_grid()</code>, I use <code>switch = "x"</code> to "switch" the label position from the top to the bottom.</li>
<li>You can tweak the distance between <code>housing</code> levels using the <code>width</code> argument of <code>geom_bar()</code>, and the distance between <code>hsdrunk</code> groups using the call to <code>expand_scale()</code> in <code>scale_x_discrete()</code>. <code>expand_scale()</code> is a pretty cool function; check out the docs for <code>expand_*_continuous()</code> and <code>expand_scale()</code> to learn more. You could also use a theme element, <code>panel.spacing</code>, to separate your groups. But you're prevented from doing that by reasons I explain below.</li>
<li>You'll see minor tweaks in the <code>scale_y_continuous()</code> statement, setting the breaks and labels the way they show up in your "desired" plot.</li>
<li>I also added the caption, and here you'll note that I'm not sure there's a sure-fire way to align it the way it's aligned in your visual. As a kludge, it does work to add a bunch of spaces till it looks right.</li>
</ul>

<p>Like I say, most of the magic happens in the <code>theme()</code> call. There are numerous ways to do this, including starting with another base theme and adding from there. All these options are documented thoroughly in the <code>theme()</code> docs, but it wouldn't be much of an answer if I just told you to read the docs, would it? I encourage you to run this code without any of the <code>theme()</code> arguments, and then add them one by one and see what they do. Here's a walk-through:</p>

<ul>
<li><code>strip.placement</code> and <code>strip.background</code> place the <code>hsdrunk</code> labels outside the x-axis with a transparent background.</li>
<li>The <em>plot</em> is the whole visual, everything that goes in your <code>png</code>. A plot can have 1 or more <em>panels</em> for data visualization; in your case there are two. <code>plot.background</code> and <code>panel.background</code> set the background colors for each.</li>
<li>But then you're left with a problem. (<strong>Note</strong>: <em>This is the nuance I mentioned</em> about background colors...) The two white panels are separated, and since the plot background is a different color the separation is really obvious. To make it look like your "desired" plot, set <code>panel.spacing</code> to 0 so they make a single, seamless, white area. Of course that also puts your groups right next to each other, but we already addressed that using <code>expand_scale()</code>.</li>
<li>You still don't have any panel gridlines, though, because the base grid is white. So set <code>panel.grid.major.y</code> to that same whitesmoke color you used for the plot background.</li>
<li><code>axis.line</code> gets you that black line at the x- and y-axes. You might be tempted to use <code>panel.border</code> for this, but <code>panel.border</code> would put lines at the top, on the right, and even between the panels.</li>
<li>Your y-axis labels are turned sideways! So you need to change their <code>angle</code> to 90°. <code>hjust = .5</code> centers them at the tick marks.</li>
<li>Speaking of tick marks, the x-axis in your final plot doesn't have them. So you'll need to use <code>axis.ticks.x</code> to remove them. You can remove the x-axis title the same way.</li>
<li>Lastly, you have your caption over on the left, which is accomplished with an <code>hjust</code> (horizontal justification) of 0.</li>
</ul>

<pre class="lang-r prettyprint-override"><code>analysis %>%
  mutate(
    housing = recode_factor(housing, !!!housing_levels),
    hsdrunk = recode_factor(hsdrunk, !!!hsdrunk_levels)
  ) %>%
  group_by(hsdrunk, housing) %>%
  summarise(drunk = mean(drunk, na.rm = TRUE)) %>%
  ggplot(aes(x = housing, y = drunk)) +
  facet_grid(cols = vars(hsdrunk), switch = "x") +
  geom_bar(stat = "identity", fill = darkslategrey, width = .7) +
  scale_x_discrete(expand = expand_scale(add = 1)) +
  scale_y_continuous(
    name   = "Proportion drunk 3 or more times in past 30 days",
    breaks = function(limits) seq(limits[1], limits[2], by = .2),
    labels = label_y,
    expand = expand_scale(mult = c(0, .05))
  ) +
  labs(caption = paste0(
      "Figure 6: Students in All Housing Types\n",
      "                 Controlling for HS Drinking"
  )) +
  theme(
    strip.placement    = "outside",
    strip.background   = element_blank(),
    plot.background    = element_rect(fill = whitesmoke),
    panel.background   = element_rect(fill = "white"),
    panel.spacing      = unit(0, "lines"),
    panel.grid.major.y = element_line(color = whitesmoke),
    axis.line          = element_line(color = "black"),
    axis.text.y        = element_text(angle = 90, hjust = .5),
    axis.ticks.x       = element_blank(),
    axis.title.x       = element_blank(),
    plot.caption       = element_text(hjust = 0)
  )
</code>```

You may not need to do all this wrangling, depending how literal you're trying to be with this desired plot. In particular, you can make it easier on yourself if you drop the background color, and if your factors are already present in your data and ordered properly. But I wanted you to have all the tools you needed to reach your stated goal with the data and parameters you presented. Happy coding!

Body:
I want to plot multiple frequency relative proportion bar plots. Here are my categories: hsdrunk, drunk, housing. It looks something like this：

housing： 1， 2， 3， 1， 4， 3， 1， 2
drunk: 1, 0, 1, 0, 0, 0, 0, 1
hsdrunk： 1， 0， 0， 1， 0， 0， 1， 1

I want to plot the proportional frequency of drunk by housing category, but also separated by value of hsdrunk (1 or 0).

I have been able to create something where it is proportional by housing category, but am not sure how to add additional category of "hsdrunk”。

png("Graphs/Analysis_Figure1.png")

analysis %>%

 count(housing, drunk) %>%

group_by(housing) %>%

 mutate(freq = n/sum(n)) %>%

 filter(drunk == 1) %>%

ggplot(aes(x = housing, y = freq, fill = drunk)) +

geom_bar(stat="identity", position = 'dodge')

dev.off()

Here is my desired output:

This is my result so far:

Body:
I really don't think you want to be using position = "dodge" for this. You'll have troubles with bar width and spacing and even labeling. What's made for this in ggplot2 is facet_grid(). Then most of the magic of making it look the way you want it actually happens in theme().

I walk through a full solution below. I really want you to have a sense here of the way ggplot2 was built to handle this (using facets and theme elements). In the Grammar of Graphics, this way of thinking is meant to flow very naturally.

I built it out to the extent that I did to give you some inspiration of just how it can be done with theme(). Otherwise, frankly, how else can you be sure I'm pointing you in the right direction? The theme elements, and the rest of ggplot2, get more intuitive with use. Here's to many more hours of practice.

Here's the data you provided. I added keys to your factor levels as named vectors (guessing re: what means what, based on plot positioning). You'll notice I already baked in some line breaks (\n) to the housing levels to make the plotting easy and nice.

library(tidyverse)

analysis <- tribble(
  ~housing, ~drunk, ~hsdrunk,
         1,      1,        1,
         2,      0,        0,
         3,      1,        0,
         1,      0,        1,
         4,      0,        0,
         3,      0,        0,
         1,      0,        1,
         2,      1,        1
)
housing_levels <- c(
      `1` = "Not\nAlc.-Free",
      `2` = "Assigned"      ,
      `3` = "All\nAlc.-Free",
      `4` = "Requested"
)
hsdrunk_levels <- c(
      `0` = "Low HS Drinking",
      `1` = "High HS Drinking"
)

This is a minor tweak, but your y-axis labels are pretty specific: 0 is expressed as "0," and decimals have no leading 0s. You can do this with a custom function like this one:

label_y <- function(y) {
  y <- scales::number(y, accuracy = .1)
  y[y == "0.0"] <- "0"
  sub("0.", ".", y, fixed = TRUE)
}

I set your bar color (why not) and I even took a look at your plot background color. There are nuances I wanted to make you aware of when you're specifying a background color. (See the theme() section below.)

darkslategrey <- "#1a476f"
whitesmoke <- "#eaf2f3"

All right, let's get down to business.

recode_factor() is a vectorized switch() function; it magically turns those numbers into the actual character values you want plotted. You probably won't need this with your base data, but it was useful for me. Of note here is the fact that the order of your factor levels determines the order on the page. By using recode_factor() instead of recode, I'm asserting the order I set in my named vectors.

Then I group_by() high school drinking and housing. Since drunk is encoded as 1s and 0s, it's really easy to get the proportion; just use mean(drunk) (not that there are any mean drunks here).

In the call to facet_grid(), I use switch = "x" to "switch" the label position from the top to the bottom.

You can tweak the distance between housing levels using the width argument of geom_bar(), and the distance between hsdrunk groups using the call to expand_scale() in scale_x_discrete(). expand_scale() is a pretty cool function; check out the docs for expand_*_continuous() and expand_scale() to learn more. You could also use a theme element, panel.spacing, to separate your groups. But you're prevented from doing that by reasons I explain below.

You'll see minor tweaks in the scale_y_continuous() statement, setting the breaks and labels the way they show up in your "desired" plot.

I also added the caption, and here you'll note that I'm not sure there's a sure-fire way to align it the way it's aligned in your visual. As a kludge, it does work to add a bunch of spaces till it looks right.

Like I say, most of the magic happens in the theme() call. There are numerous ways to do this, including starting with another base theme and adding from there. All these options are documented thoroughly in the theme() docs, but it wouldn't be much of an answer if I just told you to read the docs, would it? I encourage you to run this code without any of the theme() arguments, and then add them one by one and see what they do. Here's a walk-through:

strip.placement and strip.background place the hsdrunk labels outside the x-axis with a transparent background.

The plot is the whole visual, everything that goes in your png. A plot can have 1 or more panels for data visualization; in your case there are two. plot.background and panel.background set the background colors for each.

But then you're left with a problem. (Note: This is the nuance I mentioned about background colors...) The two white panels are separated, and since the plot background is a different color the separation is really obvious. To make it look like your "desired" plot, set panel.spacing to 0 so they make a single, seamless, white area. Of course that also puts your groups right next to each other, but we already addressed that using expand_scale().

You still don't have any panel gridlines, though, because the base grid is white. So set panel.grid.major.y to that same whitesmoke color you used for the plot background.

axis.line gets you that black line at the x- and y-axes. You might be tempted to use panel.border for this, but panel.border would put lines at the top, on the right, and even between the panels.

Your y-axis labels are turned sideways! So you need to change their angle to 90°. hjust = .5 centers them at the tick marks.

Speaking of tick marks, the x-axis in your final plot doesn't have them. So you'll need to use axis.ticks.x to remove them. You can remove the x-axis title the same way.

Lastly, you have your caption over on the left, which is accomplished with an hjust (horizontal justification) of 0.

analysis %>%
  mutate(
    housing = recode_factor(housing, !!!housing_levels),
    hsdrunk = recode_factor(hsdrunk, !!!hsdrunk_levels)
  ) %>%
  group_by(hsdrunk, housing) %>%
  summarise(drunk = mean(drunk, na.rm = TRUE)) %>%
  ggplot(aes(x = housing, y = drunk)) +
  facet_grid(cols = vars(hsdrunk), switch = "x") +
  geom_bar(stat = "identity", fill = darkslategrey, width = .7) +
  scale_x_discrete(expand = expand_scale(add = 1)) +
  scale_y_continuous(
    name   = "Proportion drunk 3 or more times in past 30 days",
    breaks = function(limits) seq(limits[1], limits[2], by = .2),
    labels = label_y,
    expand = expand_scale(mult = c(0, .05))
  ) +
  labs(caption = paste0(
      "Figure 6: Students in All Housing Types\n",
      "                 Controlling for HS Drinking"
  )) +
  theme(
    strip.placement    = "outside",
    strip.background   = element_blank(),
    plot.background    = element_rect(fill = whitesmoke),
    panel.background   = element_rect(fill = "white"),
    panel.spacing      = unit(0, "lines"),
    panel.grid.major.y = element_line(color = whitesmoke),
    axis.line          = element_line(color = "black"),
    axis.text.y        = element_text(angle = 90, hjust = .5),
    axis.ticks.x       = element_blank(),
    axis.title.x       = element_blank(),
    plot.caption       = element_text(hjust = 0)
  )

You may not need to do all this wrangling, depending how literal you're trying to be with this desired plot. In particular, you can make it easier on yourself if you drop the background color, and if your factors are already present in your data and ordered properly. But I wanted you to have all the tools you needed to reach your stated goal with the data and parameters you presented. Happy coding!


问:
Simple slopes test for merMod object with R package interactions (jtools)
I'm trying to conduct a simple slopes analysis for a mixed effects model obtained with lmer.

The model is similar to the following:

```<code>data(Orthodont,package="nlme")
mod <- lme4::lmer(distance ~ age*Sex + (1|Subject), data=Orthodont)
</code>```

When trying to conduct a simple slopes analysis with the function sim_slopes in the package interactions, I obtain the following error message.

```<code>interactions::sim_slopes(model=mod, pred=age, modx=Sex)
</code>```

Error: One of the requested columns does not exist.

  Backtrace:

  1. interactions::sim_slopes(model = mod, pred = age, modx = Sex)

  5. jtools:::summ.merMod(...)

  6. jtools:::create_table(...)

  In addition: Warning message:

  Johnson-Neyman intervals are not available for factor moderators.

Would any one have any thoughts on what the problem might be?

Note that it works well with the package reghelper, but I need p values for these tests, which reghelper does not provide.

```<code>reghelper::simple_slopes(mod)
</code>```

The output of sessionInfo() is:

R version 3.6.0 (2019-04-26)
  Platform: x86_64-pc-linux-gnu (64-bit) Running under: Ubuntu 18.04.2
  LTS

Matrix products: default BLAS:

  /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1 LAPACK:
  /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1

locale:  [1] LC_CTYPE=en_CA.UTF-8       LC_NUMERIC=C

  LC_TIME=en_CA.UTF-8         [4] LC_COLLATE=en_CA.UTF-8

  LC_MONETARY=en_CA.UTF-8    LC_MESSAGES=en_CA.UTF-8     [7]
  LC_PAPER=en_CA.UTF-8       LC_NAME=C                  LC_ADDRESS=C

  [10] LC_TELEPHONE=C             LC_MEASUREMENT=en_CA.UTF-8
  LC_IDENTIFICATION=C

attached base packages: [1] stats     graphics  grDevices utils

  datasets  methods   base

loaded via a namespace (and not attached):

  [1] Rcpp_1.0.1        magrittr_1.5       splines_3.6.0      MASS_7.3-51.1

  [5] munsell_0.5.0      colorspace_1.4-1   lattice_0.20-38    rlang_0.3.4

  [9] minqa_1.2.4        plyr_1.8.4         tools_3.6.0       grid_3.6.0

  [13] gtable_0.3.0       nlme_3.1-140       cli_1.1.0          assertthat_0.2.1

  [17] digest_0.6.19      lme4_1.1-21        lazyeval_0.2.2     tibble_2.1.2

  [21] crayon_1.3.4       Matrix_1.2-17      reghelper_0.3.4    nloptr_1.2.1

[25] ggplot2_3.1.1      interactions_1.1.0 jtools_2.0.1       pander_0.6.3

  [29] compiler_3.6.0     pillar_1.4.1       scales_1.0.0       boot_1.3-20

  [33] pkgconfig_2.0.2

答:
(Not an answer but way too long for a comment.  Will delete later if appropriate.)

In a clean R session, this works for me:

```<code>data(Orthodont,package="nlme")
mod <- lme4::lmer(distance ~ age*Sex + (1|Subject), data=Orthodont)
interactions::sim_slopes(model=mod, pred=age, modx=Sex)
sessionInfo()
</code>```

SIMPLE SLOPES ANALYSIS

  Slope of age when Sex = Female:

   Est.   S.E.    t val.      p

  ------ ------ -------- ------

   0.48   0.09     5.13   0.00

  Slope of age when Sex = Male:

   Est.   S.E.   t val.      p

  ------ ------ -------- ------

    0.78   0.08    10.12   0.00

  Warning message:
  Johnson-Neyman intervals are not available for factor moderators.

Here is my sessionInfo(): the important stuff looks the same as yours (lme4 1.1-21, interactions 1.1.0, jtools 2.0.1), but it's certainly not identical ... ??

```<code>R Under development (unstable) (2019-05-21 r76566)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.6 LTS

[matrix product and locale info deleted]

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.1         magrittr_1.5       splines_3.7.0      MASS_7.3-51.4
 [5] tidyselect_0.2.5   munsell_0.5.0      colorspace_1.4-1   lattice_0.20-38
 [9] R6_2.4.0           rlang_0.3.4        minqa_1.2.4        plyr_1.8.4
[13] dplyr_0.8.1        tools_3.7.0        grid_3.7.0         gtable_0.3.0
[17] nlme_3.1-140       cli_1.1.0          digest_0.6.19      assertthat_0.2.1
[21] lme4_1.1-21        lazyeval_0.2.2     tibble_2.1.2       numDeriv_2016.8-1
[25] crayon_1.3.4       Matrix_1.2-17      purrr_0.3.2        nloptr_1.2.1
[29] ggplot2_3.1.1      jtools_2.0.1       interactions_1.1.0 glue_1.3.1
[33] pander_0.6.3       compiler_3.7.0     pillar_1.4.1       scales_1.0.0
[37] lmerTest_3.1-0     boot_1.3-22        pkgconfig_2.0.2
</code>```

Body:
I'm trying to conduct a simple slopes analysis for a mixed effects model obtained with lmer.

The model is similar to the following:

data(Orthodont,package="nlme")
mod <- lme4::lmer(distance ~ age*Sex + (1|Subject), data=Orthodont)

When trying to conduct a simple slopes analysis with the function sim_slopes in the package interactions, I obtain the following error message.

interactions::sim_slopes(model=mod, pred=age, modx=Sex)

Error: One of the requested columns does not exist.

  Backtrace:

  1. interactions::sim_slopes(model = mod, pred = age, modx = Sex)

  5. jtools:::summ.merMod(...)

  6. jtools:::create_table(...)

  In addition: Warning message:

  Johnson-Neyman intervals are not available for factor moderators.

Would any one have any thoughts on what the problem might be?

Note that it works well with the package reghelper, but I need p values for these tests, which reghelper does not provide.

reghelper::simple_slopes(mod)

The output of sessionInfo() is:

R version 3.6.0 (2019-04-26)
  Platform: x86_64-pc-linux-gnu (64-bit) Running under: Ubuntu 18.04.2
  LTS

Matrix products: default BLAS:

  /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1 LAPACK:
  /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1

locale:  [1] LC_CTYPE=en_CA.UTF-8       LC_NUMERIC=C

  LC_TIME=en_CA.UTF-8         [4] LC_COLLATE=en_CA.UTF-8

  LC_MONETARY=en_CA.UTF-8    LC_MESSAGES=en_CA.UTF-8     [7]
  LC_PAPER=en_CA.UTF-8       LC_NAME=C                  LC_ADDRESS=C

  [10] LC_TELEPHONE=C             LC_MEASUREMENT=en_CA.UTF-8
  LC_IDENTIFICATION=C

attached base packages: [1] stats     graphics  grDevices utils

  datasets  methods   base

loaded via a namespace (and not attached):

  [1] Rcpp_1.0.1        magrittr_1.5       splines_3.6.0      MASS_7.3-51.1

  [5] munsell_0.5.0      colorspace_1.4-1   lattice_0.20-38    rlang_0.3.4

  [9] minqa_1.2.4        plyr_1.8.4         tools_3.6.0       grid_3.6.0

  [13] gtable_0.3.0       nlme_3.1-140       cli_1.1.0          assertthat_0.2.1

  [17] digest_0.6.19      lme4_1.1-21        lazyeval_0.2.2     tibble_2.1.2

  [21] crayon_1.3.4       Matrix_1.2-17      reghelper_0.3.4    nloptr_1.2.1

[25] ggplot2_3.1.1      interactions_1.1.0 jtools_2.0.1       pander_0.6.3

  [29] compiler_3.6.0     pillar_1.4.1       scales_1.0.0       boot_1.3-20

  [33] pkgconfig_2.0.2

Body:
(Not an answer but way too long for a comment.  Will delete later if appropriate.)

In a clean R session, this works for me:

data(Orthodont,package="nlme")
mod <- lme4::lmer(distance ~ age*Sex + (1|Subject), data=Orthodont)
interactions::sim_slopes(model=mod, pred=age, modx=Sex)
sessionInfo()

SIMPLE SLOPES ANALYSIS

  Slope of age when Sex = Female:

   Est.   S.E.    t val.      p

  ------ ------ -------- ------

   0.48   0.09     5.13   0.00

  Slope of age when Sex = Male:

   Est.   S.E.   t val.      p

  ------ ------ -------- ------

    0.78   0.08    10.12   0.00

  Warning message:
  Johnson-Neyman intervals are not available for factor moderators.

Here is my sessionInfo(): the important stuff looks the same as yours (lme4 1.1-21, interactions 1.1.0, jtools 2.0.1), but it's certainly not identical ... ??

R Under development (unstable) (2019-05-21 r76566)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.6 LTS

[matrix product and locale info deleted]

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.1         magrittr_1.5       splines_3.7.0      MASS_7.3-51.4
 [5] tidyselect_0.2.5   munsell_0.5.0      colorspace_1.4-1   lattice_0.20-38
 [9] R6_2.4.0           rlang_0.3.4        minqa_1.2.4        plyr_1.8.4
[13] dplyr_0.8.1        tools_3.7.0        grid_3.7.0         gtable_0.3.0
[17] nlme_3.1-140       cli_1.1.0          digest_0.6.19      assertthat_0.2.1
[21] lme4_1.1-21        lazyeval_0.2.2     tibble_2.1.2       numDeriv_2016.8-1
[25] crayon_1.3.4       Matrix_1.2-17      purrr_0.3.2        nloptr_1.2.1
[29] ggplot2_3.1.1      jtools_2.0.1       interactions_1.1.0 glue_1.3.1
[33] pander_0.6.3       compiler_3.7.0     pillar_1.4.1       scales_1.0.0
[37] lmerTest_3.1-0     boot_1.3-22        pkgconfig_2.0.2


问:
Playing instance of AVAudioPlayer from background thread sometimes fails
I am trying to play a sound from a background thread using an instance of an AVAudioPlayer in Swift 5. Most of the time, it will be successful. But once in a while the audio player fails to play a sound.

It appears as though calling play() twice, or prepareToPlay() and then play() in a row somehow fixes the problem, but this doesn't seem like a good solution to me, as I am worried that this still doesn't guarantee that it will play successfully.

```<code>func setUpAudio() {
    AVAudioSession.sharedInstance().perform(NSSelectorFromString("setCategory:error:"), with: AVAudioSession.Category.playback)
    try! AVAudioSession.sharedInstance().setActive(true)
    NotificationCenter.default.addObserver(self, selector: #selector(handleInterruption), name: AVAudioSession.interruptionNotification, object: nil)
}

func startNewAudio() {
    let destinationData = Destinations.getDestinations()
    var audio = destinationData[currentStop]!["audio"] as! String
    if inTransit {
        audio = destinationData[Paths.tourOrder[currentIndex + 1]]!["transit_audio"] as! String
    }
    let sound = NSURL(fileURLWithPath: Bundle.main.path(forResource: audio, ofType: "mp3", inDirectory: "audio")!)
    try! audioPlayer = AVAudioPlayer(contentsOf: sound as URL)
    audioPlayer.delegate = self
    currentTime = 0
    setPlay()
}

func setPlay() {
    paused = false
    pauseButton.setImage(UIImage(named: "pause"), for: .normal)
    pauseButton.isEnabled = true
    audioPlayer.currentTime = currentTime
    DispatchQueue.global(qos: .background).async {
        self.audioPlayer.play()
        print(self.audioPlayer.isPlaying) // returns false sometimes
    }
}
</code>```

I call the methods in this order:

```<code>setUpAudio()
startNewAudio()
setPlay()
</code>```

I can't figure out the problem—I really want to just call play() once and have everything work fine.

答: There is no reason to say play on a background thread; playing a sound does not block the main thread. Moreover there is no reason to suppose that AVAudioPlayer is thread safe. And YOUR code is certainly not thread safe, as you are talking to the audio player simultaneously from different threads. So you’re using threads incorrectly.  There’s no point discussing wrong behavior results. Take away your background thread and try your code doing things the right way. If there is still a problem we can talk about that.

Body:
I am trying to play a sound from a background thread using an instance of an AVAudioPlayer in Swift 5. Most of the time, it will be successful. But once in a while the audio player fails to play a sound.

It appears as though calling play() twice, or prepareToPlay() and then play() in a row somehow fixes the problem, but this doesn't seem like a good solution to me, as I am worried that this still doesn't guarantee that it will play successfully.

func setUpAudio() {
    AVAudioSession.sharedInstance().perform(NSSelectorFromString("setCategory:error:"), with: AVAudioSession.Category.playback)
    try! AVAudioSession.sharedInstance().setActive(true)
    NotificationCenter.default.addObserver(self, selector: #selector(handleInterruption), name: AVAudioSession.interruptionNotification, object: nil)
}

func startNewAudio() {
    let destinationData = Destinations.getDestinations()
    var audio = destinationData[currentStop]!["audio"] as! String
    if inTransit {
        audio = destinationData[Paths.tourOrder[currentIndex + 1]]!["transit_audio"] as! String
    }
    let sound = NSURL(fileURLWithPath: Bundle.main.path(forResource: audio, ofType: "mp3", inDirectory: "audio")!)
    try! audioPlayer = AVAudioPlayer(contentsOf: sound as URL)
    audioPlayer.delegate = self
    currentTime = 0
    setPlay()
}

func setPlay() {
    paused = false
    pauseButton.setImage(UIImage(named: "pause"), for: .normal)
    pauseButton.isEnabled = true
    audioPlayer.currentTime = currentTime
    DispatchQueue.global(qos: .background).async {
        self.audioPlayer.play()
        print(self.audioPlayer.isPlaying) // returns false sometimes
    }
}

I call the methods in this order:

setUpAudio()
startNewAudio()
setPlay()

I can't figure out the problem—I really want to just call play() once and have everything work fine.


问:
ASP.NET Core 2.2 Master Layout Model Issue
I have a master layout in ASP.NET Core 2.2 project which uses a Model (Like other views) to create the whole website unique design, each of my views uses different Model but all of them should load in a single Layout file.
How can I pass different Models to different Views while my Layout expects a single Model?

I don't want to create tons of Layout files for each views group

for visualize:

Product.cshtml (Product Model)==> _Layout.cshtml (Product Model)

Category.cshtml (Category Model)==> _Layout.cshtml (Category Model)

But _Layout.cshtml expects only one Model

答:
There is currently no way to have _Layout.cshtml to take two different models.

The best you could do is create a base model, such as

```<code>   public class LayoutModel
   {
     public string LayoutFieldA { get; set; }
   }
</code>```

Then your page models can inherit the base model, like below

```<code>   public class ProductModel : LayoutModel
   {
     public string ProductFieldA { get; set; }
   }

   public class CategoryModel : LayoutModel
   {
     public string CategoryFieldA { get; set; }
   }
</code>```

Body:
There is currently no way to have _Layout.cshtml to take two different models.

The best you could do is create a base model, such as

   public class LayoutModel
   {
     public string LayoutFieldA { get; set; }
   }

Then your page models can inherit the base model, like below

   public class ProductModel : LayoutModel
   {
     public string ProductFieldA { get; set; }
   }

   public class CategoryModel : LayoutModel
   {
     public string CategoryFieldA { get; set; }
   }


问:
Div Wider than Viewport
I am currently coding a responsive menu using the checkbox hack and noticed that when my menu appears after clicking the hamburger icon, it is wider than the viewport. The menu has a fixed position and a flex display. I have added red borders around elements to give show this issue. Here is the relevant code:

/* General styles */
html, body { height: 100%; }
body {
  font-family: 'Miriam Libre', sans-serif;
}
a {
  color: white;
  text-decoration: none;
  transition: 0.2s;
}
a:hover {
  color: #ea3c53;
}
/* Navigation styles */
nav {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  background: #222222;
}
.donate {
  position: absolute;
  margin: 21px;
}
nav .brand {
  display: block;
  height: 70px;
  margin: 10px auto;
}
input[type=checkbox] {
  position: absolute;
  top: -9999px;
  left: -9999px;
}
nav label {
  position: absolute;
  top: 0;
  right: 0;
  padding: 21px;
  background: #63E2C6;
  cursor: pointer;
  z-index: 2;
}
nav > label > span {
  display: block;
  margin: 4px auto;
  height: 4px;
  width: 25px;
  border-radius: 1px;
  background: #ffffff;
  transition: 0.5s;
}
.menu {
  display: flex;
  position: fixed;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0;
  top: -100vh;
  left: 0;
  height: 100vh;
  width: 100%;
  background: #222;
  list-style-type: none;
  border: 1px solid red;
  transition: top 0.5s cubic-bezier(0.3, 0.1, 0.3, 0.85);
}
.menu li {
  font-size: 30px;
  border: 1px solid red;
}
input[type=checkbox]:checked ~ .menu {
  top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
    <!-- Top bar -->
    Donate
    <img src="media/logo2.png" alt="Logo" class="brand">
    <input type="checkbox" id="nav">
    <label for="nav">
      <span></span>
      <span></span>
      <span></span>
    </label>
    <ul class="menu">
      <li>Home.</li>
      <li>Mission.</li>
      <li>Contact.</li>
    </ul>
  </nav></code>```

So, my question is, why is this happening? After all, I do have the width set to 100%, not 110%.

答:
You have margin on your body element. Add:

```<code>body {
  margin: 0;
}
</code>```

There is also default margin and padding on your ul element that is also being set to width: 100%;

I recommend checking all of your primary containers, looking at them in your browser's inspector will highlight when you have additional spacing on an element that you may not be accounting for.

Title: Div Wider than Viewport

Body:
I am currently coding a responsive menu using the checkbox hack and noticed that when my menu appears after clicking the hamburger icon, it is wider than the viewport. The menu has a fixed position and a flex display. I have added red borders around elements to give show this issue. Here is the relevant code:

/* General styles */
html, body { height: 100%; }
body {
  font-family: 'Miriam Libre', sans-serif;
}
a {
  color: white;
  text-decoration: none;
  transition: 0.2s;
}
a:hover {
  color: #ea3c53;
}
/* Navigation styles */
nav {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  background: #222222;
}
.donate {
  position: absolute;
  margin: 21px;
}
nav .brand {
  display: block;
  height: 70px;
  margin: 10px auto;
}
input[type=checkbox] {
  position: absolute;
  top: -9999px;
  left: -9999px;
}
nav label {
  position: absolute;
  top: 0;
  right: 0;
  padding: 21px;
  background: #63E2C6;
  cursor: pointer;
  z-index: 2;
}
nav > label > span {
  display: block;
  margin: 4px auto;
  height: 4px;
  width: 25px;
  border-radius: 1px;
  background: #ffffff;
  transition: 0.5s;
}
.menu {
  display: flex;
  position: fixed;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0;
  top: -100vh;
  left: 0;
  height: 100vh;
  width: 100%;
  background: #222;
  list-style-type: none;
  border: 1px solid red;
  transition: top 0.5s cubic-bezier(0.3, 0.1, 0.3, 0.85);
}
.menu li {
  font-size: 30px;
  border: 1px solid red;
}
input[type=checkbox]:checked ~ .menu {
  top: 0;
}

    Donate

    <input type="checkbox" id="nav">

Home.

Mission.

Contact.

So, my question is, why is this happening? After all, I do have the width set to 100%, not 110%.

Body:
You have margin on your body element. Add:

body {
  margin: 0;
}

There is also default margin and padding on your ul element that is also being set to width: 100%;

I recommend checking all of your primary containers, looking at them in your browser's inspector will highlight when you have additional spacing on an element that you may not be accounting for.


问:
Tensorflow: create tf.NodeDef() and set attributes
I'm trying to create a new node and set its attributes.

For example printing one of the graph nodes I see that its attributes are:

```<code>attr {
  key: "T"
  value {
    type: DT_FLOAT
  }
}
</code>```

I can create a node like:

```<code>node = tf.NodeDef(name='MyConstTensor', op='Const',
                   attr={'value': tf.AttrValue(tensor=tensor_proto),
                         'dtype': tf.AttrValue(type=dt)})
</code>```

but how to add key: "T" atribute? i.e. what should be inside tf.AttrValue in this case?

Looking at attr_value.proto I have tried:

```<code>node = tf.NodeDef()
node.name = 'MySub'
node.op = 'Sub'
node.input.extend(['MyConstTensor', 'conv2'])
node.attr["key"].s = 'T' # TypeError: 'T' has type str, but expected one of: bytes
</code>```

UPDATE:

I figured out that in Tensorflow it should be written like:

```<code>node.attr["T"].type = b'float32'
</code>```

But this gives an error:

TypeError: b'float32' has type bytes, but expected one of: int, long

And I'm not sure which int value corresponds to float32.

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/attr_value.proto#L23

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/attr_value.proto#L35

答:
By trial and error I fugire out that it's just:</p>

```<code>node.attr["T"].type = 1 # to set type to float32
</code>```

Body:
I'm trying to create a new node and set its attributes.

For example printing one of the graph nodes I see that its attributes are:

attr {
  key: "T"
  value {
    type: DT_FLOAT
  }
}

I can create a node like:

node = tf.NodeDef(name='MyConstTensor', op='Const',
                   attr={'value': tf.AttrValue(tensor=tensor_proto),
                         'dtype': tf.AttrValue(type=dt)})

but how to add key: "T" atribute? i.e. what should be inside tf.AttrValue in this case?

Looking at attr_value.proto I have tried:

node = tf.NodeDef()
node.name = 'MySub'
node.op = 'Sub'
node.input.extend(['MyConstTensor', 'conv2'])
node.attr["key"].s = 'T' # TypeError: 'T' has type str, but expected one of: bytes

UPDATE:

I figured out that in Tensorflow it should be written like:

node.attr["T"].type = b'float32'

But this gives an error:

TypeError: b'float32' has type bytes, but expected one of: int, long

And I'm not sure which int value corresponds to float32.

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/attr_value.proto#L23

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/attr_value.proto#L35

Body:
By trial and error I fugire out that it's just:

node.attr["T"].type = 1 # to set type to float32


问:
How do I bind a style to my v-for loop in this example?
What am I doing wrong here?  There is no error - but there is also no style being applied when I look via dev tools.

```<code><!-- Template -->
<td v-for="steps in item.steps" v-bind:style="steps.name">
 {{ steps.name }}
</td>

// Component definition
computed: {
  endstage() {
    return {
      'background-color': '#f9f9f9',
    };
  }
}
</code>```

steps.name prints and if I bind class to steps.name that works - so not sure what I'm doing wrong with trying to bind style.

update:

In my template, I also am using this example which works fine:

```<code><!-- Template -->
<table :style="tableStyle">

// Component definition
computed: {
  tableStyle() {
    return {
      'background-color': '#f9f9f9',
      'border-color': '#C0C0C0',
      'padding': '8px',
      'color': 'red',
      'width': '100%',
      'display': 'table',
      'border': '1px solid #ddd',
    };
  }
}
</code>```

So why can I not do the same for td using steps.name which in this example results in 'endstage'?

答: It must be v-bind not v:bind.

Body:
What am I doing wrong here?  There is no error - but there is also no style being applied when I look via dev tools.

 {{ steps.name }}

// Component definition
computed: {
  endstage() {
    return {
      'background-color': '#f9f9f9',
    };
  }
}

steps.name prints and if I bind class to steps.name that works - so not sure what I'm doing wrong with trying to bind style.

update:

In my template, I also am using this example which works fine:

// Component definition
computed: {
  tableStyle() {
    return {
      'background-color': '#f9f9f9',
      'border-color': '#C0C0C0',
      'padding': '8px',
      'color': 'red',
      'width': '100%',
      'display': 'table',
      'border': '1px solid #ddd',
    };
  }
}

So why can I not do the same for td using steps.name which in this example results in 'endstage'?

Body: It must be v-bind not v:bind.


问:
Knn prediction going 100% on y_test
I'm trying to implement K-nearest neighbors on Iris dataset but after doing the predictions, yhat goes 100% without errors, there must have something wrong and i have no idea what it is...

I created a column named class_id, where i changed:

setosa = 1.0

versicolor = 2.0

virginica = 3.0

that column is type float.

Getting X an Y

```<code>
    x = df[['sepal length', 'sepal width', 'petal length', 'petal width']].values

</code>```

type(x) shows nparray

```<code>
    y = df['class_id'].values

</code>```

type(y) shows nparray

Normalizing data

```<code>
    x = preprocessing.StandardScaler().fit(x).transform(x.astype(float))

</code>```

Creating train and test

```<code>
    x_train, x_test, y_train, y_test = train_test_split(x,y,test_size = 0.2, random_state = 42)

</code>```

Checking best K value:

```<code>
    Ks = 12
    for i in range(1,Ks):
       k = i
       neigh = KNeighborsClassifier(n_neighbors=k).fit(x_train,y_train)
       yhat = neigh.predict(x_test)
       score = metrics.accuracy_score(y_test,yhat)
       print('K: ', k, ' score: ', score, '\n')

</code>```

Result:

K:  1  score:  0.9666666666666667

K:  2  score:  1.0

K:  3  score:  1.0

K:  4  score:  1.0

K:  5  score:  1.0

K:  6  score:  1.0

K:  7  score:  1.0

K:  8  score:  1.0

K:  9  score:  1.0

K:  10  score:  1.0

K:  11  score:  1.0

Printing y_test and yhat WITH K = 5

```<code>
    print(yhat)
    print(y_test)

</code>```

Result:

yhat: [2. 1. 3. 2. 2. 1. 2. 3. 2. 2. 3. 1. 1. 1. 1. 2. 3. 2. 2. 3. 1. 3. 1. 3.
3. 3. 3. 3. 1. 1.]

y_test: [2. 1. 3. 2. 2. 1. 2. 3. 2. 2. 3. 1. 1. 1. 1. 2. 3. 2. 2. 3. 1. 3. 1. 3.
3. 3. 3. 3. 1. 1.]

all of them shouldn't be 100% correct, there must be something wrong

答:
I found the answer with the explanation of skillsmuggler(user):

You are making use of the iris dataset. It's a well cleaned and model
  dataset. The features have a strong correlation to the result which
  results in the kNN model fitting the data really well. To test this
  you can reduce the size of the training set and this will results in a
  drop in the accuracy.

Prediction model was correct.

Title: Knn prediction going 100% on y_test

Body:
I'm trying to implement K-nearest neighbors on Iris dataset but after doing the predictions, yhat goes 100% without errors, there must have something wrong and i have no idea what it is...

I created a column named class_id, where i changed:

setosa = 1.0

versicolor = 2.0

virginica = 3.0

that column is type float.

Getting X an Y

    x = df[['sepal length', 'sepal width', 'petal length', 'petal width']].values

type(x) shows nparray

    y = df['class_id'].values

type(y) shows nparray

Normalizing data

    x = preprocessing.StandardScaler().fit(x).transform(x.astype(float))

Creating train and test

    x_train, x_test, y_train, y_test = train_test_split(x,y,test_size = 0.2, random_state = 42)

Checking best K value:

    Ks = 12
    for i in range(1,Ks):
       k = i
       neigh = KNeighborsClassifier(n_neighbors=k).fit(x_train,y_train)
       yhat = neigh.predict(x_test)
       score = metrics.accuracy_score(y_test,yhat)
       print('K: ', k, ' score: ', score, '\n')

Result:

K:  1  score:  0.9666666666666667

K:  2  score:  1.0

K:  3  score:  1.0

K:  4  score:  1.0

K:  5  score:  1.0

K:  6  score:  1.0

K:  7  score:  1.0

K:  8  score:  1.0

K:  9  score:  1.0

K:  10  score:  1.0

K:  11  score:  1.0

Printing y_test and yhat WITH K = 5

    print(yhat)
    print(y_test)

Result:

yhat: [2. 1. 3. 2. 2. 1. 2. 3. 2. 2. 3. 1. 1. 1. 1. 2. 3. 2. 2. 3. 1. 3. 1. 3.
3. 3. 3. 3. 1. 1.]

y_test: [2. 1. 3. 2. 2. 1. 2. 3. 2. 2. 3. 1. 1. 1. 1. 2. 3. 2. 2. 3. 1. 3. 1. 3.
3. 3. 3. 3. 1. 1.]

all of them shouldn't be 100% correct, there must be something wrong


问:
Error in bundled controller when not autowiring
Symfony documentation states that public bundles should explicitly configure their services and not rely on autowiring. As such, I am using the below to configure a Controller service in my bundle.

```<code><service id="blah\blah\SecurityController">
    <argument type="service" id="security.authentication_utils"/>
    <tag name="controller.service_arguments"/>
    <tag name="container.service_subscriber"/>
</service>
</code>```

The security argument is because I am using authenticationUtils->getLastAuthenticationError() within a login method.

However, such a service definition produces a deprecation error. User Deprecated: Auto-injection of the container for "blah\blah\SecurityController" is deprecated since Symfony 4.2. Configure it as a service instead. at /var/www/html/vendor/symfony/framework-bundle/Controller/ControllerResolver.php:64)

If I simply add autowire="true" to the service definition above, the error goes away (at which point I don't need that existing argument either). However, I would like to follow Symfony recommendations about explicit configuration.

What am I missing that is being auto-injected when autowire is set to true that I need to explicitly include?

答:
Based on the deprecation, I assume your controller is extending AbstractController.

There are two possible approaches to solve this deprecation:

If you are using functionality from AbstractController not at all or only barely, you can just not extend anything at all. If you use e.g. only one function from AbstractController, you might choose to re-implement it to reduce your dependencies. This is also mentioned in the official docs.

If you want to keep extending AbstractController, you need to inject the container manually. E.g. like this:

services.xml

```<code><service id="App\Controller\FooController">
    <call method="setContainer">
        <argument type="service" id="service_container"/>
    </call>
</service>
</code>```

FooController.php

```<code>class FooController extends AbstractController {}
</code>```

Body:
Symfony documentation states that public bundles should explicitly configure their services and not rely on autowiring. As such, I am using the below to configure a Controller service in my bundle.

<service id="blah\blah\SecurityController">
    <argument type="service" id="security.authentication_utils"/>
    <tag name="controller.service_arguments"/>
    <tag name="container.service_subscriber"/>
</service>

The security argument is because I am using authenticationUtils->getLastAuthenticationError() within a login method.

However, such a service definition produces a deprecation error. User Deprecated: Auto-injection of the container for "blah\blah\SecurityController" is deprecated since Symfony 4.2. Configure it as a service instead. at /var/www/html/vendor/symfony/framework-bundle/Controller/ControllerResolver.php:64)

If I simply add autowire="true" to the service definition above, the error goes away (at which point I don't need that existing argument either). However, I would like to follow Symfony recommendations about explicit configuration.

What am I missing that is being auto-injected when autowire is set to true that I need to explicitly include?

Body:
Based on the deprecation, I assume your controller is extending AbstractController.

There are two possible approaches to solve this deprecation:

If you are using functionality from AbstractController not at all or only barely, you can just not extend anything at all. If you use e.g. only one function from AbstractController, you might choose to re-implement it to reduce your dependencies. This is also mentioned in the official docs.

If you want to keep extending AbstractController, you need to inject the container manually. E.g. like this:

services.xml

<service id="App\Controller\FooController">
    <call method="setContainer">
        <argument type="service" id="service_container"/>
    </call>
</service>

FooController.php

class FooController extends AbstractController {}


问:
array of radio - jquery
i have the code below and it shows a list of radio buttons
My question is how i can make a list of buttons, the equivalent for this in an array mode (jquery)

```<code>  <input type="radio" name="name1" value="450" /> 450€<br />
  <input type="radio" name="name2" value="500" /> 500€<br />
  <input type="radio" name="name3" value="550" /> 550€<br />
  <input type="radio" name="name4" value="600" /> 600€<br />
  <input type="radio" name="name5" value="650" /> 650€<br />
  <input type="radio" name="name6" value="700" /> 700€<br />
</code>```

this simple make an array without change anything. And another question, how i will can access the values when i will have this in an array mode?

thanks

答:
another jQuery solution:

Live Demo

```<code><ul>
    <li id="lista"></li>
</ul>

<script type="text/javascript">
$(document).ready(function() {
    var start = 450;
    for (var x=0; x<=20; x++) {
        var item = document.createElement('input');
            $(item).attr('type', 'radio');
            $(item).attr('id', 'price'+x+1);    // numbered starting from 1
            $(item).attr('name', 'price');
            $(item).attr('value', start + (x * 50));
        var label = document.createElement('label');
            $(label).attr('for', 'price'+x+1);  // numbered starting from 1
            $(label).html(start + (x * 50) + '€');
        $('#lista').append(item);
        $('#lista').append(label);
        $('#lista').append('<br>');
    }
});
</script>
</code>```

Title: array of radio - jquery

Body:
i have the code below and it shows a list of radio buttons
My question is how i can make a list of buttons, the equivalent for this in an array mode (jquery)

  <input type="radio" name="name1" value="450" /> 450€

  <input type="radio" name="name2" value="500" /> 500€

  <input type="radio" name="name3" value="550" /> 550€

  <input type="radio" name="name4" value="600" /> 600€

  <input type="radio" name="name5" value="650" /> 650€

  <input type="radio" name="name6" value="700" /> 700€

this simple make an array without change anything. And another question, how i will can access the values when i will have this in an array mode?

thanks

Body:
another jQuery solution:

Live Demo

<ul>
    <li id="lista"></li>
</ul>

<script type="text/javascript">
$(document).ready(function() {
    var start = 450;
    for (var x=0; x<=20; x++) {
        var item = document.createElement('input');
            $(item).attr('type', 'radio');
            $(item).attr('id', 'price'+x+1);    // numbered starting from 1
            $(item).attr('name', 'price');
            $(item).attr('value', start + (x * 50));
        var label = document.createElement('label');
            $(label).attr('for', 'price'+x+1);  // numbered starting from 1
            $(label).html(start + (x * 50) + '€');
        $('#lista').append(item);
        $('#lista').append(label);
        $('#lista').append('<br>');
    }
});
</script>