问:
XGBRegressor Early Stopping Rounds Working in Python
I have been developing my model with XGBRegressor and I have a technical question about the early stopping rounds working.
This is the code:

```<code>model = XGBRegressor(n_jobs=-1, n_estimators=1000, early_stopping_rounds=50, random_state=42)
model.fit(X_train, y_train, eval_set=[(X_train, y_train),(X_val,y_val)])
</code>```

This is the output:

```<code>[0] validation_0-rmse:12740.82085   validation_1-rmse:14354.43509
[1] validation_0-rmse:9487.04070    validation_1-rmse:10616.13605
[2] validation_0-rmse:7283.04039    validation_1-rmse:8239.62752
[3] validation_0-rmse:5858.70801    validation_1-rmse:6670.77442
[4] validation_0-rmse:4965.48363    validation_1-rmse:5681.79305
[5] validation_0-rmse:4385.77247    validation_1-rmse:5110.99709
[6] validation_0-rmse:4043.46385    validation_1-rmse:4774.20268
[7] validation_0-rmse:3763.10815    validation_1-rmse:4635.01149
[8] validation_0-rmse:3591.72373    validation_1-rmse:4561.27221
[9] validation_0-rmse:3459.59007    validation_1-rmse:4520.31052
[10]    validation_0-rmse:3364.49960    validation_1-rmse:4493.90137
[11]    validation_0-rmse:3292.77090    validation_1-rmse:4488.63371
[12]    validation_0-rmse:3261.68385    validation_1-rmse:4477.47174
[13]    validation_0-rmse:3194.66407    validation_1-rmse:4479.46967
[14]    validation_0-rmse:3131.46617    validation_1-rmse:4483.96315
[15]    validation_0-rmse:3105.17158    validation_1-rmse:4496.17191
[16]    validation_0-rmse:2980.64759    validation_1-rmse:4513.39312
[17]    validation_0-rmse:2969.50538    validation_1-rmse:4515.67529
[18]    validation_0-rmse:2928.73793    validation_1-rmse:4514.08650
[19]    validation_0-rmse:2885.23440    validation_1-rmse:4512.02239
[20]    validation_0-rmse:2877.47452    validation_1-rmse:4511.70923
[21]    validation_0-rmse:2775.98275    validation_1-rmse:4541.79559
[22]    validation_0-rmse:2665.77462    validation_1-rmse:4555.71092
[23]    validation_0-rmse:2636.37427    validation_1-rmse:4549.20621
[24]    validation_0-rmse:2562.55110    validation_1-rmse:4556.94927
...
[58]    validation_0-rmse:1443.62609    validation_1-rmse:4736.20431
[59]    validation_0-rmse:1423.84305    validation_1-rmse:4746.66728
[60]    validation_0-rmse:1387.68330    validation_1-rmse:4747.30871
[61]    validation_0-rmse:1367.73335    validation_1-rmse:4747.11801
</code>```

I have understood that the model has trained 62 trees and the best number of trees is 13, but if 13 is the optimal number why does it report the results until 62 if the RMSE is increasing?

Body:
I have been developing my model with XGBRegressor and I have a technical question about the early stopping rounds working.
This is the code:

model = XGBRegressor(n_jobs=-1, n_estimators=1000, early_stopping_rounds=50, random_state=42)
model.fit(X_train, y_train, eval_set=[(X_train, y_train),(X_val,y_val)])

This is the output:

[0] validation_0-rmse:12740.82085   validation_1-rmse:14354.43509
[1] validation_0-rmse:9487.04070    validation_1-rmse:10616.13605
[2] validation_0-rmse:7283.04039    validation_1-rmse:8239.62752
[3] validation_0-rmse:5858.70801    validation_1-rmse:6670.77442
[4] validation_0-rmse:4965.48363    validation_1-rmse:5681.79305
[5] validation_0-rmse:4385.77247    validation_1-rmse:5110.99709
[6] validation_0-rmse:4043.46385    validation_1-rmse:4774.20268
[7] validation_0-rmse:3763.10815    validation_1-rmse:4635.01149
[8] validation_0-rmse:3591.72373    validation_1-rmse:4561.27221
[9] validation_0-rmse:3459.59007    validation_1-rmse:4520.31052
[10]    validation_0-rmse:3364.49960    validation_1-rmse:4493.90137
[11]    validation_0-rmse:3292.77090    validation_1-rmse:4488.63371
[12]    validation_0-rmse:3261.68385    validation_1-rmse:4477.47174
[13]    validation_0-rmse:3194.66407    validation_1-rmse:4479.46967
[14]    validation_0-rmse:3131.46617    validation_1-rmse:4483.96315
[15]    validation_0-rmse:3105.17158    validation_1-rmse:4496.17191
[16]    validation_0-rmse:2980.64759    validation_1-rmse:4513.39312
[17]    validation_0-rmse:2969.50538    validation_1-rmse:4515.67529
[18]    validation_0-rmse:2928.73793    validation_1-rmse:4514.08650
[19]    validation_0-rmse:2885.23440    validation_1-rmse:4512.02239
[20]    validation_0-rmse:2877.47452    validation_1-rmse:4511.70923
[21]    validation_0-rmse:2775.98275    validation_1-rmse:4541.79559
[22]    validation_0-rmse:2665.77462    validation_1-rmse:4555.71092
[23]    validation_0-rmse:2636.37427    validation_1-rmse:4549.20621
[24]    validation_0-rmse:2562.55110    validation_1-rmse:4556.94927
...
[58]    validation_0-rmse:1443.62609    validation_1-rmse:4736.20431
[59]    validation_0-rmse:1423.84305    validation_1-rmse:4746.66728
[60]    validation_0-rmse:1387.68330    validation_1-rmse:4747.30871
[61]    validation_0-rmse:1367.73335    validation_1-rmse:4747.11801

I have understood that the model has trained 62 trees and the best number of trees is 13, but if 13 is the optimal number why does it report the results until 62 if the RMSE is increasing?


来源: stackexchange

问:
Get DOM and control the data from router hook / Navigation Guards in vue3
I want to control the data after I enter the index page from quiz page, but I found that it's not possible to control the data by the method below, is it because the afterEach is global ?

Is there any other method that I can use to control the data inside index page when I came from the quiz page ?

I thought of using the vuex, if there's no other way, I'll try it.

this is my route:

```<code>const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: () => import('layouts/MainLayout.vue'),
    children: [
      {
        name: 'index',
        path: '/',
        component: () => import('pages/IndexPage.vue')
      },
      {
        name: 'quiz',
        path: '/quiz',
        component: () => import('pages/QuizPage.vue')
      },
    ],
  },
</code>```

this is my code in index:

```<code>setup() {

    const router = useRouter()

    const state = ref(1)

    router.afterEach((to, from) => {
      if (from.name === 'quiz') {
        state.value = 2
      }
    })

    return {
      state,
    }
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to control the data after I enter the index page from quiz page, but I found that it's not possible to control the data by the method below, is it because the afterEach is global ?

Is there any other method that I can use to control the data inside index page when I came from the quiz page ?

I thought of using the vuex, if there's no other way, I'll try it.

this is my route:

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: () => import('layouts/MainLayout.vue'),
    children: [
      {
        name: 'index',
        path: '/',
        component: () => import('pages/IndexPage.vue')
      },
      {
        name: 'quiz',
        path: '/quiz',
        component: () => import('pages/QuizPage.vue')
      },
    ],
  },

this is my code in index:

setup() {

    const router = useRouter()

    const state = ref(1)

    router.afterEach((to, from) => {
      if (from.name === 'quiz') {
        state.value = 2
      }
    })

    return {
      state,
    }
  }


问:
How can i add paginator to Django filter
How can I add a paginator to the Django filter? I tried to add but whenever I am creating I got an error sometimes when the user chooses to filter by category paginator will not work all the content will show for eg: If I give paginate_by = 25 and when the user selects filter by category more than 25 data will be shown. when the paginators work filtering does not work

These is my views.py

```<code>class blogview(ListView):
    model = wallpapers
    template_name = 'blogs/blog.html'
    context_object_name = 'blogs'
    ordering = '-created_on', '-time'
    paginate_by = 2

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['filter']=WallpaperFilter(self.request.GET, queryset=self.get_queryset())
        return context
</code>```

I am trying to add paginator to these function

Body:
How can I add a paginator to the Django filter? I tried to add but whenever I am creating I got an error sometimes when the user chooses to filter by category paginator will not work all the content will show for eg: If I give paginate_by = 25 and when the user selects filter by category more than 25 data will be shown. when the paginators work filtering does not work

These is my views.py

class blogview(ListView):
    model = wallpapers
    template_name = 'blogs/blog.html'
    context_object_name = 'blogs'
    ordering = '-created_on', '-time'
    paginate_by = 2

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['filter']=WallpaperFilter(self.request.GET, queryset=self.get_queryset())
        return context

I am trying to add paginator to these function


问:
How do I keep Particular ServiceControl Audit db (Raven5) from getting larger and larger in size?
We recently upgraded Particular.ServiceControl.Audit to v4.26 and recreated our Audit instance, since from v4.26 and up new audit instances will bump up RavenDB from 3.5 to 5.4.

We did this hoping to remedy a problem in 4.25.x where compacting the audit database would not free up any disk space.

As it is, the database is still growing really large (3-400GB). To test if the data contained should actually use up all this disk space, we tried to tamper with the ServiceControl.Audit/AuditRetentionPeriod config parameter, setting it to a small value like 1 day (before value was 30 days). Naively, maybe, waiting for db to shrink at some point - expecting that retention would somehow influence disk space used. The db file remained the same size (and growing).

The docs for compacting the database in ServiceControl only mention the esent based Raven 3.5, but Raven5+ uses Raven's own Voron storage engine. There does not seem to be Particular docs describing how to compact the Voron db.

So we tried to follow the RavenDB docs for compacting the db through Raven Studio after putting the service in maintenance mode. As the screenshot shows, this operation stopped or stalled very shortly after initializing (disregard time elapsed, as we actually left it running for several hours).

We tried this several times with no luck. We can see that the disk containing the specific db has zero reads or writes, so it is definitely stalled in some way. Pressing the "Abort" button also got stuck every time, after which we resolved to simply restarting the entire service (which then seemed to bring the db back to normal operation).

So the question is: how do we keep the audit db from growing indefinitely? We can't at any point see it not growing or staying the same size, causing SSD disk costs to grow in expenses.


问:
RoR application request parameters getting overwritten with random symbol
So I have an application running Ruby 2.7.6 and Rails 6.1. Also using rom and rom-http for API calls. We have suddenly started to see our URLs in the browser, as well as server side API request parameters get overwritten with one of the symbols we use to represent an ID in the code. For example a request that should be https://sampleapi.json?currency=USD&locale=EN will be turned into https://sampleapi.json?currency=%3Asearch_id&locale=EN.

:search_id is a symbol we do use as a request parameter in many other places where we send a unique id related to a user search. But somehow, it has been injecting itself into almost all API calls as the actual value (encoded as %3Asearch_id). Sometimes we see API calls filled with almost every request parameter set this way.

The suspect is that something in activeresource or one of the rom gems has changed at some point and we never accounted for it.

There are some requests that would have &search_id as a request parameter... but with this bug the symbol :search_id itself is getting into the right side of param values.

Does this sound familiar to anyone?

Request handler code that processes data to form the final request:

```<code>def call(dataset)
      uri = URI(dataset.uri)

      uri.path += [dataset.name, dataset.path.presence].compact.join('/') + '.json'
      # recaptcha api endpoint urls
      Rails.logger.info "api endpoint is #{dataset.name}"
      if (dataset.name == '/hotels/rooms' && Settings.enable_recaptcha)
        api_path = dataset.name.split('/')
        uri = URI(Settings.recaptcha_api_gateway_url)
        uri.path += ['/', api_path.last, dataset.path.presence].compact.join('/')
      end

      if Rails.env == 'test' && dataset.name == '/hotels/rateshopping'
        dataset.params[:client_ip] = "74.125.228.110"
      end

      if dataset.request_method == :get
        uri.query = URI.encode_www_form(dataset.params.symbolize_keys.to_a.sort)
      else
        uri.query = "ip_address=#{$user_ip}"
      end

      http = Net::HTTP.new(uri.host, uri.port)

      http.use_ssl = uri.scheme.to_s == 'https'

      request_klass = Net::HTTP.const_get(ROM::Inflector.classify(dataset.request_method))

      Rails.logger.info "dataset.params: #{dataset.params}"
      request = request_klass.new(uri.request_uri)

      dataset.headers.each_with_object(request) do |(header, value), request|
         request[header.to_s] = value
      end

      if dataset.request_method == :post
        request['Content-Type'] = 'application/json; charset=utf-8'
        request.body = dataset.params.to_json
      end

      with_cache(dataset, uri) do
        with_logging(dataset, uri) { http.request(request) }
      end
    end
</code>```

Body:
So I have an application running Ruby 2.7.6 and Rails 6.1. Also using rom and rom-http for API calls. We have suddenly started to see our URLs in the browser, as well as server side API request parameters get overwritten with one of the symbols we use to represent an ID in the code. For example a request that should be https://sampleapi.json?currency=USD&locale=EN will be turned into https://sampleapi.json?currency=%3Asearch_id&locale=EN.

:search_id is a symbol we do use as a request parameter in many other places where we send a unique id related to a user search. But somehow, it has been injecting itself into almost all API calls as the actual value (encoded as %3Asearch_id). Sometimes we see API calls filled with almost every request parameter set this way.

The suspect is that something in activeresource or one of the rom gems has changed at some point and we never accounted for it.

There are some requests that would have &search_id as a request parameter... but with this bug the symbol :search_id itself is getting into the right side of param values.

Does this sound familiar to anyone?

Request handler code that processes data to form the final request:

def call(dataset)
      uri = URI(dataset.uri)

      uri.path += [dataset.name, dataset.path.presence].compact.join('/') + '.json'
      # recaptcha api endpoint urls
      Rails.logger.info "api endpoint is #{dataset.name}"
      if (dataset.name == '/hotels/rooms' && Settings.enable_recaptcha)
        api_path = dataset.name.split('/')
        uri = URI(Settings.recaptcha_api_gateway_url)
        uri.path += ['/', api_path.last, dataset.path.presence].compact.join('/')
      end

      if Rails.env == 'test' && dataset.name == '/hotels/rateshopping'
        dataset.params[:client_ip] = "74.125.228.110"
      end

      if dataset.request_method == :get
        uri.query = URI.encode_www_form(dataset.params.symbolize_keys.to_a.sort)
      else
        uri.query = "ip_address=#{$user_ip}"
      end

      http = Net::HTTP.new(uri.host, uri.port)

      http.use_ssl = uri.scheme.to_s == 'https'

      request_klass = Net::HTTP.const_get(ROM::Inflector.classify(dataset.request_method))

      Rails.logger.info "dataset.params: #{dataset.params}"
      request = request_klass.new(uri.request_uri)

      dataset.headers.each_with_object(request) do |(header, value), request|
         request[header.to_s] = value
      end

      if dataset.request_method == :post
        request['Content-Type'] = 'application/json; charset=utf-8'
        request.body = dataset.params.to_json
      end

      with_cache(dataset, uri) do
        with_logging(dataset, uri) { http.request(request) }
      end
    end


问:
Why changing folder structure causes typescript error "File is not under 'rootDir' "?
I was trying to build a MERN app. On the same repository I built two folders one for frontend client and one for backend server.

My folder structure:

```<code>  -MyProject
     -client
         -Public
         -src
         -package.json
         .......

     -server
        -dist
        -src
        -package.json
        -tsconfig.json
        ......

</code>```

Now I want to deploy my application on render.com so I change my folder structure:

New folder structure:

```<code>-MyProject
     -client
         -Public
         -src
         -package.json
         .......
     -dist
     -src
     -package.json
     -tsconfig.json
     ......

</code>```

I bring all the server files in the root dir. After doing so typescript is throwing error as

```<code> error TS6059: File 'D:/program/MyProject/client/src/App.test.tsx' is not under 'rootDir'

</code>```

It is throwing this error for all my client src files. Please guide me how to resolve this issue.

Here is my tsconfig.json:

```<code>{
  "compilerOptions": {
       "target": "es2016",
       "module": "commonjs",
       "rootDir": "./src",
       "outDir": "./dist",
       "esModuleInterop": true,
       "forceConsistentCasingInFileNames": true,
       "strict": true,
       "skipLibCheck": true
  }
}

</code>```

Body:
I was trying to build a MERN app. On the same repository I built two folders one for frontend client and one for backend server.

My folder structure:

  -MyProject
     -client
         -Public
         -src
         -package.json
         .......

     -server
        -dist
        -src
        -package.json
        -tsconfig.json
        ......

Now I want to deploy my application on render.com so I change my folder structure:

New folder structure:

-MyProject
     -client
         -Public
         -src
         -package.json
         .......
     -dist
     -src
     -package.json
     -tsconfig.json
     ......

I bring all the server files in the root dir. After doing so typescript is throwing error as

 error TS6059: File 'D:/program/MyProject/client/src/App.test.tsx' is not under 'rootDir'

It is throwing this error for all my client src files. Please guide me how to resolve this issue.

Here is my tsconfig.json:

{
  "compilerOptions": {
       "target": "es2016",
       "module": "commonjs",
       "rootDir": "./src",
       "outDir": "./dist",
       "esModuleInterop": true,
       "forceConsistentCasingInFileNames": true,
       "strict": true,
       "skipLibCheck": true
  }
}


问:
Matplotlib & Kivy: How to update inset axes xlim and ylim efficiently?
I am trying to make a data plotter using matplotlib on a Kivy-based GUI. I have 48 polynoms in same graph as Line2D. Some of them can overlap at many points. Thus I need to have an inset axes to present a zoom option. I am updating a position array with on_touch_move callback and redrawing graph in a scheduled callback using Clock.schedule_interval. The problem is updating inset plot is very slow. It takes 70ms on Windows which is negligible but in android it is very laggy. A reference snippet is below.

`

```<code>def plot_graph(self):
    self.fig, self.ax = plotter.subplots(1, 1)
    self.axin = inset_axes(self.ax, width=4, height=2)
    self.fig.tight_layout()
    for data in data_set:
        line, = self.ax.plot(data)
        self.axin.plot(data)
    self.add_widget(FigureCanvasKivyAgg(self.fig))
    Clock.schedule_interval(self.update_inset, .1)  # .2 does not work also
    mark_inset(self.ax, self.axin, loc1=1, loc2=3)

def on_touch_move(self, touch):
    if self.collide_point(*touch.pos):
        point = self.ax.transData.inverted().transform(touch.pos)
        self.inset_points = point[0] - 2.5, point[0] + 2.5, point[1] - .25, point[1] + .25

def update_inset(self, *args):
    if len(self.inset_points) == 4:     # To avoid crashes before graph drawn
        self.axin.set_xlim(self.inset_points[0], self.inset_points[1])
        self.axin.set_ylim(self.inset_points[2], self.inset_points[3])
        self.axin.figure.canvas.draw()
</code>```

`

I have tried funcAnimation but did not help, since it is not compatible with Kivy. Scheduling seems the best way to update it, but it must be faster, at least for android.

Body:
I am trying to make a data plotter using matplotlib on a Kivy-based GUI. I have 48 polynoms in same graph as Line2D. Some of them can overlap at many points. Thus I need to have an inset axes to present a zoom option. I am updating a position array with on_touch_move callback and redrawing graph in a scheduled callback using Clock.schedule_interval. The problem is updating inset plot is very slow. It takes 70ms on Windows which is negligible but in android it is very laggy. A reference snippet is below.

`

def plot_graph(self):
    self.fig, self.ax = plotter.subplots(1, 1)
    self.axin = inset_axes(self.ax, width=4, height=2)
    self.fig.tight_layout()
    for data in data_set:
        line, = self.ax.plot(data)
        self.axin.plot(data)
    self.add_widget(FigureCanvasKivyAgg(self.fig))
    Clock.schedule_interval(self.update_inset, .1)  # .2 does not work also
    mark_inset(self.ax, self.axin, loc1=1, loc2=3)

def on_touch_move(self, touch):
    if self.collide_point(*touch.pos):
        point = self.ax.transData.inverted().transform(touch.pos)
        self.inset_points = point[0] - 2.5, point[0] + 2.5, point[1] - .25, point[1] + .25

def update_inset(self, *args):
    if len(self.inset_points) == 4:     # To avoid crashes before graph drawn
        self.axin.set_xlim(self.inset_points[0], self.inset_points[1])
        self.axin.set_ylim(self.inset_points[2], self.inset_points[3])
        self.axin.figure.canvas.draw()

`

I have tried funcAnimation but did not help, since it is not compatible with Kivy. Scheduling seems the best way to update it, but it must be faster, at least for android.


问:
Shift automation system with flutter?
Hi I want to create a system that automatically creates the shifts of the workers with flutter and can intervene manually when necessary, can you help me?
thanks...

I could not set up the algorithm in my head, it is enough to have a simple mobile application, what kind of way should I follow?

Title: Shift automation system with flutter?


问:
Find an object in an array, which string field includes a specific value
I have an array of objects (comments added by users):

```<code>const myArray = [
  {
    "text": "Hello",
    "id": "11",
    "$type": "Comment"
  },
  {
    "text": "Date of birth: 01-01-2022",
    "id": "22",
    "$type": "Comment"
  },
  {
    "text": "lalala",
    "id": "33",
    "$type": "Comment"
  }
];
</code>```

My goal is:

find object, which string field text includes a phrase Date of birth

find value of id field in this object

I tried this:

```<code>let dateOfBirthComment = myArray.find(element => element.text.includes('Date of birth'));

let dateOfBirthCommentId = dateOfBirthComment.id;

console.log(dateOfBirthCommentId);
</code>```

When executing code above I get an error:

```<code>Error: Cannot read properties of null (reading 'includes')
</code>```

Unfortunately, I can't use this:

```<code>let dateOfBirthComment = array.find(element => element.text === 'Date of birth: 01-01-2022');

</code>```

Because date can be absolutely random in different cases.

Solution seems to be easy, but I'm quite new in JS and I'm really stuck. Could you please help me?

Body:
I have an array of objects (comments added by users):

const myArray = [
  {
    "text": "Hello",
    "id": "11",
    "$type": "Comment"
  },
  {
    "text": "Date of birth: 01-01-2022",
    "id": "22",
    "$type": "Comment"
  },
  {
    "text": "lalala",
    "id": "33",
    "$type": "Comment"
  }
];

My goal is:

find object, which string field text includes a phrase Date of birth

find value of id field in this object

I tried this:

let dateOfBirthComment = myArray.find(element => element.text.includes('Date of birth'));

let dateOfBirthCommentId = dateOfBirthComment.id;

console.log(dateOfBirthCommentId);

When executing code above I get an error:

Error: Cannot read properties of null (reading 'includes')

Unfortunately, I can't use this:

let dateOfBirthComment = array.find(element => element.text === 'Date of birth: 01-01-2022');

Because date can be absolutely random in different cases.

Solution seems to be easy, but I'm quite new in JS and I'm really stuck. Could you please help me?


问:
How Facebook hide their API requests in DevTool Network?
I am a newbie in Software Engineering, while I visited my profile page, I opened the Network tab in DevTool, so I do not get any API requests here. What is the technique that Facebook is using?</p>


问:
Find out with JQuery if an input field in an iFrame gets selected by user
iFrame HTML

How can I find out with JQuery if a user selects the input field in the iFrame to trigger an event? Is there a way to iterate through the iFrame elements? iFrame is on same domain. If the user input field gets selected by user I would like to call an onscreen keyboard.


问:
How to change a mouse cursor image for all windows?
I am trying to change a mouse cursor for the entire system (for each window on a display) with the help of XCursor and XInput2.

In the code below, the cursor changes. However, only for browser window =>

When I focus on other windows, the cursor is still default.

As I understand, XTranslateCoordinates() function has to return the window which is under the cursor and then I just DefineCursor for this window. It also does not work if I replace XTranslateCoordinates by  XGetInputFocus(d, &w, &revert_to).

Probably I do not understand the way cursors are going to be changed on windows. Would be extremely glad for helping!

```<code>int main(int argc, char **argv)
{
Display *display;
Window root_window;

display = XOpenDisplay(0);
root_window = XRootWindow(display, 0);

Cursor cursorDefault;
Cursor CursorClickR;
Cursor CursorClickL;

CreateCursor("1.png", cursorDefault, display);

unsigned char mask_bytes[(XI_LASTEVENT + 7) / 8] = {0}; /* must be zeroed! */
XISetMask(mask_bytes, XI_RawMotion);

XIEventMask evmasks[1];
evmasks[0].deviceid = XIAllMasterDevices;
evmasks[0].mask_len = sizeof(mask_bytes);
evmasks[0].mask = mask_bytes;
XISelectEvents(display, root_window, evmasks, 1);

XEvent xevent;
while (1)
{
    XNextEvent(display, &xevent);
    XGetEventData(display, &xevent.xcookie);

    Window root_return, child_return;
    int root_x_return, root_y_return;
    int win_x_return, win_y_return;
    unsigned int mask_return;

    XQueryPointer(display, root_window, &root_return, &child_return,
                  &root_x_return, &root_y_return,
                  &win_x_return, &win_y_return,
                  &mask_return);

    int local_x, local_y;
    XTranslateCoordinates(display, root_window, child_return,
                          root_x_return, root_y_return,
                          &local_x, &local_y, &child_return);

    if (child_return)
        XDefineCursor(display, child_return, cursorDefault);
}

XCloseDisplay(display);

return 0;
}
</code>```

Body:
I am trying to change a mouse cursor for the entire system (for each window on a display) with the help of XCursor and XInput2.

In the code below, the cursor changes. However, only for browser window =>

When I focus on other windows, the cursor is still default.

As I understand, XTranslateCoordinates() function has to return the window which is under the cursor and then I just DefineCursor for this window. It also does not work if I replace XTranslateCoordinates by  XGetInputFocus(d, &w, &revert_to).

Probably I do not understand the way cursors are going to be changed on windows. Would be extremely glad for helping!

int main(int argc, char **argv)
{
Display *display;
Window root_window;

display = XOpenDisplay(0);
root_window = XRootWindow(display, 0);

Cursor cursorDefault;
Cursor CursorClickR;
Cursor CursorClickL;

CreateCursor("1.png", cursorDefault, display);

unsigned char mask_bytes[(XI_LASTEVENT + 7) / 8] = {0}; /* must be zeroed! */
XISetMask(mask_bytes, XI_RawMotion);

XIEventMask evmasks[1];
evmasks[0].deviceid = XIAllMasterDevices;
evmasks[0].mask_len = sizeof(mask_bytes);
evmasks[0].mask = mask_bytes;
XISelectEvents(display, root_window, evmasks, 1);

XEvent xevent;
while (1)
{
    XNextEvent(display, &xevent);
    XGetEventData(display, &xevent.xcookie);

    Window root_return, child_return;
    int root_x_return, root_y_return;
    int win_x_return, win_y_return;
    unsigned int mask_return;

    XQueryPointer(display, root_window, &root_return, &child_return,
                  &root_x_return, &root_y_return,
                  &win_x_return, &win_y_return,
                  &mask_return);

    int local_x, local_y;
    XTranslateCoordinates(display, root_window, child_return,
                          root_x_return, root_y_return,
                          &local_x, &local_y, &child_return);

    if (child_return)
        XDefineCursor(display, child_return, cursorDefault);
}

XCloseDisplay(display);

return 0;
}


问:
Is there a way to modify this query and make it more simple?
I am working on a MySQl data base and  have several tables that I need to join based on a temporary table that I created (layer_2).

Each table that I join has the join key for the next table;

E.g. layer_2 joins with "colegios" table, then the result will have the join key for the next table "ciudades". and finally the result will have the Join key for the next table "departamentos".

from what I got it works but I want to know if there is a way to simplify this?

```<code>Select
    cuestionario_id,
    tiempo,
    nro_preguntas,
    nro_preguntas_correctas,
    tipo_usuario,
    fecha_creacion_cuestionario,
    con_tiempo,
    det_cuestionarios_id,
    respuesta_seleccionada,
    pregunta_id,
    enunciado,
    respuesta_correcta,
    usuarios_id,
    dominio_correo,
    tipo_institucion,
    materia,
    tematica,
    area,
    nombre_colegios,
    direccion_colegios,
    nombre_ciudades,
    redsaber.departamentos.nombre as nombre_departamentos
From
(
Select
    cuestionario_id,
    tiempo,
    nro_preguntas,
    nro_preguntas_correctas,
    cuestionable_id,
    tipo_usuario,
    fecha_creacion_cuestionario,
    con_tiempo,
    det_cuestionarios_id,
    respuesta_seleccionada,
    pregunta_id,
    enunciado,
    respuesta_correcta,
    usuarios_id,
    dominio_correo,
    cole_ciud_id,
    tipo_institucion,
    materia,
    tematica,
    area,
    combine_ciudad_id,
    nombre_colegios,
    direccion_colegios,
    redsaber.ciudades.nombre as nombre_ciudades,
    departamento_id
From
(Select
    cuestionario_id,
    tiempo,
    nro_preguntas,
    nro_preguntas_correctas,
    cuestionable_id,
    tipo_usuario,
    fecha_creacion_cuestionario,
    con_tiempo,
    det_cuestionarios_id,
    respuesta_seleccionada,
    pregunta_id,
    enunciado,
    respuesta_correcta,
    usuarios_id,
    dominio_correo,
    cole_ciud_id,
    tipo_institucion,
    materia,
    tematica,
    area,
    ifnull(redsaber.colegios.ciudad_id,cole_ciud_id) as combine_ciudad_id,
    redsaber.colegios.nombre as nombre_colegios,
    redsaber.colegios.direccion as direccion_colegios
From layer_2
Left Join redsaber.colegios on layer_2.cole_ciud_id = redsaber.colegios.id
    AND tipo_institucion = 'Colegio') as layer_3
    Left Join redsaber.ciudades on combine_ciudad_id = redsaber.ciudades.id) as layer_4
    Left Join redsaber.departamentos on departamento_id = redsaber.departamentos.id

</code>```

Body:
I am working on a MySQl data base and  have several tables that I need to join based on a temporary table that I created (layer_2).

Each table that I join has the join key for the next table;

E.g. layer_2 joins with "colegios" table, then the result will have the join key for the next table "ciudades". and finally the result will have the Join key for the next table "departamentos".

from what I got it works but I want to know if there is a way to simplify this?

Select
    cuestionario_id,
    tiempo,
    nro_preguntas,
    nro_preguntas_correctas,
    tipo_usuario,
    fecha_creacion_cuestionario,
    con_tiempo,
    det_cuestionarios_id,
    respuesta_seleccionada,
    pregunta_id,
    enunciado,
    respuesta_correcta,
    usuarios_id,
    dominio_correo,
    tipo_institucion,
    materia,
    tematica,
    area,
    nombre_colegios,
    direccion_colegios,
    nombre_ciudades,
    redsaber.departamentos.nombre as nombre_departamentos
From
(
Select
    cuestionario_id,
    tiempo,
    nro_preguntas,
    nro_preguntas_correctas,
    cuestionable_id,
    tipo_usuario,
    fecha_creacion_cuestionario,
    con_tiempo,
    det_cuestionarios_id,
    respuesta_seleccionada,
    pregunta_id,
    enunciado,
    respuesta_correcta,
    usuarios_id,
    dominio_correo,
    cole_ciud_id,
    tipo_institucion,
    materia,
    tematica,
    area,
    combine_ciudad_id,
    nombre_colegios,
    direccion_colegios,
    redsaber.ciudades.nombre as nombre_ciudades,
    departamento_id
From
(Select
    cuestionario_id,
    tiempo,
    nro_preguntas,
    nro_preguntas_correctas,
    cuestionable_id,
    tipo_usuario,
    fecha_creacion_cuestionario,
    con_tiempo,
    det_cuestionarios_id,
    respuesta_seleccionada,
    pregunta_id,
    enunciado,
    respuesta_correcta,
    usuarios_id,
    dominio_correo,
    cole_ciud_id,
    tipo_institucion,
    materia,
    tematica,
    area,
    ifnull(redsaber.colegios.ciudad_id,cole_ciud_id) as combine_ciudad_id,
    redsaber.colegios.nombre as nombre_colegios,
    redsaber.colegios.direccion as direccion_colegios
From layer_2
Left Join redsaber.colegios on layer_2.cole_ciud_id = redsaber.colegios.id
    AND tipo_institucion = 'Colegio') as layer_3
    Left Join redsaber.ciudades on combine_ciudad_id = redsaber.ciudades.id) as layer_4
    Left Join redsaber.departamentos on departamento_id = redsaber.departamentos.id


问:
Error compiling project with NodeJs and Gulp
I'm running the mvn clean install command to compile my project which is made with java in the backend and angular in the front.
I do this on Linux normally but I'm configuring the environment on windows and I'm getting errors

Error

```<code>[10:52:34] Starting '<anonymous>'...
internal/modules/cjs/loader.js:883
  throw err;
  ^

Error: Cannot find module 'D:\git\java\flextotal\src\main\webapp\build'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
    at Function.Module._load (internal/modules/cjs/loader.js:725:27)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}
[10:52:34] '<anonymous>' errored after 45 ms
[10:52:34] Error: 1
    at formatError (D:\git\java\flextotal\src\main\webapp\node_modules\gulp\node_modules\gulp-cli\lib\versioned\^4.0.0\format-error.js:21:10)
    at Gulp.<anonymous> (D:\git\java\flextotal\src\main\webapp\node_modules\gulp\node_modules\gulp-cli\lib\versioned\^4.0.0\log\events.js:33:15)
    at Gulp.emit (events.js:327:22)
    at Gulp.EventEmitter.emit (domain.js:467:12)
    at Object.error (D:\git\java\flextotal\src\main\webapp\node_modules\undertaker\lib\helpers\createExtensions.js:61:10)
    at handler (D:\git\java\flextotal\src\main\webapp\node_modules\now-and-later\lib\mapSeries.js:47:14)
    at f (D:\git\java\flextotal\src\main\webapp\node_modules\once\once.js:25:25)
    at f (D:\git\java\flextotal\src\main\webapp\node_modules\once\once.js:25:25)
    at tryCatch (D:\git\java\flextotal\src\main\webapp\node_modules\async-done\index.js:24:15)
    at done (D:\git\java\flextotal\src\main\webapp\node_modules\async-done\index.js:40:12)
[10:52:34] 'cliBuildProd' errored after 83 ms
[10:52:34] 'copyReleaseBundles' errored after 89 ms
[10:52:34] 'buildRelease' errored after 90 ms
[10:52:34] '<anonymous>' errored after 91 ms
[10:52:34] 'default' errored after 92 ms
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! flextotal@1.0.0 build:release: `gulp --release`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the flextotal@1.0.0 build:release script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
</code>```

My Gulp File

```<code>process.setMaxListeners(Number.POSITIVE_INFINITY);
const cp = require('child_process');
const gulp = require('gulp');
const del = require('del');
const browserSync = require('browser-sync');
const plugins = require('gulp-load-plugins')();
const tslint = require("tslint");
const gulpMultiProcess = require('gulp-multi-process');
const fs = require('fs');

const debug = process.argv.indexOf("--development") > -1;
const useAot = !debug; // constante usada para testes sem AOT
console.log("debug: " + debug);

const ngBuildArgs = ['build', '--deploy-url', 'dist/'];
const ngBuildArgsProd = [...ngBuildArgs, '--prod', '--extract-licenses', 'false'];
// o cli não está gerando os paths corretos sem usar extract-css
const ngBuildArgsDebug = [...ngBuildArgs];
const ngBuildArgsWatch = [...ngBuildArgsDebug, '--watch', '--no-delete-output-path', '--progress', 'false'];

if (debug) {
    var localConfig = JSON.parse(fs.readFileSync('./local-config.json'));
    if (!localConfig.deployPath) {
        throw new Error("deployPath não definido no local-config.json");
    }
    if (!localConfig.applicationUrl) {
        throw new Error("applicationUrl não definido no local-config.json");
    }
}

// workaround pra remover reflect do build aot
// https://github.com/angular/angular-cli/issues/6325
gulp.task('processPolyfills', gulp.series(function() {
    return gulp.src("app/polyfills." + (debug ? "development" : "production") + ".ts")
        .pipe(plugins.rename("polyfills.ts"))
        .pipe(gulp.dest("app/"));
}));

gulp.task('clean', (done) => {
    del.sync(['./app.jsp', 'dist/**/*', 'dist-aot']);
    done();
});

function copyAppJsp() {
    const html = fs.readFileSync('./dist-aot/index.html', 'utf-8');
    fs.writeFileSync('app.jsp', html);
    if (debug) {
        fs.writeFileSync(localConfig.deployPath + 'app.jsp', html);
    }
}

gulp.task('compileDebug', gulp.series(['processPolyfills'], function(cb) {
    const ng = cp.spawn(process.execPath, ngBuildArgsDebug, { stdio: 'inherit' });
    ng.on('close', code => cb(code));
}));

gulp.task('copyDebugBundles', gulp.series(['compileDebug'], function() {
    copyAppJsp()
    return gulp.src(['dist-aot/**/*'])
        .pipe(gulp.dest('dist'));
}));

gulp.task('startNgWatch', gulp.series(['processPolyfills'], function(done) {
    // criamos o diretório antes pois o watch não funciona com diretórios
    // inexistentes (que serão criados no ng build, e não tem como verificar quando)
    fs.mkdirSync('dist-aot');

    cp.spawn(process.execPath, ngBuildArgsWatch, { stdio: 'inherit' });
    done();
}));

gulp.task('multiProcessBundle', gulp.series(function(cb) {
    // por padrão o node executa tudo na mesma thread,
    // este plugin usa child_process pra torná-lo multi processo
    return gulpMultiProcess(['lint'], cb);
}));

gulp.task('watch', gulp.series(['clean', 'startNgWatch', 'multiProcessBundle'], function() {
    let firstFile = true;
    // plugin utilizado porque o watch padrão do gulp não detecta criação de arquivos
    return plugins.watch('dist-aot/**/*', { readDelay: 500 })
        .pipe(gulp.dest('dist'))
        .pipe(gulp.dest(localConfig.deployPath + 'dist'))
        .pipe(plugins.tap(function(file) {
            if (file.path.endsWith("/index.html")) {
                copyAppJsp();
            }

            if (firstFile) {
                firstFile = false;
                browserSync.init({
                    proxy: localConfig.applicationUrl,
                    browser: localConfig.browser,
                    ghostMode: false,
                    reloadDebounce: 500
                });
            } else {
                browserSync.reload(file);
            }
        }));
}));

gulp.task('lint', gulp.series(function() {
    var program = tslint.Linter.createProgram("./tsconfig.json");
    return gulp.src('app/**/*.ts')
        .pipe(plugins.tslint({
            program: program
        }))
        .pipe(plugins.tslint.report({
            allowWarnings: true
        }));
}))

gulp.task('cliBuildProd', gulp.series(['processPolyfills'], function(cb) {
    const ng = cp.spawn(process.execPath, ngBuildArgsProd, { stdio: 'inherit' });
    ng.on('close', code => cb(code));
}));

gulp.task('copyReleaseBundles', gulp.series(['cliBuildProd'], function() {
    copyAppJsp()
    return gulp.src(['dist-aot/**/*', '!dist-aot/index.html'])
        .pipe(gulp.dest('dist'));
}));

gulp.task('_test', gulp.series(gulp.parallel(['clean', 'copyDebugBundles', 'multiProcessBundle']), function(cb) {
    const ng = cp.spawn(process.execPath, ['test', '--single-run'], { stdio: 'inherit' });
    ng.on('close', code => cb(code));
}));

gulp.task('buildDebug', gulp.series(gulp.parallel(['clean', 'copyDebugBundles', 'multiProcessBundle']), function() {
    return del(['dist-aot']);
}));

gulp.task('buildRelease', gulp.series(gulp.parallel(['clean', 'copyReleaseBundles', 'multiProcessBundle']), function() {
    return del(['dist-aot']);
}));

gulp.task('test', gulp.series('_test', function() {
    return del(['dist-aot']);
}));

function runTaskIf(condition, task) {
    task = gulp.series(task) // make sure we have a function that takes callback as first argument
    return function(cb) {
        if (condition()) {
            task(cb)
        } else {
            cb()
        }
    }
}

isDebug = function() {
    return debug;
}
isRelease = function() {
    return !debug;
}

gulp.task('default', gulp.parallel([
    runTaskIf(isDebug, 'buildDebug'),
    runTaskIf(isRelease, 'buildRelease')
]));
</code>```

Something seems to have changed in Windows compared to Linux
However, I redid the environment with the same version for all installations

I would be grateful if anyone could shed some light on this matter.

I tried changes in the Gulp file and also tried deleting the package-lock.json folder and the NodeModules folder and running npm install again
but without success

Body:
I'm running the mvn clean install command to compile my project which is made with java in the backend and angular in the front.
I do this on Linux normally but I'm configuring the environment on windows and I'm getting errors

Error

[10:52:34] Starting '<anonymous>'...
internal/modules/cjs/loader.js:883
  throw err;
  ^

Error: Cannot find module 'D:\git\java\flextotal\src\main\webapp\build'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
    at Function.Module._load (internal/modules/cjs/loader.js:725:27)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}
[10:52:34] '<anonymous>' errored after 45 ms
[10:52:34] Error: 1
    at formatError (D:\git\java\flextotal\src\main\webapp\node_modules\gulp\node_modules\gulp-cli\lib\versioned\^4.0.0\format-error.js:21:10)
    at Gulp.<anonymous> (D:\git\java\flextotal\src\main\webapp\node_modules\gulp\node_modules\gulp-cli\lib\versioned\^4.0.0\log\events.js:33:15)
    at Gulp.emit (events.js:327:22)
    at Gulp.EventEmitter.emit (domain.js:467:12)
    at Object.error (D:\git\java\flextotal\src\main\webapp\node_modules\undertaker\lib\helpers\createExtensions.js:61:10)
    at handler (D:\git\java\flextotal\src\main\webapp\node_modules\now-and-later\lib\mapSeries.js:47:14)
    at f (D:\git\java\flextotal\src\main\webapp\node_modules\once\once.js:25:25)
    at f (D:\git\java\flextotal\src\main\webapp\node_modules\once\once.js:25:25)
    at tryCatch (D:\git\java\flextotal\src\main\webapp\node_modules\async-done\index.js:24:15)
    at done (D:\git\java\flextotal\src\main\webapp\node_modules\async-done\index.js:40:12)
[10:52:34] 'cliBuildProd' errored after 83 ms
[10:52:34] 'copyReleaseBundles' errored after 89 ms
[10:52:34] 'buildRelease' errored after 90 ms
[10:52:34] '<anonymous>' errored after 91 ms
[10:52:34] 'default' errored after 92 ms
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! flextotal@1.0.0 build:release: `gulp --release`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the flextotal@1.0.0 build:release script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)

My Gulp File

process.setMaxListeners(Number.POSITIVE_INFINITY);
const cp = require('child_process');
const gulp = require('gulp');
const del = require('del');
const browserSync = require('browser-sync');
const plugins = require('gulp-load-plugins')();
const tslint = require("tslint");
const gulpMultiProcess = require('gulp-multi-process');
const fs = require('fs');

const debug = process.argv.indexOf("--development") > -1;
const useAot = !debug; // constante usada para testes sem AOT
console.log("debug: " + debug);

const ngBuildArgs = ['build', '--deploy-url', 'dist/'];
const ngBuildArgsProd = [...ngBuildArgs, '--prod', '--extract-licenses', 'false'];
// o cli não está gerando os paths corretos sem usar extract-css
const ngBuildArgsDebug = [...ngBuildArgs];
const ngBuildArgsWatch = [...ngBuildArgsDebug, '--watch', '--no-delete-output-path', '--progress', 'false'];

if (debug) {
    var localConfig = JSON.parse(fs.readFileSync('./local-config.json'));
    if (!localConfig.deployPath) {
        throw new Error("deployPath não definido no local-config.json");
    }
    if (!localConfig.applicationUrl) {
        throw new Error("applicationUrl não definido no local-config.json");
    }
}

// workaround pra remover reflect do build aot
// https://github.com/angular/angular-cli/issues/6325
gulp.task('processPolyfills', gulp.series(function() {
    return gulp.src("app/polyfills." + (debug ? "development" : "production") + ".ts")
        .pipe(plugins.rename("polyfills.ts"))
        .pipe(gulp.dest("app/"));
}));

gulp.task('clean', (done) => {
    del.sync(['./app.jsp', 'dist/**/*', 'dist-aot']);
    done();
});

function copyAppJsp() {
    const html = fs.readFileSync('./dist-aot/index.html', 'utf-8');
    fs.writeFileSync('app.jsp', html);
    if (debug) {
        fs.writeFileSync(localConfig.deployPath + 'app.jsp', html);
    }
}

gulp.task('compileDebug', gulp.series(['processPolyfills'], function(cb) {
    const ng = cp.spawn(process.execPath, ngBuildArgsDebug, { stdio: 'inherit' });
    ng.on('close', code => cb(code));
}));

gulp.task('copyDebugBundles', gulp.series(['compileDebug'], function() {
    copyAppJsp()
    return gulp.src(['dist-aot/**/*'])
        .pipe(gulp.dest('dist'));
}));

gulp.task('startNgWatch', gulp.series(['processPolyfills'], function(done) {
    // criamos o diretório antes pois o watch não funciona com diretórios
    // inexistentes (que serão criados no ng build, e não tem como verificar quando)
    fs.mkdirSync('dist-aot');

    cp.spawn(process.execPath, ngBuildArgsWatch, { stdio: 'inherit' });
    done();
}));

gulp.task('multiProcessBundle', gulp.series(function(cb) {
    // por padrão o node executa tudo na mesma thread,
    // este plugin usa child_process pra torná-lo multi processo
    return gulpMultiProcess(['lint'], cb);
}));

gulp.task('watch', gulp.series(['clean', 'startNgWatch', 'multiProcessBundle'], function() {
    let firstFile = true;
    // plugin utilizado porque o watch padrão do gulp não detecta criação de arquivos
    return plugins.watch('dist-aot/**/*', { readDelay: 500 })
        .pipe(gulp.dest('dist'))
        .pipe(gulp.dest(localConfig.deployPath + 'dist'))
        .pipe(plugins.tap(function(file) {
            if (file.path.endsWith("/index.html")) {
                copyAppJsp();
            }

            if (firstFile) {
                firstFile = false;
                browserSync.init({
                    proxy: localConfig.applicationUrl,
                    browser: localConfig.browser,
                    ghostMode: false,
                    reloadDebounce: 500
                });
            } else {
                browserSync.reload(file);
            }
        }));
}));

gulp.task('lint', gulp.series(function() {
    var program = tslint.Linter.createProgram("./tsconfig.json");
    return gulp.src('app/**/*.ts')
        .pipe(plugins.tslint({
            program: program
        }))
        .pipe(plugins.tslint.report({
            allowWarnings: true
        }));
}))

gulp.task('cliBuildProd', gulp.series(['processPolyfills'], function(cb) {
    const ng = cp.spawn(process.execPath, ngBuildArgsProd, { stdio: 'inherit' });
    ng.on('close', code => cb(code));
}));

gulp.task('copyReleaseBundles', gulp.series(['cliBuildProd'], function() {
    copyAppJsp()
    return gulp.src(['dist-aot/**/*', '!dist-aot/index.html'])
        .pipe(gulp.dest('dist'));
}));

gulp.task('_test', gulp.series(gulp.parallel(['clean', 'copyDebugBundles', 'multiProcessBundle']), function(cb) {
    const ng = cp.spawn(process.execPath, ['test', '--single-run'], { stdio: 'inherit' });
    ng.on('close', code => cb(code));
}));

gulp.task('buildDebug', gulp.series(gulp.parallel(['clean', 'copyDebugBundles', 'multiProcessBundle']), function() {
    return del(['dist-aot']);
}));

gulp.task('buildRelease', gulp.series(gulp.parallel(['clean', 'copyReleaseBundles', 'multiProcessBundle']), function() {
    return del(['dist-aot']);
}));

gulp.task('test', gulp.series('_test', function() {
    return del(['dist-aot']);
}));

function runTaskIf(condition, task) {
    task = gulp.series(task) // make sure we have a function that takes callback as first argument
    return function(cb) {
        if (condition()) {
            task(cb)
        } else {
            cb()
        }
    }
}

isDebug = function() {
    return debug;
}
isRelease = function() {
    return !debug;
}

gulp.task('default', gulp.parallel([
    runTaskIf(isDebug, 'buildDebug'),
    runTaskIf(isRelease, 'buildRelease')
]));

Something seems to have changed in Windows compared to Linux
However, I redid the environment with the same version for all installations

I would be grateful if anyone could shed some light on this matter.

I tried changes in the Gulp file and also tried deleting the package-lock.json folder and the NodeModules folder and running npm install again
but without success


问:
Odoo Partner Ledger Report Customization
I need to customize the view of the Partner Ledger Report in Odoo 15 (from Accounting -> Reporting -> Partner Ledger) but I can't find the detailed view.

It seems very dynamic and it appears to get built during runtime.

I couldn't find it in (Settings -> Technical -> Reports).

How can I customize the view of this report or even change it from PDF to HTML?


问:
Slurm multiple job arrays on a single GPU?
I want to ask if it is possible to run multiple jobs (via job-array) on a single GPU (i.e. sharing the GPU). I am asking because each task only takes up 3GB of GPU RAM, and hence if it would be better if I could run 8 python scripts on a single GPU?

I tried doing something like :

```<code>#!/bin/bash

#SBATCH --job-name parallel_finetune  #job name을 다르게 하기 위해서
#SBATCH --nodes=1
#SBATCH --nodelist=node3 #used node4
#SBATCH -t 48:00:00 # Time for running job #길게 10일넘게 잡음
#SBATCH -o ./shell_output/output_%A_%a.output
#SBATCH -e ./shell_output/error_%A_%a.error
#SBATCH --ntasks=8
#SBATCH --mem-per-cpu=4GB
#SBATCH --gpus=1
#SBATCH --cpus-per-task=2
#SBATCH --array=0-7
</code>```

(where I didn't use --gpus-per-task) I thought that since --gpu is specified as opposed to --gpus-per-task, the slum would allocate seperate cpus (as specified by --cpus-per-task), but share a single GPU. However, this is not the case and each task gets one GPU. Is there a way to do this?

Thank you in advance for anyone's help!

Body:
I want to ask if it is possible to run multiple jobs (via job-array) on a single GPU (i.e. sharing the GPU). I am asking because each task only takes up 3GB of GPU RAM, and hence if it would be better if I could run 8 python scripts on a single GPU?

I tried doing something like :

#!/bin/bash

#SBATCH --job-name parallel_finetune  #job name을 다르게 하기 위해서
#SBATCH --nodes=1
#SBATCH --nodelist=node3 #used node4
#SBATCH -t 48:00:00 # Time for running job #길게 10일넘게 잡음
#SBATCH -o ./shell_output/output_%A_%a.output
#SBATCH -e ./shell_output/error_%A_%a.error
#SBATCH --ntasks=8
#SBATCH --mem-per-cpu=4GB
#SBATCH --gpus=1
#SBATCH --cpus-per-task=2
#SBATCH --array=0-7

(where I didn't use --gpus-per-task) I thought that since --gpu is specified as opposed to --gpus-per-task, the slum would allocate seperate cpus (as specified by --cpus-per-task), but share a single GPU. However, this is not the case and each task gets one GPU. Is there a way to do this?

Thank you in advance for anyone's help!


问:
How to make a higher order component with parameters?
I have two components that use the same logic. They have a useEffect and UseState, but one of them uses the parameters. I need to move all the same logic to a Higher Order Component. How can I make a higher order component?

//Сomponent1

function Сomponent1List({ onEntityDetailsClick, propsToDisplay, fetchMethod }) {
const [entities, setEntities] = useState(null);
  useEffect(() => {
    fetchMethod().then((res) => {
      setEntities(res);
      console.log("Text: ", res);
    });
  }, []);

}

export default withText(Сomponent1List);

//Сomponent2

function Сomponent2Details({ fetchMethod, params, propsToDisplay }) {
  const [entity, setEntity] = useState(null);
  useEffect(() => {
    setEntity(null);
    fetchMethod(params).then((res) => {
      setEntity(res);
      console.log("Text: ", res);
    });
  }, [params]);

}

export default withText(Сomponent2Details);

//Higher-Order Components

const withText = (WrappedComponent) => {
  return (props) => {

    return <WrappedComponent />;
  };
};

export default withText;```


问:
how to implement "beforeAll", "afterAll" or "afterEach" in gherkins with the framework CodeceptsJS with Playwright
I am using the framework CodeceptsJS with Playwright (https://codecept.io/playwright/) and I saw in the website that the tag "Background" is the "beforeEach", but I do not find out how to implement "beforeAll", "afterAll" or "afterEach".

Any suggestion would be appreciate, thank you for reading and replying it.


问:
Flutter How to know Workmanager has finished
I use Flutter with the plugin Workmanager. I did not find a way to know if the background task has finished for registerOneOffTask. I had ideas with RxSharedPreferences that I write something from the Workmanager into SharedPreferences and then observe it in my main application but this seems to be quite dirty.

Is there an elegant way to know if the Workmanager task is finished?


问:
Splitting and translating object type column values to multiple columns in a dataframe

I'm working on a DA project on a job post dataset that was scraped from linkedin. I'm trying to split the 'criteria' column and create separate columns for each criterion (i.e. seniority level, employment type, job function, industries). I'll also need to translate the arabic texts contained in the column to english, instead of deleting the rows.

I was able to translate the arabic texts (thanks to the stack overflow community) but I'm struggling to separate the 'criteria' column or the 'new_cr' column i just created. As always your help is much appreciated.
What I'm expecting to get is new columns named after each criterion and the values in the rows.

```<code> seniority_level    employment_type  job_function                industries

 Entry level          Full-time      Information technology      Software Development
</code>```

Body:
I'm working on a DA project on a job post dataset that was scraped from linkedin. I'm trying to split the 'criteria' column and create separate columns for each criterion (i.e. seniority level, employment type, job function, industries). I'll also need to translate the arabic texts contained in the column to english, instead of deleting the rows.

I was able to translate the arabic texts (thanks to the stack overflow community) but I'm struggling to separate the 'criteria' column or the 'new_cr' column i just created. As always your help is much appreciated.
What I'm expecting to get is new columns named after each criterion and the values in the rows.

 seniority_level    employment_type  job_function                industries

 Entry level          Full-time      Information technology      Software Development


问:
How to load properties in Spring Boot Library Project with environments?
I have a Spring Boot Security Library project as package/dependency. Now I want to add properties for different environments [local,dev,stage,prod], so I added file security-properties.yml in resources directory as shown below

```<code>security:
  jwt:
    secret: xxxxxxxxxxxxxxxxxxxx

---

spring:
  profiles: local

security:
  # Proxy
  proxy:
    authUrl: http://localhost:8080
  # JWT
  jwt:
    expiryMs: 14400000

---

spring:
  profiles: dev

security:
  # Proxy
  proxy:
    authUrl: https://example-dev.com
  # JWT
  jwt:
    expiryMs: 43200000

---

spring:
  profiles: stage

security:
  # Proxy
  proxy:
    authUrl: https://example-stage.com
  # JWT
  jwt:
    expiryMs: 43200000

---

spring:
  profiles: prod

security:
  # Proxy
  proxy:
    authUrl: https://example.com
  # JWT
  jwt:
    expiryMs: 43200000
</code>```

Now to load the properties I created SecurityProperties.class

```<code>@Getter
@Setter
@Configuration
@PropertySource(value = "classpath:security-properties.yml", factory = YamlPropertySourceFactory.class)
@ConfigurationProperties(prefix = "security")
public class SecurityProperties {

    private Jwt jwt = new Jwt();

    private Proxy proxy = new Proxy();

    @Getter
    @Setter
    public static class Jwt {

        private String tokenHeader = "Authorization";

        private String tokenHead = "Bearer ";

        private String secret;

        private Long expiryMs = 43200000L;
    }

    @Getter
    @Setter
    public static class Proxy {

        private String authUrl;
    }

    @Getter
    @Setter
    public static class IgnoreUrls {

        private String[] get = {};

        private String[] post = {};

        private String[] patch = {};

        private String[] delete = {};
    }
}
</code>```

and YamlPropertySourceFactory.class to load yaml file

```<code>public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
        yamlFactory.setResources(resource.getResource());
        yamlFactory.afterPropertiesSet();
        Properties properties = yamlFactory.getObject();
        assert properties != null;
        return new PropertiesPropertySource(Objects.requireNonNull(resource.getResource().getFilename()), properties);
    }
}
</code>```

Now after publishing the artifact for the library project and injecting the dependency in main project, I am unable to load security properties for environments from the library project.

Note: I can add security properties in application-{profile}.yml file in main project , it works

How to add properties in Spring Boot Library projects [dependency] ?

Body:
I have a Spring Boot Security Library project as package/dependency. Now I want to add properties for different environments [local,dev,stage,prod], so I added file security-properties.yml in resources directory as shown below

security:
  jwt:
    secret: xxxxxxxxxxxxxxxxxxxx

---

spring:
  profiles: local

security:
  # Proxy
  proxy:
    authUrl: http://localhost:8080
  # JWT
  jwt:
    expiryMs: 14400000

---

spring:
  profiles: dev

security:
  # Proxy
  proxy:
    authUrl: https://example-dev.com
  # JWT
  jwt:
    expiryMs: 43200000

---

spring:
  profiles: stage

security:
  # Proxy
  proxy:
    authUrl: https://example-stage.com
  # JWT
  jwt:
    expiryMs: 43200000

---

spring:
  profiles: prod

security:
  # Proxy
  proxy:
    authUrl: https://example.com
  # JWT
  jwt:
    expiryMs: 43200000

Now to load the properties I created SecurityProperties.class

@Getter
@Setter
@Configuration
@PropertySource(value = "classpath:security-properties.yml", factory = YamlPropertySourceFactory.class)
@ConfigurationProperties(prefix = "security")
public class SecurityProperties {

    private Jwt jwt = new Jwt();

    private Proxy proxy = new Proxy();

    @Getter
    @Setter
    public static class Jwt {

        private String tokenHeader = "Authorization";

        private String tokenHead = "Bearer ";

        private String secret;

        private Long expiryMs = 43200000L;
    }

    @Getter
    @Setter
    public static class Proxy {

        private String authUrl;
    }

    @Getter
    @Setter
    public static class IgnoreUrls {

        private String[] get = {};

        private String[] post = {};

        private String[] patch = {};

        private String[] delete = {};
    }
}

and YamlPropertySourceFactory.class to load yaml file

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
        yamlFactory.setResources(resource.getResource());
        yamlFactory.afterPropertiesSet();
        Properties properties = yamlFactory.getObject();
        assert properties != null;
        return new PropertiesPropertySource(Objects.requireNonNull(resource.getResource().getFilename()), properties);
    }
}

Now after publishing the artifact for the library project and injecting the dependency in main project, I am unable to load security properties for environments from the library project.

Note: I can add security properties in application-{profile}.yml file in main project , it works

How to add properties in Spring Boot Library projects [dependency] ?


问:
How do I retrieve all polymorphic relations for one model?
I have setup a User model to be able to be linked with a polymorphic many to many to 3 models, let's call them A, B and C.

I have setup the models as follows:

// User.php

public function a(): MorphToMany
{
    return $this->morphedByMany(A::class, 'shareable')->withPivot('view_mode');
}

public function b(): MorphToMany
{
    return $this->morphedByMany(B::class, 'shareable')->withPivot('view_mode');
}

public function c(): MorphToMany
{
    return $this->morphedByMany(C::class, 'shareable')->withPivot('view_mode');
}

// A, B and C.php

public function users(): MorphToMany
{
    return $this->morphToMany(User::class, 'shareable');
}
```
<p>Of course I created a pivot table to store the relations.</p>
<p>I am now trying to find a way to find ALL relations linked to a given user based on the pivot table. Let's say this is currently my data:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>user_id</th>
<th>view_mode</th>
<th>shareable_type</th>
<th>shareable_id</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>RW</td>
<td>App\Models\A</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>R</td>
<td>App\Models\A</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>W</td>
<td>App\Models\B</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>R</td>
<td>App\Models\A</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>W</td>
<td>App\Models\C</td>
<td>8</td>
</tr>
</tbody>
</table>
</div>
<p>How can I retrieve all the related content for User with id 1?</p>
<p>My goal would be for it to look like this:</p>
```relations: [
    a: [
        - A entity with id 1
        - A entity with id 2
    ],
    b: [
        - B entity with id 5
    ],
    c: [
        - C entity with id 8
    ]
]
```
<p>I tried by created a model named <code>Shareable</code>, and adding the following:</p>
```protected $table = 'shareables';

public function shareable()
{
    return $this->morphTo();
}

public function a()
{
    return $this->morphedByMany(A::class, 'shareable');
}
```
<p>I then added the following to the User model:</p>
```public function shared()
{
    return $this->hasMany(Shareable::class)->with('a');
}
```
<p>But when I call it by doing</p>
```$user->shared
```

I don't get my a instances, only an empty collection.

What am I doing wrong?

Body:
I have setup a User model to be able to be linked with a polymorphic many to many to 3 models, let's call them A, B and C.

I have setup the models as follows:

// User.php

public function a(): MorphToMany
{
    return $this->morphedByMany(A::class, 'shareable')->withPivot('view_mode');
}

public function b(): MorphToMany
{
    return $this->morphedByMany(B::class, 'shareable')->withPivot('view_mode');
}

public function c(): MorphToMany
{
    return $this->morphedByMany(C::class, 'shareable')->withPivot('view_mode');
}

// A, B and C.php

public function users(): MorphToMany
{
    return $this->morphToMany(User::class, 'shareable');
}

Of course I created a pivot table to store the relations.

I am now trying to find a way to find ALL relations linked to a given user based on the pivot table. Let's say this is currently my data:

user_id
view_mode
shareable_type
shareable_id

1
RW
App\Models\A
1

1
R
App\Models\A
2

1
W
App\Models\B
5

2
R
App\Models\A
2

1
W
App\Models\C
8

How can I retrieve all the related content for User with id 1?

My goal would be for it to look like this:

relations: [
    a: [
        - A entity with id 1
        - A entity with id 2
    ],
    b: [
        - B entity with id 5
    ],
    c: [
        - C entity with id 8
    ]
]

I tried by created a model named Shareable, and adding the following:

protected $table = 'shareables';

public function shareable()
{
    return $this->morphTo();
}

public function a()
{
    return $this->morphedByMany(A::class, 'shareable');
}

I then added the following to the User model:

public function shared()
{
    return $this->hasMany(Shareable::class)->with('a');
}

But when I call it by doing

$user->shared

I don't get my a instances, only an empty collection.

What am I doing wrong?


问:
How to reference method in xml comments when using multiple frameworks?
I have a project with target frameworks for net6 and net7, and i'm seeing the following warning pop up:

error CS1574: XML comment has cref attribute 'CreateParameter(DbCommand, string, object, bool?)' that could not be resolved

This seems to be because there are multiple versions of that function defined in the framework;

So the method presumably cannot be found when using net7.
How can i make it so the cref picks the right method?


问:
Redis error: being thrown by Docker container: The queue is full
I have a number of docker containers running on a vm, all of which are using the same Redis cache db, each has the same Redis config settings:

```<code> -e CACHE_ENABLED=true -e CACHE_KEY_IGNORED_PROPS=meta -e CACHE_TYPE=redis -e CACHE_REDIS_PORT=6379 -e CACHE_REDIS_HOST=xx.xx.xx.x -e CACHE_MAX_AGE=60000 -e RATE_LIMIT_ENABLED=false -e WS_ENABLED=true -e CACHE_REDIS_TIMEOUT=2000  --log-opt max-size=10m --log-opt max-file=3
</code>```

and I'm getting the following error in the Docker logs on just a couple of them, one after a while (days), another almost immediately after restarting:

```<code>"msg":"[Redis] Method getResponse errored: <...> \nError: The queue is full"}
</code>```

...and am having a bit of a hard time trying to trouble shoot.  Anyone have any advice???
Thanks so much!

Body:
I have a number of docker containers running on a vm, all of which are using the same Redis cache db, each has the same Redis config settings:

 -e CACHE_ENABLED=true -e CACHE_KEY_IGNORED_PROPS=meta -e CACHE_TYPE=redis -e CACHE_REDIS_PORT=6379 -e CACHE_REDIS_HOST=xx.xx.xx.x -e CACHE_MAX_AGE=60000 -e RATE_LIMIT_ENABLED=false -e WS_ENABLED=true -e CACHE_REDIS_TIMEOUT=2000  --log-opt max-size=10m --log-opt max-file=3

and I'm getting the following error in the Docker logs on just a couple of them, one after a while (days), another almost immediately after restarting:

"msg":"[Redis] Method getResponse errored: <...> \nError: The queue is full"}

...and am having a bit of a hard time trying to trouble shoot.  Anyone have any advice???
Thanks so much!


问:
Javascript - make a feature that lowers or raises the pitch of the song that's playing
Has anyone ever made an app for music?  I need to make a feature that lowers or raises the pitch of the song that's playing... I need to be able to play my audio sample .wav, .mp3, .mp4

Which library to use to do this in javascript?  I still haven't decided which language to use.  How do I capture an audio or video with audio and manage to increase or decrease the sound pitch?  I want to do a KARAOKE show.  In this program I will need to increase and decrease the pitch of the music.  I'll do it with javascript


问:
How to replace a js file of a web page without opening dev tools?
I would like to make it so that when I enter a page it changes its js for me (actually I would like it to change only one function).

I was hoping to find a Chrome extension that can do this.

I would also like to do this from Android (Kiwi Browser, which supports dev tools and all Chrome extensions).

Any advice?

I tried Resource Ovverride but it doesn't work.
I was expecting it to change the website JS but it doesn't. Maybe I wasn't using that in the proper way, I don't know.


问:
Selenium Google Account Login via Chromedriver Blocked
I'm using Selenium with python. I want to login to my account but Google says that automation drivers are not allowed to log in. Is there anyway to use Chrome directly instead of chromedriver? I am not sure if it is possible or not...

Screeshot of error message


问:
How to schedule query in GCP BQ to update file (sheet) in a bucket?
I have a dataset in BQ with 4 tables.

I scheduled a query to run every week and collect new data for last 7 days and append it to the 4 tables mentioned above.

I am looking for the way of filling the updated data from these 4 tables into 4 CSV files and upload them to replace the old version weekly in a Google Storage Bucket.

Please help if you know how to automate this process to run after the successful execution of the scheduled query!

Update: using EXPORT command in SQL

My issue is now to get this to run every week as when I re-run this code below I get an error that the file can't be deleted!

I tried now with the EXPORT command and it worked, (I used "SELECT DISTINCT" and "LIMIT" to avoid getting multible files issue, my query is as follows:

```<code>    # Create new date variables to query last 7 days each time!
    DECLARE DateFrom STRING DEFAULT FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 7 DAY));
    DECLARE DateTo STRING DEFAULT FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY));

    EXPORT DATA OPTIONS(
    uri='gs://bucket_x_product_information/Weekly/test_*.csv',
    format='CSV',
    overwrite=true,
    header=false,
    field_delimiter=',') AS

    SELECT DISTINCT * FROM `ga-data-xyz.Data.OnlineOrders` WHERE FORMAT_DATE('%Y%m%d', date) BETWEEN DateFrom AND DateTo LIMIT 999999
</code>```

Best,
Naz

Body:
I have a dataset in BQ with 4 tables.

I scheduled a query to run every week and collect new data for last 7 days and append it to the 4 tables mentioned above.

I am looking for the way of filling the updated data from these 4 tables into 4 CSV files and upload them to replace the old version weekly in a Google Storage Bucket.

Please help if you know how to automate this process to run after the successful execution of the scheduled query!

Update: using EXPORT command in SQL

My issue is now to get this to run every week as when I re-run this code below I get an error that the file can't be deleted!

I tried now with the EXPORT command and it worked, (I used "SELECT DISTINCT" and "LIMIT" to avoid getting multible files issue, my query is as follows:

    # Create new date variables to query last 7 days each time!
    DECLARE DateFrom STRING DEFAULT FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 7 DAY));
    DECLARE DateTo STRING DEFAULT FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY));

    EXPORT DATA OPTIONS(
    uri='gs://bucket_x_product_information/Weekly/test_*.csv',
    format='CSV',
    overwrite=true,
    header=false,
    field_delimiter=',') AS

    SELECT DISTINCT * FROM `ga-data-xyz.Data.OnlineOrders` WHERE FORMAT_DATE('%Y%m%d', date) BETWEEN DateFrom AND DateTo LIMIT 999999

Best,
Naz


问:
Cannot create a custom catalog rule condition in magento 2
Is there a way to make a custom catalog rule condition in magento 2 because adobe's documentation is not helpful at all. I created an after plugin and successfully added the condition but when I save the rule magento throws an error that the rule cannot be saved because I have an invalid method named collectValidatedAttributes  in my class that extends the AbstractCondition class.</p>


问:
How do I make a Google Wallet pass generator?
I want to make a HTML site where the users have to imput their names and a number of a physical loyalty card. The website should generate a Google Wallet Pass with specified logo and layout (and some other details which are the same on every card) and then let the user download it. How do is start? Thank you for your help!

How do is start? Thank you for your help!


问:
Cloudwatch event rule to match branch pattern name
I'm trying to trigger a CodePipeline Build when someone makes a commit to an AWS Codecommit branch. This works if I target the master branch with a pattern like this:

{
  "detail": {
    "referenceName": ["master"],
    "referenceType": ["branch"]
  },
  "detail-type": ["CodeCommit Repository State Change"],
  "resources": ["arn:aws:codecommit:region:1234:repo-name"],
  "source": ["aws.codecommit"]
}
```
<p>But it does not work when I try to match any branch that starts with the "release" string, as per documentation from here:</p>
<pre class="lang-json prettyprint-override"><code>{
  "detail": {
    "referenceName": [{
      "prefix": "release/"
    }],
    "referenceType": ["branch"]
  },
  "detail-type": ["CodeCommit Repository State Change"],
  "resources": ["arn:aws:codecommit:region:1234:repo-name"],
  "source": ["aws.codecommit"]
}
</code>```

Is there another way I can match a branch with a pattern name?

Body:
I'm trying to trigger a CodePipeline Build when someone makes a commit to an AWS Codecommit branch. This works if I target the master branch with a pattern like this:

{
  "detail": {
    "referenceName": ["master"],
    "referenceType": ["branch"]
  },
  "detail-type": ["CodeCommit Repository State Change"],
  "resources": ["arn:aws:codecommit:region:1234:repo-name"],
  "source": ["aws.codecommit"]
}

But it does not work when I try to match any branch that starts with the "release" string, as per documentation from here:

{
  "detail": {
    "referenceName": [{
      "prefix": "release/"
    }],
    "referenceType": ["branch"]
  },
  "detail-type": ["CodeCommit Repository State Change"],
  "resources": ["arn:aws:codecommit:region:1234:repo-name"],
  "source": ["aws.codecommit"]
}

Is there another way I can match a branch with a pattern name?


问:
How to publish Msbuild package to 2 octopus deploy servers
We are using two Octopus Deploy Instances at the moment. One is on-prem and newer is octopus cloud. We intend to keep running both OD Servers. Our github actions runs msbuild command and publishes the packages to on-prem OD instance. I want to publish the same package to Octopus Deploy Cloud instance as well. Is there a way to do this?
I tried running MSBuild command twice with changing octopus deploy urls and apikey but it doesnt work always. Works once and fails couple of times.

Here is the command that generates packages and publishes it to OD on-prem.

MSBuild ./Web.slnf /m:8 /v:quiet
/p:configuration=release /p:RestorePackages=false
/p:CreateHardLinksForCopyFilesToOutputDirectoryIfPossible=true /p:CreateHardLinksForCopyAdditionalFilesIfPossible=true
/p:CreateHardLinksForCopyLocalIfPossible=true /p:CreateHardLinksForPublishFilesIfPossible=true
/p:RunOctoPack=true /p:OctoPackPackageVersion=$version
/p:OctoPackPublishApiKey=${{ secrets.octopus_apikey }} /p:OctoPackPublishPackageToHttp=https://odserverurl/nuget/packages?replace=true
/warnAsError


问:
Delta Tables do not retain column names?
I have started with a DataFrame. Strangely I need to extract the paths for the files to convert it to a DeltaTable. Even more strangely, the column names are lost on the DeltaTable.  What is the thinking behind this?  Do we need to always pair up the DeltaTable with its DataFrame and track it ourselves? If so why then is there a toDF() method on the DeltaTable: it loses the columns info!

    def convert_df_to_delta_by_path(cls, df: DataFrame,
           out_path: str = None) -> [DeltaTable, str]:
        spark = df.sparkSession

        # we need to perform gymnastics to extract filename
        #  and construct the parquet 'identifier'..
        df_files_path_raw = df.withColumn("filename",input_file_name())
              .select('filename')
        df_files_path = df_files_path_raw.first()['filename']
        df_files_path = df_files_path[0:df_files_path.rfind('/')]
        output_id = f"parquet.`{out_path}`"
        delta_table = DeltaTable.convertToDelta(spark, output_id)
        print(delta_table.toDF())
```
<p>We lost the columns info during the conversion from <code>DataFrame</code> to <code>DeltaTable</code> so the output is:</p>
```DataFrame[_c0: string, _c1: string, _c2: string, _c3: string,
_c4: string, _c5: string, _c6: string, _c7: string, _c8: string,
_c9: string, _c10: string, _c11: string, _c12: string, _c13: string]
```

What is then the expected/recommended pattern for managing the DataFrame/DeltaTable interactions - including a more direct route to conversion between them (not involving extracting the file paths) and also retaining column names and other metadata?

Body:
I have started with a DataFrame. Strangely I need to extract the paths for the files to convert it to a DeltaTable. Even more strangely, the column names are lost on the DeltaTable.  What is the thinking behind this?  Do we need to always pair up the DeltaTable with its DataFrame and track it ourselves? If so why then is there a toDF() method on the DeltaTable: it loses the columns info!

    def convert_df_to_delta_by_path(cls, df: DataFrame,
           out_path: str = None) -> [DeltaTable, str]:
        spark = df.sparkSession

        # we need to perform gymnastics to extract filename
        #  and construct the parquet 'identifier'..
        df_files_path_raw = df.withColumn("filename",input_file_name())
              .select('filename')
        df_files_path = df_files_path_raw.first()['filename']
        df_files_path = df_files_path[0:df_files_path.rfind('/')]
        output_id = f"parquet.`{out_path}`"
        delta_table = DeltaTable.convertToDelta(spark, output_id)
        print(delta_table.toDF())

We lost the columns info during the conversion from DataFrame to DeltaTable so the output is:

DataFrame[_c0: string, _c1: string, _c2: string, _c3: string,
_c4: string, _c5: string, _c6: string, _c7: string, _c8: string,
_c9: string, _c10: string, _c11: string, _c12: string, _c13: string]

What is then the expected/recommended pattern for managing the DataFrame/DeltaTable interactions - including a more direct route to conversion between them (not involving extracting the file paths) and also retaining column names and other metadata?


问:
How various Link Time Optimization settings in VC++ work with each other?
I recently faced error MSB6006: "link.exe" exited with code -1073741819 building a VC2017 project with VC2022 and after no luck with Google I tried to resolve it myself. It seems the problem is related to "contradicting" or "missing" compiler and linker optimization options, which rises my question.

There are the following 3 options in C++ Property Pages that can give this error when you provide contradicting or missing values:

Configuration Properties

Advanced: Whole Program Optimization (several options)

No Whole Porgram Optimization

Use Link Time Code Generation

Profile Guided Optimization - Instrument / Optimize / Update

inherit from parent or project defaults

C/C++

Optimization: Whole Program Optimization (No or /GL)

Linker

Link Time Code Generation: (several options)

Default

Use Fast Link Time Code Generation (/LTCG:incremental)

Use Link Time Code Generation (/LTCG)

Profile Guided Optimization - Instrument / Optimize / Update

inherit from parent or project defaults

In my case I had linker option /INCREMENTAL, I was missing linker option /LTCG:incremental (it was empty), but had Advanced: Whole Program Optimization set to Use Link Time Code Generation. In MSVC2017 it was sufficient but in VC2022 it caused error MSB6006: "link.exe" exited with code -1073741819.

So, how various Link Time Optimization settings in VC++ work with each other? What is their relationship and defaulting logic?


问:
How do i use requests.post http to change a variable
Im trying to implement a bully-election algorithm between pods in kubernetes.
Currently im using requests.get() to get the ID number of a pod.
Every pod has a variable leader_id which is the ID number of the current leader pod.
However i need to change this variable leader_id, and thought i could use
requests.post(pod_url, message = new_leader_id ) i just do not understand how to.
`

Currently i have this code and thought i could implement it in this way
The send_out_coordinator function is run by the new coordinator and therefore it needs to send out its ID to all other pods and they need to update it.

```<code>from aiohttp import web
import requests

async def send_out_coordinator(ip_list):
    for ip in ip_list:
        url = 'http://' + str(ip) + ':' + str(WEB_PORT) + "/update_coordinator"
        requests.post(str(url), data=POD_ID)
#POST
async def update_coordinator(request):
    #coordinator_id
    coordinator_id=request.message # the message is the coordinator_id

if __name__ == "__main__":
    app = web.Application()

    app.router.add_post('/update_coordinator', update_coordinator)
    app.router.add_get('/pod_id', pod_id)

    web.run_app(app, host='0.0.0.0', port=WEB_PORT)

</code>```

Body:
Im trying to implement a bully-election algorithm between pods in kubernetes.
Currently im using requests.get() to get the ID number of a pod.
Every pod has a variable leader_id which is the ID number of the current leader pod.
However i need to change this variable leader_id, and thought i could use
requests.post(pod_url, message = new_leader_id ) i just do not understand how to.
`

Currently i have this code and thought i could implement it in this way
The send_out_coordinator function is run by the new coordinator and therefore it needs to send out its ID to all other pods and they need to update it.

from aiohttp import web
import requests

async def send_out_coordinator(ip_list):
    for ip in ip_list:
        url = 'http://' + str(ip) + ':' + str(WEB_PORT) + "/update_coordinator"
        requests.post(str(url), data=POD_ID)
#POST
async def update_coordinator(request):
    #coordinator_id
    coordinator_id=request.message # the message is the coordinator_id

if __name__ == "__main__":
    app = web.Application()

    app.router.add_post('/update_coordinator', update_coordinator)
    app.router.add_get('/pod_id', pod_id)

    web.run_app(app, host='0.0.0.0', port=WEB_PORT)


问:
Should I throw "UsernameNotFoundException" in `loadUserByUsername()` for case check? If yes, how do I handle it?
I'm trying to return 401 for mismatched username & password. Here is the code for checking username case

```<code>public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    HUser hUser = uRepo.findByUsername(username);

    if (!hUser.getUsername().equals(username)) {
        throw new UsernameNotFoundException("User not found");
    }
    return new User(hUser.getUsername(), hUser.getPassword(), aRepo.findByUsername(username));
}
</code>```

Should I throw "UsernameNotFoundException" there? If yes, how do I handle the exception?

I tried the following code

```<code>@RestControllerAdvice
public class ExceptionController {

    @ExceptionHandler(UsernameNotFoundException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ResponseEntity<?> ret401(final UsernameNotFoundException exception){
        System.out.println("HttpStatus.FORBIDDEN");
        return (ResponseEntity<?>) ResponseEntity
                .status(HttpStatus.FORBIDDEN);
    }
}
</code>```

and got nothing. The code block is never invoked.

what am I missing?

Body:
I'm trying to return 401 for mismatched username & password. Here is the code for checking username case

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    HUser hUser = uRepo.findByUsername(username);

    if (!hUser.getUsername().equals(username)) {
        throw new UsernameNotFoundException("User not found");
    }
    return new User(hUser.getUsername(), hUser.getPassword(), aRepo.findByUsername(username));
}

Should I throw "UsernameNotFoundException" there? If yes, how do I handle the exception?

I tried the following code

@RestControllerAdvice
public class ExceptionController {

    @ExceptionHandler(UsernameNotFoundException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ResponseEntity<?> ret401(final UsernameNotFoundException exception){
        System.out.println("HttpStatus.FORBIDDEN");
        return (ResponseEntity<?>) ResponseEntity
                .status(HttpStatus.FORBIDDEN);
    }
}

and got nothing. The code block is never invoked.

what am I missing?


问:
Recharts Yaxis change interval between values
Would anyone now if there is a way, using Recharts, to produce an YAxis that looks like the image bellow.

Essentially I would like to change the interval between ticks at somepoint in the Yaxes. I would also like to reflect the change in interval with a design change as well, as shown in the attachment by the two slanted lines. The actual way this change is represented is not important, it should just be obvious.

I have been reading lots and lots of examples for Recharts from many sources and I can not see any way to achive this. Any guidance in this would be amazing. Thanks


问:
How to iterate through the nested list and delete an element from it after satisfying certain condition
I have two nested lists and 1 list as below:

```<code>list1 = [0, 4, 27, 30, 64, 88, 91, 98]
list2 = [[40, 43, 61], [39, 40, 43, 61], [85], [82, 52], [72, 57, 10], [11], [97, 13, 82, 73, 90, 45], [48, 97, 35]]
list3 = [[40, 43, 61], [40, 43, 61], [], [82], [], [], [97, 82], [97]]
</code>```

list1 and list2 are zipped. i.e. [40,43,61] are elements of 0 and so on. list3 has some common elements present in list2. I want to remove only those common elements from list2 which have less distance from list1. I m having the distance matrix.

Here [40, 43, 61] are elements of 0 and [39, 40, 43, 61] are elements of 4. And in list3 I have only the common elements. I have all the distances. If the distance between 0 to 40,43,61 are greater than distance between 4 to 40,43,62 I need to remove only those elements from list2[0]  and if it is less then I need to remove from list2[1].

```<code>list1 = [0, 4, 27, 30, 64, 88, 91, 98]
list2 = [[40, 43, 61], [39, 40, 43, 61], [85], [82, 52], [72, 57, 10], [11], [97, 13, 82, 73, 90, 45], [48, 97, 35]]
list3 = [[40, 43, 61], [40, 43, 61], [], [82], [], [], [97, 82], [97]]
n = len(list3)
i = 0
while i < n:
    j = 0
    while j < len(list3[i]):
        if (list3[i][j] in list3[i][:]):
            print(list3[i])
        j +=1
    i +=1
</code>```

Body:
I have two nested lists and 1 list as below:

list1 = [0, 4, 27, 30, 64, 88, 91, 98]
list2 = [[40, 43, 61], [39, 40, 43, 61], [85], [82, 52], [72, 57, 10], [11], [97, 13, 82, 73, 90, 45], [48, 97, 35]]
list3 = [[40, 43, 61], [40, 43, 61], [], [82], [], [], [97, 82], [97]]

list1 and list2 are zipped. i.e. [40,43,61] are elements of 0 and so on. list3 has some common elements present in list2. I want to remove only those common elements from list2 which have less distance from list1. I m having the distance matrix.

Here [40, 43, 61] are elements of 0 and [39, 40, 43, 61] are elements of 4. And in list3 I have only the common elements. I have all the distances. If the distance between 0 to 40,43,61 are greater than distance between 4 to 40,43,62 I need to remove only those elements from list2[0]  and if it is less then I need to remove from list2[1].

list1 = [0, 4, 27, 30, 64, 88, 91, 98]
list2 = [[40, 43, 61], [39, 40, 43, 61], [85], [82, 52], [72, 57, 10], [11], [97, 13, 82, 73, 90, 45], [48, 97, 35]]
list3 = [[40, 43, 61], [40, 43, 61], [], [82], [], [], [97, 82], [97]]
n = len(list3)
i = 0
while i < n:
    j = 0
    while j < len(list3[i]):
        if (list3[i][j] in list3[i][:]):
            print(list3[i])
        j +=1
    i +=1


问:
Getting ValueError: At least one stride in the given numpy array is negative, and tensors with negative strides are not currently supported
I am trying to train inception net on a custom dataset of fruits which are of two classes 0 and 1. This is mentioned in csv file. Contents of the file can be seen below:

```<code>fruit0626.JPG   0
fruit0006.JPG   0
fruit0007.JPG   0
fruit0008.JPG   0
fruit0009.JPG   0
fruit0010.JPG   0
fruit0001.JPG   0
fruit0002.JPG   0
fruit0003.JPG   0
fruit0004.JPG   0
fruit0005.JPG   0
fruit0186.JPG   0
fruit0187.JPG   0
fruit0188.JPG   0
fruit0189.JPG   0
fruit0190.JPG   0
fruit0141.JPG   0
fruit0142.JPG   0
fruit0143.JPG   0
fruit0144.JPG   0
fruit0145.JPG   0
fruit0146.JPG   0
fruit0147.JPG   0
fruit0148.JPG   0
fruit0149.JPG   0
fruit0150.JPG   0
fruit0031.JPG   0
fruit0032.JPG   0
fruit0033.JPG   0
fruit0034.JPG   0
fruit0035.JPG   0
fruit0156.JPG   0
fruit0157.JPG   0
fruit0158.JPG   0
fruit0159.JPG   0
fruit0160.JPG   0
</code>```

each row has the image name and which class it belongs to (0 or 1).

Below is the code that i have used:

```<code>from google.colab import drive
drive.mount('/content/drive')
import os
import pandas as pd
import torch
from torch.utils.data import Dataset
from skimage import io
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import torchvision
from torch.utils.data import DataLoader

class kinoo(Dataset):
  def __init__(self, csv_file, root_dir, transform=None):
    self.annotations = pd.read_csv(csv_file)
    self.root_dir = root_dir
    self.transform = transform
  def __len__(self):
    return(len(self.annotations))

  def __getitem__(self, index):
    image_path = os.path.join(self.root_dir, self.annotations.iloc[index,0])
    image = io.imread(image_path)
    y_label = torch.tensor(int(self.annotations.iloc[index,1]))

    if self.transform:
      image = self.transform(image)

    return (image, y_label)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

#hyperparameters
in_channel = 3
learning_rate = 1e-3
batch_size = 32
num_epochs = 50

#transforms
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
    transforms.Resize((640,640))
])

#load data
dataset = kinoo(csv_file = '/content/drive/MyDrive/aza-exp/aza-fruit-regression-v2/fruit_classification.csv', root_dir = '/content/drive/MyDrive/aza-exp/aza-fruit-regression-v2', transform = transform)

train_set, test_set = torch.utils.data.random_split(dataset, [0.8, 0.2])
train_loader = DataLoader(dataset = train_set, batch_size = batch_size, shuffle = True)
test_loader = DataLoader(dataset = test_set, batch_size = batch_size, shuffle = True)

print(list(train_set))
</code>```

This gave me the following error:

I found two similar questions with same error:
link 1
link 2

But these solutions didn't worked for me.
I've searched the internet and couldn't troubleshoot it on my own. Any help regarding why this error is generated and how i can solve it, would be greatly appreciated.

Body:
I am trying to train inception net on a custom dataset of fruits which are of two classes 0 and 1. This is mentioned in csv file. Contents of the file can be seen below:

fruit0626.JPG   0
fruit0006.JPG   0
fruit0007.JPG   0
fruit0008.JPG   0
fruit0009.JPG   0
fruit0010.JPG   0
fruit0001.JPG   0
fruit0002.JPG   0
fruit0003.JPG   0
fruit0004.JPG   0
fruit0005.JPG   0
fruit0186.JPG   0
fruit0187.JPG   0
fruit0188.JPG   0
fruit0189.JPG   0
fruit0190.JPG   0
fruit0141.JPG   0
fruit0142.JPG   0
fruit0143.JPG   0
fruit0144.JPG   0
fruit0145.JPG   0
fruit0146.JPG   0
fruit0147.JPG   0
fruit0148.JPG   0
fruit0149.JPG   0
fruit0150.JPG   0
fruit0031.JPG   0
fruit0032.JPG   0
fruit0033.JPG   0
fruit0034.JPG   0
fruit0035.JPG   0
fruit0156.JPG   0
fruit0157.JPG   0
fruit0158.JPG   0
fruit0159.JPG   0
fruit0160.JPG   0

each row has the image name and which class it belongs to (0 or 1).

Below is the code that i have used:

from google.colab import drive
drive.mount('/content/drive')
import os
import pandas as pd
import torch
from torch.utils.data import Dataset
from skimage import io
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import torchvision
from torch.utils.data import DataLoader

class kinoo(Dataset):
  def __init__(self, csv_file, root_dir, transform=None):
    self.annotations = pd.read_csv(csv_file)
    self.root_dir = root_dir
    self.transform = transform
  def __len__(self):
    return(len(self.annotations))

  def __getitem__(self, index):
    image_path = os.path.join(self.root_dir, self.annotations.iloc[index,0])
    image = io.imread(image_path)
    y_label = torch.tensor(int(self.annotations.iloc[index,1]))

    if self.transform:
      image = self.transform(image)

    return (image, y_label)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

#hyperparameters
in_channel = 3
learning_rate = 1e-3
batch_size = 32
num_epochs = 50

#transforms
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
    transforms.Resize((640,640))
])

#load data
dataset = kinoo(csv_file = '/content/drive/MyDrive/aza-exp/aza-fruit-regression-v2/fruit_classification.csv', root_dir = '/content/drive/MyDrive/aza-exp/aza-fruit-regression-v2', transform = transform)

train_set, test_set = torch.utils.data.random_split(dataset, [0.8, 0.2])
train_loader = DataLoader(dataset = train_set, batch_size = batch_size, shuffle = True)
test_loader = DataLoader(dataset = test_set, batch_size = batch_size, shuffle = True)

print(list(train_set))

This gave me the following error:

I found two similar questions with same error:
link 1
link 2

But these solutions didn't worked for me.
I've searched the internet and couldn't troubleshoot it on my own. Any help regarding why this error is generated and how i can solve it, would be greatly appreciated.