问:
shinyFiles package within module
I'm having trouble using the shinyFiles package with module. When i'm using it without module it works fine. When i'm using it within module i can't dive into directories (other threads have no positive answer) :</p>

```<code>#' @export
dirModule = function(input, output, session, fileRoot = NULL) {
  root = c(C = "/")
  shinyFileChoose(input, session$ns('files'), roots = root, session = session)
  shinyDirChoose(input, session$ns("directory"),  session=session, roots = c(home = '/home', root = '/'), filetypes=c(''))
  shinyFileSave(input, session$ns("fileSave"), roots = root, session = session)

  observeEvent(input$files, { print(parseFilePaths(root, input$files)$datapath) })
  observeEvent(input$directory, { print(parseDirPath(root, input$directory)) })
  observeEvent(input$fileSave, { print(parseSavePath(root, input$fileSave)$datapath) })
}

#' @export
dirModuleUI = function(id) {
  ns = NS(id)

  fluidPage(
    fluidRow(
      shinyFilesButton(ns('files'), label='File select', title='Please select a file', multiple=T),
      shinyDirButton(ns("directory"), label="Directory select", title = "Select directory", FALSE),
      shinySaveButton(ns("fileSave"), label = "File save", title = "Save file as", filetype=list(text='txt'))
    )
  )
}
</code>```

答:
Similar post here

It is namespace issue. I stuck here multiple times in different R version and here is the solution in R 3.6.

I cannot get it work in R 3.4 because it always have problem navigate into subfolders.

```<code>#' @export
dirModule = function(input, output, session, fileRoot = NULL) {
  root = c(C = "/")
  shinyFileChoose(input, 'files', roots = root, session = session)
  shinyDirChoose(input, "directory",  session=session, roots = c(home = '/home', root = '/'), filetypes=c(''))
  shinyFileSave(input, "fileSave", roots = root, session = session)

  observeEvent(input$files, { print(parseFilePaths(root, input$files)$datapath) })
  observeEvent(input$directory, { print(parseDirPath(root, input$directory)) })
  observeEvent(input$fileSave, { print(parseSavePath(root, input$fileSave)$datapath) })
}

#' @export
dirModuleUI = function(id) {
  ns = NS(id)

  fluidPage(
    fluidRow(
      shinyFilesButton(ns('files'), label='File select', title='Please select a file', multiple=T),
      shinyDirButton(ns("directory"), label="Directory select", title = "Select directory", FALSE),
      shinySaveButton(ns("fileSave"), label = "File save", title = "Save file as", filetype=list(text='txt'))
    )
  )
}
</code>```

Title: shinyFiles package within module

Body:
I'm having trouble using the shinyFiles package with module. When i'm using it without module it works fine. When i'm using it within module i can't dive into directories (other threads have no positive answer) :

#' @export
dirModule = function(input, output, session, fileRoot = NULL) {
  root = c(C = "/")
  shinyFileChoose(input, session$ns('files'), roots = root, session = session)
  shinyDirChoose(input, session$ns("directory"),  session=session, roots = c(home = '/home', root = '/'), filetypes=c(''))
  shinyFileSave(input, session$ns("fileSave"), roots = root, session = session)

  observeEvent(input$files, { print(parseFilePaths(root, input$files)$datapath) })
  observeEvent(input$directory, { print(parseDirPath(root, input$directory)) })
  observeEvent(input$fileSave, { print(parseSavePath(root, input$fileSave)$datapath) })
}

#' @export
dirModuleUI = function(id) {
  ns = NS(id)

  fluidPage(
    fluidRow(
      shinyFilesButton(ns('files'), label='File select', title='Please select a file', multiple=T),
      shinyDirButton(ns("directory"), label="Directory select", title = "Select directory", FALSE),
      shinySaveButton(ns("fileSave"), label = "File save", title = "Save file as", filetype=list(text='txt'))
    )
  )
}

Body:
Similar post here

It is namespace issue. I stuck here multiple times in different R version and here is the solution in R 3.6.

I cannot get it work in R 3.4 because it always have problem navigate into subfolders.

#' @export
dirModule = function(input, output, session, fileRoot = NULL) {
  root = c(C = "/")
  shinyFileChoose(input, 'files', roots = root, session = session)
  shinyDirChoose(input, "directory",  session=session, roots = c(home = '/home', root = '/'), filetypes=c(''))
  shinyFileSave(input, "fileSave", roots = root, session = session)

  observeEvent(input$files, { print(parseFilePaths(root, input$files)$datapath) })
  observeEvent(input$directory, { print(parseDirPath(root, input$directory)) })
  observeEvent(input$fileSave, { print(parseSavePath(root, input$fileSave)$datapath) })
}

#' @export
dirModuleUI = function(id) {
  ns = NS(id)

  fluidPage(
    fluidRow(
      shinyFilesButton(ns('files'), label='File select', title='Please select a file', multiple=T),
      shinyDirButton(ns("directory"), label="Directory select", title = "Select directory", FALSE),
      shinySaveButton(ns("fileSave"), label = "File save", title = "Save file as", filetype=list(text='txt'))
    )
  )
}


来源: stackexchange

问:
User and his contacts belongs to and Has many Asssociation in rails
I want to manage user and his contacts with the relation or contact type can some body suggest me the correct association of it..

I want to run query some thing like user.companions and it returns list of contact list..

If there is any gem available please guide me. Thanks

```<code>class CreateContacts < ActiveRecord::Migration
  def self.up
    create_table :contacts do |t|
      t.integer :companion_id
      t.references :user
      t.timestamps
    end
  end

  def self.down
    drop_table :contacts
  end
end

class User < ActiveRecord::Base
        has_many :contacts, :dependent => :destroy
        has_many :users, :through=>:contacts, :foreign_key => :companion_id
end
class Contact < ActiveRecord::Base
  belongs_to :user
  has_many :companions, :class_name=>'User', :foreign_key => :companion_id
end
</code>```

答:
You should change your Contact model to:</p>

```<code>class Contact < ActiveRecord::Base
  belongs_to :user
  belongs_to :companion, :class_name=>'User'
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to manage user and his contacts with the relation or contact type can some body suggest me the correct association of it..

I want to run query some thing like user.companions and it returns list of contact list..

If there is any gem available please guide me. Thanks

class CreateContacts < ActiveRecord::Migration
  def self.up
    create_table :contacts do |t|
      t.integer :companion_id
      t.references :user
      t.timestamps
    end
  end

  def self.down
    drop_table :contacts
  end
end

class User < ActiveRecord::Base
        has_many :contacts, :dependent => :destroy
        has_many :users, :through=>:contacts, :foreign_key => :companion_id
end
class Contact < ActiveRecord::Base
  belongs_to :user
  has_many :companions, :class_name=>'User', :foreign_key => :companion_id
end

Body:
You should change your Contact model to:

class Contact < ActiveRecord::Base
  belongs_to :user
  belongs_to :companion, :class_name=>'User'
end


问:
How to upload file from umbraco backoffice to media section?
I am using a custom section within umbraco for displaying messages sent by users. I want the admins to be able to answer these messages by uploading a file to the message itself. This way I will know which file belongs to which message. I have followed some guides and recommendations most notably this one
file-upload-in-backoffice-custom-section on how to upload files from umbraco backoffice.

Problem with my code however is that it does not seem to send the whole file with the post request just the path of the file which becomes something similar to: C:\fakepath\file.pdf

My question would be how do I send the whole file in the post request and how can i catch/convert the file into an HttpPostedFileBase inside of the API function. If I can get the file as HttpPostedFileBase I will know how to upload it to the media section of umbraco.

Code below:

edit.html:

```<code>                    <umb-control-group label="File" description="File to upload">
                        <input type="file" class="umb-editor umb-textstring" ng-model="files" ng-change="fileSelected(files)" ng-multiple="false" />
                    </umb-control-group>
                </div>
            </div>
        </div>
    </umb-editor-container>

    <umb-editor-footer>
        <umb-editor-footer-content-right>
            <div class="umb-button ng-scope">
                <button ng-click="OnSave()" class="btn umb-button__button btn-success umb-button--">
                    <span class="umb-button__content">
                        Save
                    </span>
                </button>
            </div>
        </umb-editor-footer-content-right>
    </umb-editor-footer>
</code>```

edit.controller.js:

```<code>$scope.fileSelected = function (files) {
        $scope.file = files;
    };

    $scope.OnSave = function () {
            var request = {
                file: $scope.file
            };
            return $http({
                method: 'POST',
                url: "backoffice/Messages/MessagesApi/PostSaveFile",
                headers: { 'Content-Type': undefined },
                transformRequest: function (data) {
                    var formData = new FormData();
                    formData.append("file", data.file);
                    return formData;
                },
                data: request
            }).then(function (response) {
                if (response) {
                    var fileName = response.data;
                    return fileName;
                } else {
                    return false;
                }
            });

    };
</code>```

MessagesApiController.cs:

```<code>public HttpResponseMessage PostSaveFile(HttpPostedFileBase file)
{
    var files = HttpContext.Current.Request;

    if (files != null && files.ContentLength > 0)
    {
        StreamReader reader = new StreamReader(files.InputStream);
        string responseFromServer = reader.ReadToEnd();
    }
    return Request.CreateResponse(HttpStatusCode.OK);
}
</code>```

答:
For those of you who are struggling with file uploads in custom sections in Umbraco 8 here's my solution:

View:

```<code><input type="file" class="umb-textstring" ngf-select="" ng-model="files" ng-multiple="false" ngf-change="fileSelected(files)" required />
<umb-button action="vm.clickUploadButton()"
            type="button"
            button-style="info"
            label="Upload">
</umb-button>
</code>```

Controller:

```<code>function Controller($scope, Upload) {
    var vm = this;
    vm.clickUploadButton = clickUploadButton;

    $scope.fileSelected = function (files) {
        $scope.file = files;
    };

    function clickUploadButton() {
        if (!$scope.file)
            return false;

        Upload.upload({
            url: "backoffice/api/Upload/UploadFile",
            fields: {
                "field1": "value1",
                "field2": "value2"
            },
            file: $scope.file
        }).success(function (data, status, headers, config) {
            console.log(status);
            console.log(data);
        }).error(function (evt, status, headers, config) {
            console.log(evt.Message);
        });
    }
}
</code>```

API controller:

```<code>public class UploadController : UmbracoAuthorizedApiController
{
    [HttpPost]
    public HttpResponseMessage UploadFile()
    {
        var files = HttpContext.Current.Request.Files;
        var field1 = HttpContext.Current.Request.Form["field1"];
        var field2 = HttpContext.Current.Request.Form["field2"];

        return Request.CreateResponse(HttpStatusCode.OK, new { fileCount = files.Count, field1, field2 }) ;
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using a custom section within umbraco for displaying messages sent by users. I want the admins to be able to answer these messages by uploading a file to the message itself. This way I will know which file belongs to which message. I have followed some guides and recommendations most notably this one
file-upload-in-backoffice-custom-section on how to upload files from umbraco backoffice.

Problem with my code however is that it does not seem to send the whole file with the post request just the path of the file which becomes something similar to: C:\fakepath\file.pdf

My question would be how do I send the whole file in the post request and how can i catch/convert the file into an HttpPostedFileBase inside of the API function. If I can get the file as HttpPostedFileBase I will know how to upload it to the media section of umbraco.

Code below:

edit.html:

                    <umb-control-group label="File" description="File to upload">
                        <input type="file" class="umb-editor umb-textstring" ng-model="files" ng-change="fileSelected(files)" ng-multiple="false" />
                    </umb-control-group>

    </umb-editor-container>

    <umb-editor-footer>
        <umb-editor-footer-content-right>

                <button ng-click="OnSave()" class="btn umb-button__button btn-success umb-button--">

                        Save

                </button>

        </umb-editor-footer-content-right>
    </umb-editor-footer>

edit.controller.js:

$scope.fileSelected = function (files) {
        $scope.file = files;
    };

    $scope.OnSave = function () {
            var request = {
                file: $scope.file
            };
            return $http({
                method: 'POST',
                url: "backoffice/Messages/MessagesApi/PostSaveFile",
                headers: { 'Content-Type': undefined },
                transformRequest: function (data) {
                    var formData = new FormData();
                    formData.append("file", data.file);
                    return formData;
                },
                data: request
            }).then(function (response) {
                if (response) {
                    var fileName = response.data;
                    return fileName;
                } else {
                    return false;
                }
            });

    };

MessagesApiController.cs:

public HttpResponseMessage PostSaveFile(HttpPostedFileBase file)
{
    var files = HttpContext.Current.Request;

    if (files != null && files.ContentLength > 0)
    {
        StreamReader reader = new StreamReader(files.InputStream);
        string responseFromServer = reader.ReadToEnd();
    }
    return Request.CreateResponse(HttpStatusCode.OK);
}

Body:
For those of you who are struggling with file uploads in custom sections in Umbraco 8 here's my solution:

View:

<input type="file" class="umb-textstring" ngf-select="" ng-model="files" ng-multiple="false" ngf-change="fileSelected(files)" required />
<umb-button action="vm.clickUploadButton()"
            type="button"
            button-style="info"
            label="Upload">
</umb-button>

Controller:

function Controller($scope, Upload) {
    var vm = this;
    vm.clickUploadButton = clickUploadButton;

    $scope.fileSelected = function (files) {
        $scope.file = files;
    };

    function clickUploadButton() {
        if (!$scope.file)
            return false;

        Upload.upload({
            url: "backoffice/api/Upload/UploadFile",
            fields: {
                "field1": "value1",
                "field2": "value2"
            },
            file: $scope.file
        }).success(function (data, status, headers, config) {
            console.log(status);
            console.log(data);
        }).error(function (evt, status, headers, config) {
            console.log(evt.Message);
        });
    }
}

API controller:

public class UploadController : UmbracoAuthorizedApiController
{
    [HttpPost]
    public HttpResponseMessage UploadFile()
    {
        var files = HttpContext.Current.Request.Files;
        var field1 = HttpContext.Current.Request.Form["field1"];
        var field2 = HttpContext.Current.Request.Form["field2"];

        return Request.CreateResponse(HttpStatusCode.OK, new { fileCount = files.Count, field1, field2 }) ;
    }
}


问:
How can I add an element to a list using the delete1() predicate in prolog?
I need to add an element to a list using the delete1 predicate that I have written:

```<code>delete1(H,[H|T],T).
delete1(H,[D|X],[D|Y]):-delete1(H,X,Y).
</code>```

How can I do that? Well, I know how to delete element but can't figure out how to add an element there. I need to show all the possible lists that will be the result of adding 56 to [x,y,z,a] list. Do you have any ideas?

答:
If they are well-programmed, Prolog predicates can run "backwards":

f(X,Y) should be read as X is related to Y via f.

Given an x, on can compute the Y (possibly several Y via backtracking): f(x,Y) is interpreted as The set of Y such that: f(x) = Y.

Given a y, on can compute the X (possibly several X via backtracking): f(X,y) is interpreted as The set of X such that: f(X) = y.

Given an (x,y), on can compute the truth value: f(x,y) interpreted as true if (but not iff) f(x) == y.

(How many Prolog predicates are "well-programmed"? If there is a study about how many Prolog predicates written outside of the classroom can work bidirectionally I would like to know about it; my guess is most decay quickly into unidirectional functions, it's generally not worth the hassle of adding the edge cases and the test code to make predicates work bidirectionally)

The above works best if

f is bijective, i.e.: "no information is thrown away when computing in either direction"

the computation in both directions is tractable (having encryption work backwards is hard)

So, in this case:

delete(Element,ListWith,ListWithout) relates the three arguments (Element,ListWith,ListWithout) as follows:

ListWithout is ListWith without Element.

Note that "going forward" from (Element,ListWith) to ListWithout destroys information, namely the exact position of the deleted element, or even if there was one in the first place. BAD! NOT BIJECTIVE!

To make delete1/3 run backwards we just have to:

```<code>?- delete1(56,L,[a,b,c]).
L = [56, a, b, c] ;
L = [a, 56, b, c] ;
L = [a, b, 56, c] ;
L = [a, b, c, 56] ;
</code>```

There are four solutions to the reverse deletion problem.

And the program misses one:

```<code>L = [a, b, c]
</code>```

or even a few more:

```<code>L = [56, a, b, 56, c]
</code>```

etc.

As you can see, it is important to retain information!

Body:
I need to add an element to a list using the delete1 predicate that I have written:

delete1(H,[H|T],T).
delete1(H,[D|X],[D|Y]):-delete1(H,X,Y).

How can I do that? Well, I know how to delete element but can't figure out how to add an element there. I need to show all the possible lists that will be the result of adding 56 to [x,y,z,a] list. Do you have any ideas?

Body:
If they are well-programmed, Prolog predicates can run "backwards":

f(X,Y) should be read as X is related to Y via f.

Given an x, on can compute the Y (possibly several Y via backtracking): f(x,Y) is interpreted as The set of Y such that: f(x) = Y.

Given a y, on can compute the X (possibly several X via backtracking): f(X,y) is interpreted as The set of X such that: f(X) = y.

Given an (x,y), on can compute the truth value: f(x,y) interpreted as true if (but not iff) f(x) == y.

(How many Prolog predicates are "well-programmed"? If there is a study about how many Prolog predicates written outside of the classroom can work bidirectionally I would like to know about it; my guess is most decay quickly into unidirectional functions, it's generally not worth the hassle of adding the edge cases and the test code to make predicates work bidirectionally)

The above works best if

f is bijective, i.e.: "no information is thrown away when computing in either direction"

the computation in both directions is tractable (having encryption work backwards is hard)

So, in this case:

delete(Element,ListWith,ListWithout) relates the three arguments (Element,ListWith,ListWithout) as follows:

ListWithout is ListWith without Element.

Note that "going forward" from (Element,ListWith) to ListWithout destroys information, namely the exact position of the deleted element, or even if there was one in the first place. BAD! NOT BIJECTIVE!

To make delete1/3 run backwards we just have to:

?- delete1(56,L,[a,b,c]).
L = [56, a, b, c] ;
L = [a, 56, b, c] ;
L = [a, b, 56, c] ;
L = [a, b, c, 56] ;

There are four solutions to the reverse deletion problem.

And the program misses one:

L = [a, b, c]

or even a few more:

L = [56, a, b, 56, c]

etc.

As you can see, it is important to retain information!


问:
R susbet matching "ANY" (union)
I'm attempting to subset from mtcars, such that the rows have a specific column which matches ANY of several values, stored in a list.

```<code>cylChoices = c(4,6)
subset(mtcars,cyl==cylChoices[1] | cyl== cylChoices[2])
</code>```

However, I'd like to do when cylChoices is of arbitrary length.

I've gotten close to this with for loops, but this results in what feels like unnecessarily long code, for example:

```<code>cars = list()
cylChoices = c(4,6)
count = 1
for(tempChoice in cylChoices){
count =count+1
cars[[count]] = subset(mtcars,cyl==tempChoice)
}
</code>```

This doesn't produce the same result, but it's getting closer.

Is there any way to match a subset easily?

Thank you very much for your time!

Title: R susbet matching "ANY" (union)

Body:
I'm attempting to subset from mtcars, such that the rows have a specific column which matches ANY of several values, stored in a list.

cylChoices = c(4,6)
subset(mtcars,cyl==cylChoices[1] | cyl== cylChoices[2])

However, I'd like to do when cylChoices is of arbitrary length.

I've gotten close to this with for loops, but this results in what feels like unnecessarily long code, for example:

cars = list()
cylChoices = c(4,6)
count = 1
for(tempChoice in cylChoices){
count =count+1
cars[[count]] = subset(mtcars,cyl==tempChoice)
}

This doesn't produce the same result, but it's getting closer.

Is there any way to match a subset easily?

Thank you very much for your time!

Body:
We can use the %in% operator to subset the data as requested in the OP.

cylChoices = c(4,6)
subset(mtcars,cyl %in% cylChoices)

...and the first few rows of output:

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4      21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710     22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Valiant        18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Merc 240D      24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230       22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280       19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
Merc 280C      17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4

`%in% can also be used with the extract operator, such as:

mtcars[mtcars$cyl %in% cylChoices,]


问:
Rials Routing Error:Because of Controller name different from model name?
everyone! I am new to rails and working on Codecademy tutorials. But I wanted to see if I can run the same app on my mac using VS Code and got into some roadblocks. The application is basically to create a form that takes in messages and displays it (in the index view). I wanted to explore changing the names of controller and model to what I want and guess I messed up the internal routing. Following is the controller (messagec)

```<code>class MessagecController < ApplicationController

    def index
        @messages1 = MessagesMo1.all
    end

    def new
        @messages2 = MessagesMo1.new
    end

    def create
        @messages2 = MessagesMo1.new(message_params)
        if @messages2.save #tells if the object is saved successfully in db or not
           flash[:success] = "Great! Your post has been created!"
           redirect_to '/messages'
        else
          flash.now[:error] = "Fix your mistakes, please."
          render 'new'
        end
    end

    private
    def message_params
      params.require(:message).permit(:content)
    end
end
</code>```

THe following is the model (messagesmo1)

```<code>class CreateMessagesMo1s < ActiveRecord::Migration[6.0]
  def change
    create_table :messages_mo1s do |t|
      t.text :content
      t.timestamps
    end
  end
end
</code>```

The following is the routes.rb file

```<code>get '/messages' => 'messagec#index'
get '/messages/new' => 'messagec#new'
post 'messages' => 'messagec#create'
post 'messages_mo1s' => 'message_mo1s#create'
</code>```

The following is the code in create.html.erb file

```<code>    <%= form_for(@messages2) do |f| %>
    <div class = "field">
        <%= f.label :message %><br>
        <%= f.text_area :content %>
    </div>
    <div class = "actions">
    <%= f.submit "Create" %>
    </div>
    <% end %>
</code>```

I am able to see the message list and able to go to create new message page. But when I submit the form, I am getting the following Routing error:

uninitialized constant MessageMo1sController Did you mean? MessagecController MessagesMController

My first questions is:
1) What am I missing in the routes.rb file?
2) Is there any rule between naming the model similar to that of the controller?

答:
I just replicated all of the above, I think there are many things to keep in mind.

Your model file must be of name messagesmo1.rb and in this model:

class MessagesMo1 < ApplicationRecord
end
```</li>
<li><p>Your controller file should be of name <code>messagec_controller.rb</code> and in it:</p>

<pre class="lang-rb prettyprint-override"><code>def index
  @messages1 = MessagesMo1.all
end

def new
  @messages2 = MessagesMo1.new
end

def create
  @messages2 = MessagesMo1.new(message_params)
  if @messages2.save #tells if the object is saved successfully in db or not
    flash[:success] = "Great! Your post has been created!"
    redirect_to '/messages'
  else

    flash.now[:error] = "Fix your mistakes, please."
    redirect_to '/messages/new'
  end
end

private
def message_params
  params.require(:messages_mo1).permit(:content)
end
</code>```

In the above point, look at the message_params part, it must be :messages_mo1 and not :message

No changes required in _form.html.erb file

Your migration file must be of name timestamp__create_messages_mo1s.rb and it must have:

class CreateMessagesMo1s < ActiveRecord::Migration[6.0]
  def change
    create_table :messages_mo1s do |t|
      t.text :content

      t.timestamps
    end
  end
end
```</li>
<li><p>In your <code>routes.rb</code> file, change the last route:</p>

<pre class="lang-rb prettyprint-override"><code>get '/messages' => 'messagec#index'
get '/messages/new' => 'messagec#new'
post 'messages' => 'messagec#create'
post 'messages_mo1s' => 'messagec#create'
</code>```

Make sure all your links are updated in index.html.erb, in show.html.erb and in new.html.erb -> Like links to show, delete, edit etc. Or if your just testing remove these links.

After making above changes, run rails db:drop db:create db:migrate as it will clean your DB of old migration.

That's it, now everything should work. The main problem is naming convention should be standard across all files. So it's better to use standard convention.

Body:
everyone! I am new to rails and working on Codecademy tutorials. But I wanted to see if I can run the same app on my mac using VS Code and got into some roadblocks. The application is basically to create a form that takes in messages and displays it (in the index view). I wanted to explore changing the names of controller and model to what I want and guess I messed up the internal routing. Following is the controller (messagec)

class MessagecController < ApplicationController

    def index
        @messages1 = MessagesMo1.all
    end

    def new
        @messages2 = MessagesMo1.new
    end

    def create
        @messages2 = MessagesMo1.new(message_params)
        if @messages2.save #tells if the object is saved successfully in db or not
           flash[:success] = "Great! Your post has been created!"
           redirect_to '/messages'
        else
          flash.now[:error] = "Fix your mistakes, please."
          render 'new'
        end
    end

    private
    def message_params
      params.require(:message).permit(:content)
    end
end

THe following is the model (messagesmo1)

class CreateMessagesMo1s < ActiveRecord::Migration[6.0]
  def change
    create_table :messages_mo1s do |t|
      t.text :content
      t.timestamps
    end
  end
end

The following is the routes.rb file

get '/messages' => 'messagec#index'
get '/messages/new' => 'messagec#new'
post 'messages' => 'messagec#create'
post 'messages_mo1s' => 'message_mo1s#create'

The following is the code in create.html.erb file

    <%= form_for(@messages2) do |f| %>

        <%= f.label :message %>

        <%= f.text_area :content %>

    <%= f.submit "Create" %>

    <% end %>

I am able to see the message list and able to go to create new message page. But when I submit the form, I am getting the following Routing error:

uninitialized constant MessageMo1sController Did you mean? MessagecController MessagesMController

My first questions is:
1) What am I missing in the routes.rb file?
2) Is there any rule between naming the model similar to that of the controller?

Body:
I just replicated all of the above, I think there are many things to keep in mind.

Your model file must be of name messagesmo1.rb and in this model:

class MessagesMo1 < ApplicationRecord
end

Your controller file should be of name messagec_controller.rb and in it:

def index
  @messages1 = MessagesMo1.all
end

def new
  @messages2 = MessagesMo1.new
end

def create
  @messages2 = MessagesMo1.new(message_params)
  if @messages2.save #tells if the object is saved successfully in db or not
    flash[:success] = "Great! Your post has been created!"
    redirect_to '/messages'
  else

    flash.now[:error] = "Fix your mistakes, please."
    redirect_to '/messages/new'
  end
end

private
def message_params
  params.require(:messages_mo1).permit(:content)
end

In the above point, look at the message_params part, it must be :messages_mo1 and not :message

No changes required in _form.html.erb file

Your migration file must be of name timestamp__create_messages_mo1s.rb and it must have:

class CreateMessagesMo1s < ActiveRecord::Migration[6.0]
  def change
    create_table :messages_mo1s do |t|
      t.text :content

      t.timestamps
    end
  end
end

In your routes.rb file, change the last route:

get '/messages' => 'messagec#index'
get '/messages/new' => 'messagec#new'
post 'messages' => 'messagec#create'
post 'messages_mo1s' => 'messagec#create'

Make sure all your links are updated in index.html.erb, in show.html.erb and in new.html.erb -> Like links to show, delete, edit etc. Or if your just testing remove these links.

After making above changes, run rails db:drop db:create db:migrate as it will clean your DB of old migration.

That's it, now everything should work. The main problem is naming convention should be standard across all files. So it's better to use standard convention.


问:
SQL - insert and limit the number of entries
I have a table that represents a user's entries:

```<code>User_ID | Entry_ID
</code>```

Now I want to store only the last 20 entries (for example).

What would be the best way to insert new entries while keeping the maximum number of entries per user at 20 (new entries will replace oldest entries) ?

I need to be able to insert also a list of items to replace the old ones (if possible, to avoid multiple SQL requests)

答:
Sounds like a job for a trigger...

Add a statement-level after insert trigger, which deletes rows like:

```<code>delete from yourtbl
where yourid not in (
  select yourid from yourtbl order by yourid desc limit 20
)
</code>```

Body:
I have a table that represents a user's entries:

User_ID | Entry_ID

Now I want to store only the last 20 entries (for example).

What would be the best way to insert new entries while keeping the maximum number of entries per user at 20 (new entries will replace oldest entries) ?

I need to be able to insert also a list of items to replace the old ones (if possible, to avoid multiple SQL requests)

Body:
Sounds like a job for a trigger...

Add a statement-level after insert trigger, which deletes rows like:

delete from yourtbl
where yourid not in (
  select yourid from yourtbl order by yourid desc limit 20
)


问:
color only mean group of PCA
Let's say I have a PCA (either using prcomp() or PCA() from FactoMineR. I'd like to plot all points per each group in black, but label and color only the mean point per group. For example,

```<code>library(FactoMineR)
library(factoextra)
iris
res.ACP<-PCA(iris[,c(1:3)],scale.unit = TRUE,ncp= 5)
fviz_pca_ind(res.ACP,geom.ind=c("point"),point.size=3,pointshape=16,
             col.ind=iris$Species,
             col="Set1",legend.title="Species",addlabel=TRUE, mean.point.size=5)

</code>```

How do I keep the mean points colored as above but plot all the data points in black? Ideally, I'd also like to label the means and then I'll drop the legend.

Thanks for the help.

答:
Here is a possibile solution.

```<code>library(FactoMineR)
library(factoextra)
library(dplyr)

res.ACP <- PCA(iris[,c(1:3)], scale.unit = TRUE, ncp= 5)

df <- data.frame(res.ACP$ind$coord[,1:2], Species=iris$Species)
df <- df %>%
      group_by(Species) %>%
      summarize(Dim1=mean(Dim.1), Dim2=mean(Dim.2))

fviz_pca_ind(res.ACP, geom.ind=c("point"), point.size=3, pointshape=16,
             legend.title="Species", addlabel=TRUE) +
  geom_text(data=df, aes(x=Dim1, y=Dim2, label=Species, color=Species),
            size=6, nudge_y=0.25) +
  geom_point(data=df, aes(x=Dim1, y=Dim2, color=Species), size=5)
</code>```

Title: color only mean group of PCA

Body:
Let's say I have a PCA (either using prcomp() or PCA() from FactoMineR. I'd like to plot all points per each group in black, but label and color only the mean point per group. For example,

library(FactoMineR)
library(factoextra)
iris
res.ACP<-PCA(iris[,c(1:3)],scale.unit = TRUE,ncp= 5)
fviz_pca_ind(res.ACP,geom.ind=c("point"),point.size=3,pointshape=16,
             col.ind=iris$Species,
             col="Set1",legend.title="Species",addlabel=TRUE, mean.point.size=5)

How do I keep the mean points colored as above but plot all the data points in black? Ideally, I'd also like to label the means and then I'll drop the legend.

Thanks for the help.

Body:
Here is a possibile solution.

library(FactoMineR)
library(factoextra)
library(dplyr)

res.ACP <- PCA(iris[,c(1:3)], scale.unit = TRUE, ncp= 5)

df <- data.frame(res.ACP$ind$coord[,1:2], Species=iris$Species)
df <- df %>%
      group_by(Species) %>%
      summarize(Dim1=mean(Dim.1), Dim2=mean(Dim.2))

fviz_pca_ind(res.ACP, geom.ind=c("point"), point.size=3, pointshape=16,
             legend.title="Species", addlabel=TRUE) +
  geom_text(data=df, aes(x=Dim1, y=Dim2, label=Species, color=Species),
            size=6, nudge_y=0.25) +
  geom_point(data=df, aes(x=Dim1, y=Dim2, color=Species), size=5)


问:
for-of loop in Angular
Is there an easier way to use for-of loop in Angular 9?
I had written code like this:

```<code>Object.keys(httpParams).forEach((key) => {
  for (const paramKey of httpParams[key]) {
     params = params.append(key, paramKey);
  }
});
</code>```

But are there some other ways not to use this for-of loop

答:
```<code>Object.entries(httpParams).forEach((data) => {
     let key = data[0];
     data[1].forEach((item)=> {
            params=params.append(key, item);
     });
});
</code>```

Title: for-of loop in Angular

Body:
Is there an easier way to use for-of loop in Angular 9?
I had written code like this:

Object.keys(httpParams).forEach((key) => {
  for (const paramKey of httpParams[key]) {
     params = params.append(key, paramKey);
  }
});

But are there some other ways not to use this for-of loop


问:
Python BeautifulSoup how to extract var result from javascript element?
I'm new with Python and I've been trying to use BeautifulSoup to extract one particular data line from a variable defined in a script element.

Code:

```<code>import requests
from bs4 import BeautifulSoup
import esprima

#----------------some comment'

URL = 'https://downdetector.com/status/facebook/'

browser = {'user-agent': 'my agent'}

#--------------some comment:
page = requests.get(URL, headers=browser)
soup = BeautifulSoup(page.content, 'html.parser')

#---------------some comment:

chart = soup.find("div",{"class":"popover-container justify-content-center p-relative"}).script.get_text()
print(chart)
</code>```

OUTPUT:

```<code>var data = {
status: 'success',
baseline: 29,
communicate: null,
company: 'Facebook',
max: 66,
series: [

                      { x: '2020-05-30T13:22:28.168484-04:00', y: 25  },

                      { x: '2020-05-30T13:37:28.168484-04:00', y: 27  },

                      .....

                      { x: '2020-05-31T13:07:28.168484-04:00', y: 30  },

                  ]
                }

                $(function () {
                  chartThis(data, 'holder', 'line')
                });

                if (data.communicate && $('#dd-communicate').length) {
                  $('#dd-communicate').html('<div class="border text-left d-inline-block p-2"><i class="fa" aria-hidden="true" style="color: red; width:16px; height:12px; background:url(https://cdn2.downdetector.com/d328eb8cbe4e164/images/v2/message.svg) no-repeat"></i>'
                    +'<span class="d-inline-block px-1">'+ data.company+' •  ' + moment.utc(data.communicate.created_at).fromNow()
                    + '</span><p class="font-weight-bold my-0">'+ data.communicate.message + '</p></div>')
                }
</code>```

Do you know an easy way to extract the 'max' value from the var result above?

I've tried using esprima, but still no luck as I've hit error:

Traceback (most recent call last):   File
  "c:/test.py, line 31, in
      if token["type"] == "Identifier" and token["value"] == "max": TypeError: 'BufferEntry' object is not subscriptable

My code with esprima looked like this:

```<code>import requests
from bs4 import BeautifulSoup
import esprima

#----------------some comment'

URL = 'https://downdetector.com/status/facebook/'

browser = {'user-agent': 'my agent'}

#--------------some comment:
page = requests.get(URL, headers=browser)
soup = BeautifulSoup(page.content, 'html.parser')

#---------------some comment:

chart = soup.find("div",{"class":"popover-container justify-content-center p-relative"}).script.get_text()

tokens = esprima.tokenize(chart)

token_iterator = iter(tokens)

for token in token_iterator:
    if token["type"] == "Identifier" and token["value"] == "max":
        value_token = next(next(token_iterator))
        result = value_token["value"]
</code>```

Any help would be greatly appreciated!

答:
A quick solution to extract the max value would be to use split on the chart:

```<code>import requests
from bs4 import BeautifulSoup

URL = 'https://downdetector.com/status/facebook/'
browser = {'user-agent': 'my agent'}

page = requests.get(URL, headers=browser)
soup = BeautifulSoup(page.content, 'html.parser')

chart = soup.find("div",{"class":"popover-container justify-content-center p-relative"}).script.get_text()
max_val= chart.split("max: ")[1].split(",")[0]

print(max_val)

OUT: 64
</code>```

Body:
I'm new with Python and I've been trying to use BeautifulSoup to extract one particular data line from a variable defined in a script element.

Code:

import requests
from bs4 import BeautifulSoup
import esprima

#----------------some comment'

URL = 'https://downdetector.com/status/facebook/'

browser = {'user-agent': 'my agent'}

#--------------some comment:
page = requests.get(URL, headers=browser)
soup = BeautifulSoup(page.content, 'html.parser')

#---------------some comment:

chart = soup.find("div",{"class":"popover-container justify-content-center p-relative"}).script.get_text()
print(chart)

OUTPUT:

var data = {
status: 'success',
baseline: 29,
communicate: null,
company: 'Facebook',
max: 66,
series: [

                      { x: '2020-05-30T13:22:28.168484-04:00', y: 25  },

                      { x: '2020-05-30T13:37:28.168484-04:00', y: 27  },

                      .....

                      { x: '2020-05-31T13:07:28.168484-04:00', y: 30  },

                  ]
                }

                $(function () {
                  chartThis(data, 'holder', 'line')
                });

                if (data.communicate && $('#dd-communicate').length) {
                  $('#dd-communicate').html('
'
                    +''+ data.company+' •  ' + moment.utc(data.communicate.created_at).fromNow()
                    + '
'+ data.communicate.message + '

')
                }

Do you know an easy way to extract the 'max' value from the var result above?

I've tried using esprima, but still no luck as I've hit error:

Traceback (most recent call last):   File
  "c:/test.py, line 31, in
      if token["type"] == "Identifier" and token["value"] == "max": TypeError: 'BufferEntry' object is not subscriptable

My code with esprima looked like this:

import requests
from bs4 import BeautifulSoup
import esprima

#----------------some comment'

URL = 'https://downdetector.com/status/facebook/'

browser = {'user-agent': 'my agent'}

#--------------some comment:
page = requests.get(URL, headers=browser)
soup = BeautifulSoup(page.content, 'html.parser')

#---------------some comment:

chart = soup.find("div",{"class":"popover-container justify-content-center p-relative"}).script.get_text()

tokens = esprima.tokenize(chart)

token_iterator = iter(tokens)

for token in token_iterator:
    if token["type"] == "Identifier" and token["value"] == "max":
        value_token = next(next(token_iterator))
        result = value_token["value"]

Any help would be greatly appreciated!

Body:
A quick solution to extract the max value would be to use split on the chart:

import requests
from bs4 import BeautifulSoup

URL = 'https://downdetector.com/status/facebook/'
browser = {'user-agent': 'my agent'}

page = requests.get(URL, headers=browser)
soup = BeautifulSoup(page.content, 'html.parser')

chart = soup.find("div",{"class":"popover-container justify-content-center p-relative"}).script.get_text()
max_val= chart.split("max: ")[1].split(",")[0]

print(max_val)

OUT: 64


问:
My text in my clock python is not aligning properly
My text in my turtle module is not aligning properly, it is aligned up and to the left. I want it to align exactly where the turtle is. Can anyone help? I tried setting the xcor and ycor of the turtle up and to the left by 5 units and that did not work. Any help would be greatly appreciated.

Code:

```<code>import time
from datetime import datetime,date
import turtle
t = turtle.Pen()

while True:
    turtle.tracer(0, 0)
    hour_hand = float(datetime.today().hour)
    minute_hand = float(datetime.today().minute)
    second_hand = float(datetime.today().second)

    # Draw circle
    t.hideturtle()
    t.circle(150)
    t.left(90)
    t.up()
    t.forward(150)
    t.down()

    # Draw hands
    t.right(float(float(minute_hand) * 6))
    t.forward(100)
    t.backward(100)
    t.left(float(float(minute_hand) * 6))
    t.right(int(float(hour_hand) * 30 + float(minute_hand) / 60 * 30))
    t.forward(50)
    t.backward(50)
    t.left(int(float(hour_hand) * 30 + float(minute_hand) / 60 * 30))
    t.right(second_hand * 6)
    t.forward(125)
    t.backward(125)
    t.left(second_hand * 6)

    # Draw ticks
    for x in range(0, 12):
        t.up()
        t.forward(130)
        t.down()
        t.forward(20)
        t.backward(20)
        t.up()
        t.backward(130)
        t.down()
        t.right(30)
    for y in range(0, 60):
        t.up()
        t.forward(140)
        t.down()
        t.forward(10)
        t.backward(10)
        t.up()
        t.backward(140)
        t.down()
        t.right(6)
    t.up()

    # Draw numbers
    t.right(32.5)
    for z in range(1, 12):
        t.forward(130)
        t.sety(t.ycor() - 5)
        t.setx(t.xcor() - 5)
        t.write(z, align = 'center', font = ('Times New Roman', 16))
        t.sety(t.ycor() + 5)
        t.setx(t.xcor() + 5)
        t.backward(130)
        t.right(30)
    t.forward(130)
    t.write(12, align = 'center', font = ('Times New Roman', 16))
    turtle.update()
    t.hideturtle()
    time.sleep(0.85)
    t.reset()
</code>```

I don't really want to use tkinter, it is too complicated.

答:
A simpler, though potentially less accurate, way to do this completely within turtle:

```<code>FONT_SIZE = 16
FONT = ('Times New Roman', FONT_SIZE)

t.color('red')
t.dot(2) # show target of where we want to center text, for debugging
t.color('black')

t.sety(t.ycor() - FONT_SIZE/2)
t.write(12, align='center', font=FONT)
</code>```

Now let's address your program as a whole.  The primary issues I see is that it flickers and is more complicated than necessary.  The first thing to do is to switch turtle into Logo mode, which makes positive angles clockwise and makes 0 degrees at the top (not unlike a clock!).

Then we split the dial drawing onto it's own turtle to be drawn once an we put the hands on their own turtle to be erased and redraw over and over.  We all toss the while True: and sleep(), which have no place in an event-driven world like turtle, and use a turtle timer event instead:

```<code>from datetime import datetime
from turtle import Screen, Turtle

OUTER_RADIUS = 150
LARGE_TICK = 20
SMALL_TICK = 10

FONT_SIZE = 16
FONT = ('Times New Roman', FONT_SIZE)

def draw_dial():
    dial = Turtle()
    dial.hideturtle()

    dial.dot()

    dial.up()
    dial.forward(OUTER_RADIUS)
    dial.right(90)
    dial.down()
    dial.circle(-OUTER_RADIUS)
    dial.up()
    dial.left(90)
    dial.backward(OUTER_RADIUS)

    for mark in range(60):
        distance = LARGE_TICK if mark % 5 == 0 else SMALL_TICK
        dial.forward(OUTER_RADIUS)
        dial.down()
        dial.backward(distance)
        dial.up()
        dial.backward(OUTER_RADIUS - distance)
        dial.right(6)

    dial.sety(-FONT_SIZE/2)
    dial.setheading(30)  # starting at 1 o'clock

    for z in range(1, 13):
        dial.forward(OUTER_RADIUS - (LARGE_TICK + FONT_SIZE/2))
        dial.write(z, align='center', font=FONT)
        dial.backward(OUTER_RADIUS - (LARGE_TICK + FONT_SIZE/2))
        dial.right(30)

def tick():
    hour_hand = datetime.today().hour
    minute_hand = datetime.today().minute
    second_hand = datetime.today().second

    hands.reset()
    hands.hideturtle()  # redo as undone by reset()

    hands.right(hour_hand * 30 + minute_hand / 60 * 30)
    hands.forward(1/3 * OUTER_RADIUS)
    hands.backward(1/3 * OUTER_RADIUS)
    hands.left(hour_hand * 30 + minute_hand / 60 * 30)

    hands.right(minute_hand * 6)
    hands.forward(2/3 * OUTER_RADIUS)
    hands.backward(2/3 * OUTER_RADIUS)
    hands.left(minute_hand * 6)

    hands.right(second_hand * 6)
    hands.forward(OUTER_RADIUS - (LARGE_TICK + FONT_SIZE))
    hands.backward(OUTER_RADIUS - (LARGE_TICK + FONT_SIZE))
    hands.left(second_hand * 6)

    screen.update()
    screen.ontimer(tick, 1000)

screen = Screen()
screen.mode('logo')  # make 0 degrees straight up, positive angles clockwise (like a clock!)
screen.tracer(False)

draw_dial()

hands = Turtle()

tick()

screen.mainloop()
</code>```

Body:
My text in my turtle module is not aligning properly, it is aligned up and to the left. I want it to align exactly where the turtle is. Can anyone help? I tried setting the xcor and ycor of the turtle up and to the left by 5 units and that did not work. Any help would be greatly appreciated.

Code:

import time
from datetime import datetime,date
import turtle
t = turtle.Pen()

while True:
    turtle.tracer(0, 0)
    hour_hand = float(datetime.today().hour)
    minute_hand = float(datetime.today().minute)
    second_hand = float(datetime.today().second)

    # Draw circle
    t.hideturtle()
    t.circle(150)
    t.left(90)
    t.up()
    t.forward(150)
    t.down()

    # Draw hands
    t.right(float(float(minute_hand) * 6))
    t.forward(100)
    t.backward(100)
    t.left(float(float(minute_hand) * 6))
    t.right(int(float(hour_hand) * 30 + float(minute_hand) / 60 * 30))
    t.forward(50)
    t.backward(50)
    t.left(int(float(hour_hand) * 30 + float(minute_hand) / 60 * 30))
    t.right(second_hand * 6)
    t.forward(125)
    t.backward(125)
    t.left(second_hand * 6)

    # Draw ticks
    for x in range(0, 12):
        t.up()
        t.forward(130)
        t.down()
        t.forward(20)
        t.backward(20)
        t.up()
        t.backward(130)
        t.down()
        t.right(30)
    for y in range(0, 60):
        t.up()
        t.forward(140)
        t.down()
        t.forward(10)
        t.backward(10)
        t.up()
        t.backward(140)
        t.down()
        t.right(6)
    t.up()

    # Draw numbers
    t.right(32.5)
    for z in range(1, 12):
        t.forward(130)
        t.sety(t.ycor() - 5)
        t.setx(t.xcor() - 5)
        t.write(z, align = 'center', font = ('Times New Roman', 16))
        t.sety(t.ycor() + 5)
        t.setx(t.xcor() + 5)
        t.backward(130)
        t.right(30)
    t.forward(130)
    t.write(12, align = 'center', font = ('Times New Roman', 16))
    turtle.update()
    t.hideturtle()
    time.sleep(0.85)
    t.reset()

I don't really want to use tkinter, it is too complicated.

Body:
A simpler, though potentially less accurate, way to do this completely within turtle:

FONT_SIZE = 16
FONT = ('Times New Roman', FONT_SIZE)

t.color('red')
t.dot(2) # show target of where we want to center text, for debugging
t.color('black')

t.sety(t.ycor() - FONT_SIZE/2)
t.write(12, align='center', font=FONT)

Now let's address your program as a whole.  The primary issues I see is that it flickers and is more complicated than necessary.  The first thing to do is to switch turtle into Logo mode, which makes positive angles clockwise and makes 0 degrees at the top (not unlike a clock!).

Then we split the dial drawing onto it's own turtle to be drawn once an we put the hands on their own turtle to be erased and redraw over and over.  We all toss the while True: and sleep(), which have no place in an event-driven world like turtle, and use a turtle timer event instead:

from datetime import datetime
from turtle import Screen, Turtle

OUTER_RADIUS = 150
LARGE_TICK = 20
SMALL_TICK = 10

FONT_SIZE = 16
FONT = ('Times New Roman', FONT_SIZE)

def draw_dial():
    dial = Turtle()
    dial.hideturtle()

    dial.dot()

    dial.up()
    dial.forward(OUTER_RADIUS)
    dial.right(90)
    dial.down()
    dial.circle(-OUTER_RADIUS)
    dial.up()
    dial.left(90)
    dial.backward(OUTER_RADIUS)

    for mark in range(60):
        distance = LARGE_TICK if mark % 5 == 0 else SMALL_TICK
        dial.forward(OUTER_RADIUS)
        dial.down()
        dial.backward(distance)
        dial.up()
        dial.backward(OUTER_RADIUS - distance)
        dial.right(6)

    dial.sety(-FONT_SIZE/2)
    dial.setheading(30)  # starting at 1 o'clock

    for z in range(1, 13):
        dial.forward(OUTER_RADIUS - (LARGE_TICK + FONT_SIZE/2))
        dial.write(z, align='center', font=FONT)
        dial.backward(OUTER_RADIUS - (LARGE_TICK + FONT_SIZE/2))
        dial.right(30)

def tick():
    hour_hand = datetime.today().hour
    minute_hand = datetime.today().minute
    second_hand = datetime.today().second

    hands.reset()
    hands.hideturtle()  # redo as undone by reset()

    hands.right(hour_hand * 30 + minute_hand / 60 * 30)
    hands.forward(1/3 * OUTER_RADIUS)
    hands.backward(1/3 * OUTER_RADIUS)
    hands.left(hour_hand * 30 + minute_hand / 60 * 30)

    hands.right(minute_hand * 6)
    hands.forward(2/3 * OUTER_RADIUS)
    hands.backward(2/3 * OUTER_RADIUS)
    hands.left(minute_hand * 6)

    hands.right(second_hand * 6)
    hands.forward(OUTER_RADIUS - (LARGE_TICK + FONT_SIZE))
    hands.backward(OUTER_RADIUS - (LARGE_TICK + FONT_SIZE))
    hands.left(second_hand * 6)

    screen.update()
    screen.ontimer(tick, 1000)

screen = Screen()
screen.mode('logo')  # make 0 degrees straight up, positive angles clockwise (like a clock!)
screen.tracer(False)

draw_dial()

hands = Turtle()

tick()

screen.mainloop()


问:
Why this java program not working properly?
I am newcomer to java and as you see this program in java swing  consists of one jframe and one jpanel. When you click a button its color changes to red and automatically button 1 pressed and its color changed to blue.

But the problem is I want a delay between these actions and when I use Thread.sleep(1000) it causes a delay between pressing a button and changing its color and I don't want that.

What can i do that when I press the button 2 (for example) its color changed immediately and after 1 second button 1 pressed?

jframe:

```<code>public class NewJFrame extends javax.swing.JFrame {

    private String player = "Player 1";
    private JButton[] btn = new JButton[4];

    public NewJFrame() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        newJPanel1 = new NewJPanel();
        newJPanel2 = new NewJPanel();
        btn1 = new javax.swing.JButton();
        btn2 = new javax.swing.JButton();
        btn3 = new javax.swing.JButton();

        javax.swing.GroupLayout newJPanel1Layout = new javax.swing.GroupLayout(newJPanel1);
        newJPanel1.setLayout(newJPanel1Layout);
        newJPanel1Layout.setHorizontalGroup(
                newJPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 100, Short.MAX_VALUE)
        );
        newJPanel1Layout.setVerticalGroup(
                newJPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        newJPanel2.setBackground(new java.awt.Color(255, 255, 255));
        newJPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        btn1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAction(evt);
            }
        });

        btn2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAction(evt);
            }
        });

        btn3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAction(evt);
            }
        });

        javax.swing.GroupLayout newJPanel2Layout = new javax.swing.GroupLayout(newJPanel2);
        newJPanel2.setLayout(newJPanel2Layout);
        newJPanel2Layout.setHorizontalGroup(
                newJPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(newJPanel2Layout.createSequentialGroup()
                                .addGap(35, 35, 35)
                                .addComponent(btn1)
                                .addGap(74, 74, 74)
                                .addComponent(btn2)
                                .addGap(66, 66, 66)
                                .addComponent(btn3)
                                .addContainerGap(104, Short.MAX_VALUE))
        );
        newJPanel2Layout.setVerticalGroup(
                newJPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(newJPanel2Layout.createSequentialGroup()
                                .addGap(31, 31, 31)
                                .addGroup(newJPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(btn1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(btn2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(btn3, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addContainerGap(222, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(newJPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addContainerGap())
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(newJPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    private void btnAction(java.awt.event.ActionEvent evt) {
        JButton btn = (JButton) evt.getSource();
        if (player.equals("Player 1")) {
            player = "Player 2";
            btn.setBackground(Color.RED);
        } else {
            player = "Player 1";
            btn.setBackground(Color.BLUE);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        player2Action();

    }

    private void player2Action() {
        if (player.equals("Player 2")) {
            btn1.doClick();
        }

    }

    public static void main(String args[]) {

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

// Variables declaration - do not modify
    private javax.swing.JButton btn1;
    private javax.swing.JButton btn2;
    private javax.swing.JButton btn3;
    private NewJPanel newJPanel1;
    private NewJPanel newJPanel2;
// End of variables declaration
}
</code>```

jpanel:

```<code>public class NewJPanel extends javax.swing.JPanel {

    public NewJPanel() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>

    // Variables declaration - do not modify
    // End of variables declaration
}
</code>```

答:
In this case, use Timer in stead of Thread. Look at comments from Andrew Thompson for more details.

To fix your code, just remove the try-catch block of the Thread.sleep and the player2Action() method next to it. Then add following codes to make it work:

```<code>ActionListener player2ActionListener = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        player2Action();
    }
};
Timer timer = new Timer(1000, player2ActionListener);
timer.setRepeats(false);
timer.start();
</code>```

And don't forget to import javax.swing.Timer.

Body:
I am newcomer to java and as you see this program in java swing  consists of one jframe and one jpanel. When you click a button its color changes to red and automatically button 1 pressed and its color changed to blue.

But the problem is I want a delay between these actions and when I use Thread.sleep(1000) it causes a delay between pressing a button and changing its color and I don't want that.

What can i do that when I press the button 2 (for example) its color changed immediately and after 1 second button 1 pressed?

jframe:

public class NewJFrame extends javax.swing.JFrame {

    private String player = "Player 1";
    private JButton[] btn = new JButton[4];

    public NewJFrame() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        newJPanel1 = new NewJPanel();
        newJPanel2 = new NewJPanel();
        btn1 = new javax.swing.JButton();
        btn2 = new javax.swing.JButton();
        btn3 = new javax.swing.JButton();

        javax.swing.GroupLayout newJPanel1Layout = new javax.swing.GroupLayout(newJPanel1);
        newJPanel1.setLayout(newJPanel1Layout);
        newJPanel1Layout.setHorizontalGroup(
                newJPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 100, Short.MAX_VALUE)
        );
        newJPanel1Layout.setVerticalGroup(
                newJPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        newJPanel2.setBackground(new java.awt.Color(255, 255, 255));
        newJPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        btn1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAction(evt);
            }
        });

        btn2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAction(evt);
            }
        });

        btn3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAction(evt);
            }
        });

        javax.swing.GroupLayout newJPanel2Layout = new javax.swing.GroupLayout(newJPanel2);
        newJPanel2.setLayout(newJPanel2Layout);
        newJPanel2Layout.setHorizontalGroup(
                newJPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(newJPanel2Layout.createSequentialGroup()
                                .addGap(35, 35, 35)
                                .addComponent(btn1)
                                .addGap(74, 74, 74)
                                .addComponent(btn2)
                                .addGap(66, 66, 66)
                                .addComponent(btn3)
                                .addContainerGap(104, Short.MAX_VALUE))
        );
        newJPanel2Layout.setVerticalGroup(
                newJPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(newJPanel2Layout.createSequentialGroup()
                                .addGap(31, 31, 31)
                                .addGroup(newJPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(btn1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(btn2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(btn3, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addContainerGap(222, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(newJPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addContainerGap())
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(newJPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    private void btnAction(java.awt.event.ActionEvent evt) {
        JButton btn = (JButton) evt.getSource();
        if (player.equals("Player 1")) {
            player = "Player 2";
            btn.setBackground(Color.RED);
        } else {
            player = "Player 1";
            btn.setBackground(Color.BLUE);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        player2Action();

    }

    private void player2Action() {
        if (player.equals("Player 2")) {
            btn1.doClick();
        }

    }

    public static void main(String args[]) {

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

// Variables declaration - do not modify
    private javax.swing.JButton btn1;
    private javax.swing.JButton btn2;
    private javax.swing.JButton btn3;
    private NewJPanel newJPanel1;
    private NewJPanel newJPanel2;
// End of variables declaration
}

jpanel:

public class NewJPanel extends javax.swing.JPanel {

    public NewJPanel() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>

    // Variables declaration - do not modify
    // End of variables declaration
}

Body:
In this case, use Timer in stead of Thread. Look at comments from Andrew Thompson for more details.

To fix your code, just remove the try-catch block of the Thread.sleep and the player2Action() method next to it. Then add following codes to make it work:

ActionListener player2ActionListener = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        player2Action();
    }
};
Timer timer = new Timer(1000, player2ActionListener);
timer.setRepeats(false);
timer.start();

And don't forget to import javax.swing.Timer.


问:
MariaDB - Create Foreign key
I want to  create a Foreign key in MariaDB:

```<code>ALTER TABLE `t_time_lapse` ADD CONSTRAINT `time_lapse_company_uk` FOREIGN KEY(`COMPANY_ID`) REFERENCES `T_COMPANY`(`ID`);
</code>```

but I have this error:

```<code>Can't create table `lopes_db`.`t_time_lapse` (errno: 150 "Foreign key constraint is incorrectly formed")
</code>```

答:
There would be multiple reasons for the error. The data type of your foreign key column (COMPANY_ID) and reference column (ID) may not be same. Or there can be standardization issues as well. I would suggest you to check the issue and resolve it. If you still wanted to force create the foreign key, please use below statements,</p>

```<code>SET FOREIGN_KEY_CHECKS=OFF;
ALTER TABLE `t_time_lapse` ADD CONSTRAINT `time_lapse_company_uk` FOREIGN KEY(`COMPANY_ID`) REFERENCES `T_COMPANY`(`ID`);
SET FOREIGN_KEY_CHECKS=ON;
</code>```

Title: MariaDB - Create Foreign key

Body:
I want to  create a Foreign key in MariaDB:

ALTER TABLE `t_time_lapse` ADD CONSTRAINT `time_lapse_company_uk` FOREIGN KEY(`COMPANY_ID`) REFERENCES `T_COMPANY`(`ID`);

but I have this error:

Can't create table `lopes_db`.`t_time_lapse` (errno: 150 "Foreign key constraint is incorrectly formed")

Body:
There would be multiple reasons for the error. The data type of your foreign key column (COMPANY_ID) and reference column (ID) may not be same. Or there can be standardization issues as well. I would suggest you to check the issue and resolve it. If you still wanted to force create the foreign key, please use below statements,

SET FOREIGN_KEY_CHECKS=OFF;
ALTER TABLE `t_time_lapse` ADD CONSTRAINT `time_lapse_company_uk` FOREIGN KEY(`COMPANY_ID`) REFERENCES `T_COMPANY`(`ID`);
SET FOREIGN_KEY_CHECKS=ON;


问:
Omitting inline ASM code in C source code
While using MS VC98, is there a way to omit compiling inline ASM code in a C source ?</p>

答: There's no magic switch built into the compiler to do this. You'll have to do it with the pre-processor and I can't see any alternative to wrapping all such blocks in #ifdef.


问:
split URL using Regular Expression in IIS
I am facing challenges in splitting the URL using regular expression.

I want to change the mid of the URL part since we changed the URL of the site pages.

```<code>      https://test.company.com/about/news/2015/test/award.aspx
</code>```

The above given URL needs to replace as below,

```<code>      https://test.company.com/en/about/media/news/2015/test/award.aspx
</code>```

I want to achieve this functionality using Regular Expression in IIS.

I tried the code as below in URL Rewrite in IIS,

```<code>      about/news/2015(.*.+?)
</code>```

Help to resolve this as required, thanks in advance.

答:
The regex engine gets the string without the host and protocol, starting with about. Thus, you need to match starting with this fixed string, capture the parts between which you need to insert the required value and use

```<code>^(about)(/news/2015/)
</code>```

Replace with

```<code>en/{R:1}/media{R:2}
</code>```

Where {R:1} refers to about and the {R:2} refers to /news/2015/.

Here is a demo of how this regex works.

Body:
I am facing challenges in splitting the URL using regular expression.

I want to change the mid of the URL part since we changed the URL of the site pages.

      https://test.company.com/about/news/2015/test/award.aspx

The above given URL needs to replace as below,

      https://test.company.com/en/about/media/news/2015/test/award.aspx

I want to achieve this functionality using Regular Expression in IIS.

I tried the code as below in URL Rewrite in IIS,

      about/news/2015(.*.+?)

Help to resolve this as required, thanks in advance.

Body:
The regex engine gets the string without the host and protocol, starting with about. Thus, you need to match starting with this fixed string, capture the parts between which you need to insert the required value and use

^(about)(/news/2015/)

Replace with

en/{R:1}/media{R:2}

Where {R:1} refers to about and the {R:2} refers to /news/2015/.

Here is a demo of how this regex works.


问:
Django ckeditor can not add youtube plugin
I have seen this tutorial https://samulinatri.com/blog/django-ckeditor-codesnippet-hightlightjs-youtube/ and I have downloaded the youtube plugin here https://ckeditor.com/cke4/addon/youtube

Then I created the youtube folder and pushed it into it. Specifically my_project / static / ckeditor / ckeditor / plugins / youtube /

After I python manage.py runserver, field ['content'] show normal, field ['content1'] it doesn't work (does not display frames textarea).

Someone helped me check, I did something wrong. Thanks !!!

File model.py

```<code>class Posts(models.Model):
    title = models.CharField(max_length=50)
    content = RichTextUploadingField(extra_plugins=['codesnippet'],)
    content1 = RichTextUploadingField(
        config_name='special',
        extra_plugins=['youtube'],
        external_plugin_resources=[(
            'youtube',
            '/static/ckeditor/ckeditor/plugins/youtube/youtube/',
            'plugin.js',
        )],
    )
</code>```

File setting.py

```<code>INSTALLED_APPS = [
    'suit',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',

    'ckeditor',
    'ckeditor_uploader',
]

CKEDITOR_UPLOAD_PATH = "uploads/"

CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': 'full',
     },

    'special': {
        'toolbar': 'Special',
        'toolbar_Special': [
            ['Bold'], ['CodeSnippet', 'Youtube'],
        ],
        'extraPlugins': ','.join(['codesnippet', 'youtube']),
    }
}
</code>```

File urls.py

```<code>urlpatterns = [
    path('admin/', admin.site.urls),
    path('account/', include(('accounts.urls', 'accounts'), namespace='accounts')),
    path('blog/', include(('blog.urls', 'blog'), namespace='blog')),
    path('ckeditor/', include('ckeditor_uploader.urls')),
]
if settings.DEBUG:
    import debug_toolbar

    debug_patterns = [
        re_path(r'^__debug__/', include(debug_toolbar.urls)),
    ]
    urlpatterns = debug_patterns + urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

</code>```

My_project

```<code>├── blog                          <= This my_app
│   ├── view.py
│   ├── form.py
│   ├── model.py
├── project                          <= Project settings directory
│   ├── __init__.py
│   ├── settings.py          <= settings
│   ├── urls.py
│   └── wsgi.py
├── static
│   ├── ckeditor
│       ├── ckeditor_uploader
│       ├── ckeditor
│           ├── plugins
│               └── youtube
│                   └── youtube
│                        └── images
│                        └── lang
│                        └── plugin.js
│                        └── ....
│                   └── ...
│                └── ...
</code>```

答:
In your models.py file, you need to point to the directory where the plugin.js is.

I believe the directory you should refer to is this:

```<code>class Posts(models.Model):
    title = models.CharField(max_length=50)
    content = RichTextUploadingField(extra_plugins=['codesnippet'],)
    content1 = RichTextUploadingField(
        config_name='special',
        extra_plugins=['youtube'],
        external_plugin_resources=[(
            'youtube',
            '/static/ckeditor/ckeditor/plugins/youtube/',
            'plugin.js',
        )],
    )
</code>```

Body:
I have seen this tutorial https://samulinatri.com/blog/django-ckeditor-codesnippet-hightlightjs-youtube/ and I have downloaded the youtube plugin here https://ckeditor.com/cke4/addon/youtube

Then I created the youtube folder and pushed it into it. Specifically my_project / static / ckeditor / ckeditor / plugins / youtube /

After I python manage.py runserver, field ['content'] show normal, field ['content1'] it doesn't work (does not display frames textarea).

Someone helped me check, I did something wrong. Thanks !!!

File model.py

class Posts(models.Model):
    title = models.CharField(max_length=50)
    content = RichTextUploadingField(extra_plugins=['codesnippet'],)
    content1 = RichTextUploadingField(
        config_name='special',
        extra_plugins=['youtube'],
        external_plugin_resources=[(
            'youtube',
            '/static/ckeditor/ckeditor/plugins/youtube/youtube/',
            'plugin.js',
        )],
    )

File setting.py

INSTALLED_APPS = [
    'suit',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',

    'ckeditor',
    'ckeditor_uploader',
]

CKEDITOR_UPLOAD_PATH = "uploads/"

CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': 'full',
     },

    'special': {
        'toolbar': 'Special',
        'toolbar_Special': [
            ['Bold'], ['CodeSnippet', 'Youtube'],
        ],
        'extraPlugins': ','.join(['codesnippet', 'youtube']),
    }
}

File urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('account/', include(('accounts.urls', 'accounts'), namespace='accounts')),
    path('blog/', include(('blog.urls', 'blog'), namespace='blog')),
    path('ckeditor/', include('ckeditor_uploader.urls')),
]
if settings.DEBUG:
    import debug_toolbar

    debug_patterns = [
        re_path(r'^__debug__/', include(debug_toolbar.urls)),
    ]
    urlpatterns = debug_patterns + urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

My_project

├── blog                          <= This my_app
│   ├── view.py
│   ├── form.py
│   ├── model.py
├── project                          <= Project settings directory
│   ├── __init__.py
│   ├── settings.py          <= settings
│   ├── urls.py
│   └── wsgi.py
├── static
│   ├── ckeditor
│       ├── ckeditor_uploader
│       ├── ckeditor
│           ├── plugins
│               └── youtube
│                   └── youtube
│                        └── images
│                        └── lang
│                        └── plugin.js
│                        └── ....
│                   └── ...
│                └── ...

Body:
In your models.py file, you need to point to the directory where the plugin.js is.

I believe the directory you should refer to is this:

class Posts(models.Model):
    title = models.CharField(max_length=50)
    content = RichTextUploadingField(extra_plugins=['codesnippet'],)
    content1 = RichTextUploadingField(
        config_name='special',
        extra_plugins=['youtube'],
        external_plugin_resources=[(
            'youtube',
            '/static/ckeditor/ckeditor/plugins/youtube/',
            'plugin.js',
        )],
    )


问:
Item separator for context menu in Android
Is it possible to add a separator between menu items in Android's context menu? I don't see any directions for this in the documentation. Apparently menu items should be separated in some cases when they perform operations of a different kind.

NB. The question is about context menu, not options menu.

答:
I'm not able to comment and maybe I'm a bit late but I hope this will help someone. For what I know: Android adds a separator between groups if you enable this via ContextMenu.setGroupDividerEnabled.

```<code>@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, view, menuInfo);
    menu.setHeaderTitle(R.string.choose_action);
    menu.add(0, MENU_ITEM_CREATE, 0, R.string.create);
    menu.add(1, MENU_ITEM_CHECK, 0, R.string.check);
    menu.add(2, MENU_ITEM_EDIT, 0, R.string.edit);
    menu.add(2, MENU_ITEM_DELETE, 1, R.string.delete);

    // Enable group separator
    menu.setGroupDividerEnabled(true);
}
</code>```

https://developer.android.com/reference/android/view/Menu#setGroupDividerEnabled(boolean)

Body:
I'm not able to comment and maybe I'm a bit late but I hope this will help someone. For what I know: Android adds a separator between groups if you enable this via ContextMenu.setGroupDividerEnabled.

@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, view, menuInfo);
    menu.setHeaderTitle(R.string.choose_action);
    menu.add(0, MENU_ITEM_CREATE, 0, R.string.create);
    menu.add(1, MENU_ITEM_CHECK, 0, R.string.check);
    menu.add(2, MENU_ITEM_EDIT, 0, R.string.edit);
    menu.add(2, MENU_ITEM_DELETE, 1, R.string.delete);

    // Enable group separator
    menu.setGroupDividerEnabled(true);
}

https://developer.android.com/reference/android/view/Menu#setGroupDividerEnabled(boolean)


问:
Django, separate settings files with a common part
I'm trying to setup Django with two separate settings files, to be selected via the command line parameter --settings, and that (obviously) must have a common file they both use for the common variables.

So I have the file settings_local.py:

```<code>DEBUG = True

from . import settings
</code>```

And I expected that then in settings I would have been able to access DEBUG.

I found no way at all to do that. I've tried to use globals() in both files, I've tried to use global in both, nothing seems to work.

Obviously I cannot import settings_local from settings: the entire point of this setup is to also have a settings_public.py and call either one from the command line. settings itself should be agnostic to it.

I'm also planning to add some kind of control check to ensure settings is not called directly, such as:

```<code>try:
    DEBUG
except NameError:
    raise ValueError( "This file shouldn't be used directly." )
</code>```

But the exception is always raised, since DEBUG doesn't seem to appear in settings.

I reiterate, even using globals() in both files does not work.

Searched a lot online, couldn't find anything at all that could help me in this very specific situation. I've found many different situations, that either didn't apply, didn't work, or both.

答:
Django settings are just python modules, therefore you cannot write from . import settings and expect settings to have access to global DEBUG variable. Just imagine importing some module which has access to all your global variables - this not only may break module code, but also can lead to bugs in your code relying to these global variables.

The correct answer depends on how complex your requirements are. If you just want to define some variables in dev / prod settings and use them in base settings file the easiest approach would be to switch to .env / .ini / any other external configuration file. E.g. with environ library your code may look like this:

```<code># settings/base.py
import environ

env = environ.Env()
DEBUG = env.bool('DEBUG', default=False)

# now you can use DEBUG value in this file
print(DEBUG)

# settings/local.py
import os
os.environ['DEBUG'] = 'true'

from project.settings.base import *

del os.environ['DEBUG']  # del for simplicity, ideally should be restored to previous value
</code>```

I'm also planning to add some kind of control check to ensure settings is not called directly

I'm not sure if this is a good idea. What is the reason behind it? If you want to ensure your settings variables are not conflicting with each other it will be better to check their values, without relying on whether the settings module was imported directly or through prod / dev settings. This can be implemented, if you really want to, you'll just need some flag which will indicate if someone imported your base settings outside of dev / prod settings. But this looks like an unnecessary complexity added to the settings module, which should be as simple and dumb as possible

Body:
I'm trying to setup Django with two separate settings files, to be selected via the command line parameter --settings, and that (obviously) must have a common file they both use for the common variables.

So I have the file settings_local.py:

DEBUG = True

from . import settings

And I expected that then in settings I would have been able to access DEBUG.

I found no way at all to do that. I've tried to use globals() in both files, I've tried to use global in both, nothing seems to work.

Obviously I cannot import settings_local from settings: the entire point of this setup is to also have a settings_public.py and call either one from the command line. settings itself should be agnostic to it.

I'm also planning to add some kind of control check to ensure settings is not called directly, such as:

try:
    DEBUG
except NameError:
    raise ValueError( "This file shouldn't be used directly." )

But the exception is always raised, since DEBUG doesn't seem to appear in settings.

I reiterate, even using globals() in both files does not work.

Searched a lot online, couldn't find anything at all that could help me in this very specific situation. I've found many different situations, that either didn't apply, didn't work, or both.

Body:
Django settings are just python modules, therefore you cannot write from . import settings and expect settings to have access to global DEBUG variable. Just imagine importing some module which has access to all your global variables - this not only may break module code, but also can lead to bugs in your code relying to these global variables.

The correct answer depends on how complex your requirements are. If you just want to define some variables in dev / prod settings and use them in base settings file the easiest approach would be to switch to .env / .ini / any other external configuration file. E.g. with environ library your code may look like this:

# settings/base.py
import environ

env = environ.Env()
DEBUG = env.bool('DEBUG', default=False)

# now you can use DEBUG value in this file
print(DEBUG)

# settings/local.py
import os
os.environ['DEBUG'] = 'true'

from project.settings.base import *

del os.environ['DEBUG']  # del for simplicity, ideally should be restored to previous value

I'm also planning to add some kind of control check to ensure settings is not called directly

I'm not sure if this is a good idea. What is the reason behind it? If you want to ensure your settings variables are not conflicting with each other it will be better to check their values, without relying on whether the settings module was imported directly or through prod / dev settings. This can be implemented, if you really want to, you'll just need some flag which will indicate if someone imported your base settings outside of dev / prod settings. But this looks like an unnecessary complexity added to the settings module, which should be as simple and dumb as possible


问:
Morphia 2.0.0-RC1 query returns empty list just after I have saved an object
I am trying to get Morphia to work with mongoDB and am able to save my object into the database. But when I try to retrieve all objects i get an empty list?

I am using mongo db java driver 3.12.0 and morphia 2.0.0-rc1. The old execute method has been deprecated since 2.0 but the reference guide has not been updated. I looked through the code on github and calling iterator directly instead of using execute before seems to be the right way now.

Update: by just adding any filter i get results?

```<code>public class MongoDBConnectorTest {
@Test
public void test() {
    //MongoDatabase db = MongoDBConnector.getClient().getDatabase("lottoDB");
    //MongoCollection<Lotto> lottoCollection = db.getCollection("lotto", Lotto.class);

    Datastore lottoDatastore = LottoDataStore.getLottoDataStore().getDataStore();

    //System.out.println(db.getName());

    final Lotto lotto = new Lotto();
    lotto.setHighestPriceMoney(100000);

    // Insert lotto object
    //lottoCollection.insertOne(lotto);
    lottoDatastore.save(lotto);

    // Find it again
    //final Query<Lotto> query = lottoDatastore.find(Lotto.class);
    //List<Lotto> lottos = (List<Lotto>) query.iterator().toList();
    final Query<Lotto> query = lottoDatastore.find(Lotto.class);
    final List<Lotto> lottos = query.iterator().toList();
    final Lotto lotto2 = query.first();
    //Lotto lotto2 = query.first();

    System.out.println("Lotto found:");
    System.out.println(lottos.size());
    System.out.println(lotto2);

}
}
</code>```

LottoDataStore.java

```<code>public class LottoDataStore {
private static LottoDataStore lottoDataStore = null;
protected final Datastore datastore;

public static LottoDataStore getLottoDataStore() {
    if(lottoDataStore == null) lottoDataStore = new LottoDataStore();

    return lottoDataStore;
}

private LottoDataStore() {
    this.datastore = Morphia.createDatastore(MongoDBConnector.getClient().getMongoClient(), "lottoDB");
    // tell Morphia where to find your classes
    // can be called multiple times with different packages or classes
    datastore.getMapper().mapPackage("com.j.productdata.model.entity.lotto");
    datastore.ensureIndexes();
}

public Datastore getDataStore() {
    return datastore;
}
</code>```

}

Lotto.java

```<code>@Entity("lotto")
public class Lotto {
@Id
protected String alias = "lotto";

@BsonProperty(value = "highest_price_money")
protected int highestPriceMoney;

@BsonProperty(value = "average_price_money")
protected int averagePriceMoney;

@BsonProperty(value = "min_cost")
protected int minCost;

@BsonProperty(value = "min_cost_highest_price_money")
protected int minCostHighestPriceMoney;

List<LottoResult> results;

public Lotto() {

}

public String getAlias() {
    return alias;
}

public void setAlias(String alias) {
    this.alias = alias;
}

public int getHighestPriceMoney() {
    return highestPriceMoney;
}

public void setHighestPriceMoney(int highestPriceMoney) {
    this.highestPriceMoney = highestPriceMoney;
}

public int getAveragePriceMoney() {
    return averagePriceMoney;
}

public void setAveragePriceMoney(int averagePriceMoney) {
    this.averagePriceMoney = averagePriceMoney;
}

public int getMinCost() {
    return minCost;
}

public void setMinCost(int minCost) {
    this.minCost = minCost;
}

public int getMinCostHighestPriceMoney() {
    return minCostHighestPriceMoney;
}

public void setMinCostHighestPriceMoney(int minCostHighestPriceMoney) {
    this.minCostHighestPriceMoney = minCostHighestPriceMoney;
}

public List<LottoResult> getResults() {
    return results;
}

public void setResults(List<LottoResult> results) {
    this.results = results;
}

@Override
public String toString() {
    return "Lotto [id=" + alias + ", highestPriceMoney=" + highestPriceMoney + ", minCost=" + minCost
            + ", minCostHighestPriceMoney=" + minCostHighestPriceMoney + ", results=" + results + "]";
}

}
</code>```

答:
This works for me using the reproducer and 2.0.0-RC1.  I'm not entirely sure what's going on locally that you're not seeing the results.  There are some oddities in the code, though.  You have a number of driver annotations in your code.  That's fine as far as it goes but Morphia doesn't use those annotations.

It might be that package you're mapping doesn't match where Lotto lives but i would expected an error about a missing Codec in that case.

Body:
I am trying to get Morphia to work with mongoDB and am able to save my object into the database. But when I try to retrieve all objects i get an empty list?

I am using mongo db java driver 3.12.0 and morphia 2.0.0-rc1. The old execute method has been deprecated since 2.0 but the reference guide has not been updated. I looked through the code on github and calling iterator directly instead of using execute before seems to be the right way now.

Update: by just adding any filter i get results?

public class MongoDBConnectorTest {
@Test
public void test() {
    //MongoDatabase db = MongoDBConnector.getClient().getDatabase("lottoDB");
    //MongoCollection<Lotto> lottoCollection = db.getCollection("lotto", Lotto.class);

    Datastore lottoDatastore = LottoDataStore.getLottoDataStore().getDataStore();

    //System.out.println(db.getName());

    final Lotto lotto = new Lotto();
    lotto.setHighestPriceMoney(100000);

    // Insert lotto object
    //lottoCollection.insertOne(lotto);
    lottoDatastore.save(lotto);

    // Find it again
    //final Query<Lotto> query = lottoDatastore.find(Lotto.class);
    //List<Lotto> lottos = (List<Lotto>) query.iterator().toList();
    final Query<Lotto> query = lottoDatastore.find(Lotto.class);
    final List<Lotto> lottos = query.iterator().toList();
    final Lotto lotto2 = query.first();
    //Lotto lotto2 = query.first();

    System.out.println("Lotto found:");
    System.out.println(lottos.size());
    System.out.println(lotto2);

}
}

LottoDataStore.java

public class LottoDataStore {
private static LottoDataStore lottoDataStore = null;
protected final Datastore datastore;

public static LottoDataStore getLottoDataStore() {
    if(lottoDataStore == null) lottoDataStore = new LottoDataStore();

    return lottoDataStore;
}

private LottoDataStore() {
    this.datastore = Morphia.createDatastore(MongoDBConnector.getClient().getMongoClient(), "lottoDB");
    // tell Morphia where to find your classes
    // can be called multiple times with different packages or classes
    datastore.getMapper().mapPackage("com.j.productdata.model.entity.lotto");
    datastore.ensureIndexes();
}

public Datastore getDataStore() {
    return datastore;
}

}

Lotto.java

@Entity("lotto")
public class Lotto {
@Id
protected String alias = "lotto";

@BsonProperty(value = "highest_price_money")
protected int highestPriceMoney;

@BsonProperty(value = "average_price_money")
protected int averagePriceMoney;

@BsonProperty(value = "min_cost")
protected int minCost;

@BsonProperty(value = "min_cost_highest_price_money")
protected int minCostHighestPriceMoney;

List<LottoResult> results;

public Lotto() {

}

public String getAlias() {
    return alias;
}

public void setAlias(String alias) {
    this.alias = alias;
}

public int getHighestPriceMoney() {
    return highestPriceMoney;
}

public void setHighestPriceMoney(int highestPriceMoney) {
    this.highestPriceMoney = highestPriceMoney;
}

public int getAveragePriceMoney() {
    return averagePriceMoney;
}

public void setAveragePriceMoney(int averagePriceMoney) {
    this.averagePriceMoney = averagePriceMoney;
}

public int getMinCost() {
    return minCost;
}

public void setMinCost(int minCost) {
    this.minCost = minCost;
}

public int getMinCostHighestPriceMoney() {
    return minCostHighestPriceMoney;
}

public void setMinCostHighestPriceMoney(int minCostHighestPriceMoney) {
    this.minCostHighestPriceMoney = minCostHighestPriceMoney;
}

public List<LottoResult> getResults() {
    return results;
}

public void setResults(List<LottoResult> results) {
    this.results = results;
}

@Override
public String toString() {
    return "Lotto [id=" + alias + ", highestPriceMoney=" + highestPriceMoney + ", minCost=" + minCost
            + ", minCostHighestPriceMoney=" + minCostHighestPriceMoney + ", results=" + results + "]";
}

}