问:
vue-router hashMode not rendring component of some paths
I am using vue3 and vue-router.

routes

```<code>import { createRouter, createWebHashHistory } from 'vue-router'
import InitialView from '../views/InitialView.vue'
import store from '@/store/index.js'

import { defineAsyncComponent } from 'vue'
import SkeletonCard from '../skeletons/SkeletonCard.vue'
import NotFound from '@/components/NotFound.vue'

// const UsersList = defineAsyncComponent({
//   loader: () => import("@/components/UserList.vue"),
//   loadingComponent: SkeletonCard,
//   delay: 0
// })
const RolesList = defineAsyncComponent({
  loader: () => import('../components/RoleList.vue'),
  loadingComponent: SkeletonCard,
  delay: 0
})
const ClientsList = defineAsyncComponent({
  loader: () => import('../components/ClientsList.vue'),
  loadingComponent: SkeletonCard,
  delay: 0
})
const TasksList = defineAsyncComponent({
  loader: () => import('../components/TasksList.vue'),
  loadingComponent: SkeletonCard,
  delay: 0
})
// const MyTasksList = defineAsyncComponent({
  // loader: () =>
//   loadingComponent: SkeletonCard,
//   delay: 0
// })
const ActivityList = defineAsyncComponent({
  loader: () => import('../components/UserActivity.vue'),
  loadingComponent: SkeletonCard,
  delay: 0
})

const routes = [
  {
    path: '/',
    alias: '/#',
    name: 'main',
    component: InitialView,
    children: [{
      path: '/',
      alias: 'login',
      name: 'login',
      component: () => import('../components/LogIn.vue')
    }]
  },
  {
    path: '/u',
    name: 'u',
    component: () => import('../views/MainView.vue'),
    children: [
      {
        path: '/no-access',
        name: 'no_access',
        component: () => import('../components/NoAccess.vue')
      },{
      path: '/users',
      alias: 'users',
      name: 'users',
      component: () => import('../views/UsersView.vue'),
      children: [{
          path: 'create-user',
          name: 'create_user',
          component: () => import('../components/UserCreate.vue'),
          meta: {
            protected: true,
            breadcrumb: {
              title: 'create user',
              path: [{
                text: 'list',
                route: '/u/users/list'
              }, {
                text: 'create',
                route: '/u/users/create-user'
              }]
            }
          },
        }, {
          path: '',
          alias: 'list',
          name: 'users_list',
          component: () => import("@/components/UserList.vue"),
          meta: {
            breadcrumb: {
              title: 'users',
              action: true,
              actionUrl: '/u/users/create-user',
              path: [{
                text: 'list',
                route: '/u/users/list'
              }]
            }
          }
        },
        {
          path: 'edit/:editUserId',
          name: 'edit_user',
          meta: {protected: true},
          component: () => import('../components/UserCreate.vue'),
          props: true,
        }
      ]
    }, {
      path: 'roles',
      name: 'roles',
      component: () => import('../views/RoleView.vue'),
      children: [{
        path: 'create-role',
        name: 'create_role',
        component: () => import('../components/RoleCreate.vue'),
        meta: {
          breadcrumb: {
            title: 'roles',
            path: [{
              text: 'list',
              route: '/u/roles/list'
            }, {
              text: 'create',
              route: '/u/roles/create-role'
            }]
          },
          protected: true
        },
      }, {
        path: 'list',
        alias: '',
        name: 'roles_list',
        component: RolesList,
        meta: {
          breadcrumb: {
            title: 'roles',
            action: true,
            actionUrl: '/u/roles/create-role',
            path: [{
              text: 'list',
              route: '/u/roles/list'
            }]
          }
        }
      }, {
        path: 'edit/:editRoleId',
        name: 'edit_role',
        meta: {
          breadcrumb: [{
            title: 'edit role',
            path: [{
              text: 'list',
              route: '/u/roles/list'
            }, {
              text: 'edit',
              route: '/u/roles/edit/:editRoleId',
            }]
          }],
          protected: true
        },
        component: () => import('../components/RoleCreate.vue'),
        props: true
      }]
    },{
      path: 'clients',
      name: 'clients_list',
      component: () => import('../views/ClientView.vue'),
      children: [{
        path: 'list',
        alias: '',
        name: 'clients_list',
        component: ClientsList,
        meta: {
          breadcrumb: {
            title: 'clients',
            action: true,
            actionUrl: '/u/clients/create-client',
            path: [{
              text: 'list',
              route: '/u/clients/list'
            }]
          }
        }
      }, {
        path: 'create-client',
        name: 'create_client',
        component: () => import('../components/ClientCreate.vue'),
        meta: {
          breadcrumb: {
            title: 'create client',
            path: [{
              text: 'list',
              route: '/u/clients/list'
            }, {
              text: 'create',
              route: '/u/clients/create-client'
            }]
          },
          protected: true,
        }}
    ]}, {
      path: '/tasks',
      name: 'tasks',
      component: () => import('../views/TasksView.vue'),
      children: [{
        path: '',
        alias: 'list',
        name: 'tasks_list',
        component: TasksList,
        meta: {
          breadcrumb: {
            title: 'tasks',
            action: true,
            actionUrl: '/u/tasks/create-task',
            path: [{
              text: 'list',
              route: '/u/tasks/list'
            }]
          }
        }
      }, {
        path: 'create-task',
        name: 'create_task',
        component: () => import('../components/TasksCreate.vue'),
        meta: {
          breadcrumb: {
            title: 'create task',
            path: [{
              text: 'list',
              route: '/u/tasks/list'
            }, {
              text: 'create',
              route: '/u/tasks/create-task'
            }]
          },
          protected: true
        }
      }]
    }, {
      path: '/my-tasks',
      name: 'my_tasks',
      component: () => import('../views/MyTasksView.vue'),
      children: [{
        path: '',
        name: 'my_tasks_list',
        component: () => import('../components/MyTasksList.vue'),
        meta: {
          breadcrumb: {
            title: 'my tasks',
            path: [{
              text: 'list',
              route: '/u/my-tasks/list'
            }]
          }
        }
      }]
    }, {
      path: 'activity',
      name: 'activity',
      component: ActivityList,
      meta: {
        breadcrumb: {
          title: 'activity',
          path: [{
            text: 'list',
            route: '/u/activity/'
          }]
        },
        protected: true
      },
    }]
  },
  {
    path: '/:pathMatch(.*)',
    name: 'not-found',
    component: NotFound
  }
]

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from)=>{
  if (to?.meta?.protected) {
    console.log(to, from)
    const userRights = store.getters['rights/getUserRights']
    const allow = userRights?.some((right) => right?.code_name == to?.name)
    if (!allow) return { name: 'no_access'}
  }
})

export default router
</code>```

http://localhost:8080/#/ is login page if valid login in performed user gets redirected to my_tasks_list route
In login page

```<code>            axios.post('api/login', {
                email: this.email,
                password: this.pwd
            }, {
                withCredentials: true,
            })
            .then((results) => {
                if (results?.data?.login == 1) {
                    this.$router.push({name: 'my_tasks_list'})
                }
                else {
                    this.$router.push({name: 'login'})
                }
            })
            .catch(err =>
                swal({
                    text: `Ooops ${err}`
                })
            )
</code>```

Everything works fine If I access http://localhost:8080 it immediately redirect me to http://localhost:8080/#/ and if I pass valid login credentials then to my_tasks_list component
if I try to access http://localhost:8080/#/ then I get redirected to login page and if I pass valid login credentials then to my_tasks_list everything seems to work but my_tasks_list isn't rendering actual component.

any help is appreciated

Body:
I am using vue3 and vue-router.

routes

import { createRouter, createWebHashHistory } from 'vue-router'
import InitialView from '../views/InitialView.vue'
import store from '@/store/index.js'

import { defineAsyncComponent } from 'vue'
import SkeletonCard from '../skeletons/SkeletonCard.vue'
import NotFound from '@/components/NotFound.vue'

// const UsersList = defineAsyncComponent({
//   loader: () => import("@/components/UserList.vue"),
//   loadingComponent: SkeletonCard,
//   delay: 0
// })
const RolesList = defineAsyncComponent({
  loader: () => import('../components/RoleList.vue'),
  loadingComponent: SkeletonCard,
  delay: 0
})
const ClientsList = defineAsyncComponent({
  loader: () => import('../components/ClientsList.vue'),
  loadingComponent: SkeletonCard,
  delay: 0
})
const TasksList = defineAsyncComponent({
  loader: () => import('../components/TasksList.vue'),
  loadingComponent: SkeletonCard,
  delay: 0
})
// const MyTasksList = defineAsyncComponent({
  // loader: () =>
//   loadingComponent: SkeletonCard,
//   delay: 0
// })
const ActivityList = defineAsyncComponent({
  loader: () => import('../components/UserActivity.vue'),
  loadingComponent: SkeletonCard,
  delay: 0
})

const routes = [
  {
    path: '/',
    alias: '/#',
    name: 'main',
    component: InitialView,
    children: [{
      path: '/',
      alias: 'login',
      name: 'login',
      component: () => import('../components/LogIn.vue')
    }]
  },
  {
    path: '/u',
    name: 'u',
    component: () => import('../views/MainView.vue'),
    children: [
      {
        path: '/no-access',
        name: 'no_access',
        component: () => import('../components/NoAccess.vue')
      },{
      path: '/users',
      alias: 'users',
      name: 'users',
      component: () => import('../views/UsersView.vue'),
      children: [{
          path: 'create-user',
          name: 'create_user',
          component: () => import('../components/UserCreate.vue'),
          meta: {
            protected: true,
            breadcrumb: {
              title: 'create user',
              path: [{
                text: 'list',
                route: '/u/users/list'
              }, {
                text: 'create',
                route: '/u/users/create-user'
              }]
            }
          },
        }, {
          path: '',
          alias: 'list',
          name: 'users_list',
          component: () => import("@/components/UserList.vue"),
          meta: {
            breadcrumb: {
              title: 'users',
              action: true,
              actionUrl: '/u/users/create-user',
              path: [{
                text: 'list',
                route: '/u/users/list'
              }]
            }
          }
        },
        {
          path: 'edit/:editUserId',
          name: 'edit_user',
          meta: {protected: true},
          component: () => import('../components/UserCreate.vue'),
          props: true,
        }
      ]
    }, {
      path: 'roles',
      name: 'roles',
      component: () => import('../views/RoleView.vue'),
      children: [{
        path: 'create-role',
        name: 'create_role',
        component: () => import('../components/RoleCreate.vue'),
        meta: {
          breadcrumb: {
            title: 'roles',
            path: [{
              text: 'list',
              route: '/u/roles/list'
            }, {
              text: 'create',
              route: '/u/roles/create-role'
            }]
          },
          protected: true
        },
      }, {
        path: 'list',
        alias: '',
        name: 'roles_list',
        component: RolesList,
        meta: {
          breadcrumb: {
            title: 'roles',
            action: true,
            actionUrl: '/u/roles/create-role',
            path: [{
              text: 'list',
              route: '/u/roles/list'
            }]
          }
        }
      }, {
        path: 'edit/:editRoleId',
        name: 'edit_role',
        meta: {
          breadcrumb: [{
            title: 'edit role',
            path: [{
              text: 'list',
              route: '/u/roles/list'
            }, {
              text: 'edit',
              route: '/u/roles/edit/:editRoleId',
            }]
          }],
          protected: true
        },
        component: () => import('../components/RoleCreate.vue'),
        props: true
      }]
    },{
      path: 'clients',
      name: 'clients_list',
      component: () => import('../views/ClientView.vue'),
      children: [{
        path: 'list',
        alias: '',
        name: 'clients_list',
        component: ClientsList,
        meta: {
          breadcrumb: {
            title: 'clients',
            action: true,
            actionUrl: '/u/clients/create-client',
            path: [{
              text: 'list',
              route: '/u/clients/list'
            }]
          }
        }
      }, {
        path: 'create-client',
        name: 'create_client',
        component: () => import('../components/ClientCreate.vue'),
        meta: {
          breadcrumb: {
            title: 'create client',
            path: [{
              text: 'list',
              route: '/u/clients/list'
            }, {
              text: 'create',
              route: '/u/clients/create-client'
            }]
          },
          protected: true,
        }}
    ]}, {
      path: '/tasks',
      name: 'tasks',
      component: () => import('../views/TasksView.vue'),
      children: [{
        path: '',
        alias: 'list',
        name: 'tasks_list',
        component: TasksList,
        meta: {
          breadcrumb: {
            title: 'tasks',
            action: true,
            actionUrl: '/u/tasks/create-task',
            path: [{
              text: 'list',
              route: '/u/tasks/list'
            }]
          }
        }
      }, {
        path: 'create-task',
        name: 'create_task',
        component: () => import('../components/TasksCreate.vue'),
        meta: {
          breadcrumb: {
            title: 'create task',
            path: [{
              text: 'list',
              route: '/u/tasks/list'
            }, {
              text: 'create',
              route: '/u/tasks/create-task'
            }]
          },
          protected: true
        }
      }]
    }, {
      path: '/my-tasks',
      name: 'my_tasks',
      component: () => import('../views/MyTasksView.vue'),
      children: [{
        path: '',
        name: 'my_tasks_list',
        component: () => import('../components/MyTasksList.vue'),
        meta: {
          breadcrumb: {
            title: 'my tasks',
            path: [{
              text: 'list',
              route: '/u/my-tasks/list'
            }]
          }
        }
      }]
    }, {
      path: 'activity',
      name: 'activity',
      component: ActivityList,
      meta: {
        breadcrumb: {
          title: 'activity',
          path: [{
            text: 'list',
            route: '/u/activity/'
          }]
        },
        protected: true
      },
    }]
  },
  {
    path: '/:pathMatch(.*)',
    name: 'not-found',
    component: NotFound
  }
]

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from)=>{
  if (to?.meta?.protected) {
    console.log(to, from)
    const userRights = store.getters['rights/getUserRights']
    const allow = userRights?.some((right) => right?.code_name == to?.name)
    if (!allow) return { name: 'no_access'}
  }
})

export default router

http://localhost:8080/#/ is login page if valid login in performed user gets redirected to my_tasks_list route
In login page

            axios.post('api/login', {
                email: this.email,
                password: this.pwd
            }, {
                withCredentials: true,
            })
            .then((results) => {
                if (results?.data?.login == 1) {
                    this.$router.push({name: 'my_tasks_list'})
                }
                else {
                    this.$router.push({name: 'login'})
                }
            })
            .catch(err =>
                swal({
                    text: `Ooops ${err}`
                })
            )

Everything works fine If I access http://localhost:8080 it immediately redirect me to http://localhost:8080/#/ and if I pass valid login credentials then to my_tasks_list component
if I try to access http://localhost:8080/#/ then I get redirected to login page and if I pass valid login credentials then to my_tasks_list everything seems to work but my_tasks_list isn't rendering actual component.

any help is appreciated


来源: stackexchange

问:
Electron send data to react with preload.js
I am trying achieve something where I can directly send data to react and where in react whenever it receives it does something.

So my electron.js is in below format.

```<code>    // ./public/electron.js
const path = require("path");
const { app, BrowserWindow, ipcMain} = require("electron");
const isDev = false; //require("electron-is-dev"); //false

let splash = null;
let win = null;
let etmf_obj = null;

function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 1920,
    height: 1080,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: true,
      enableRemoteModule: true,
      preload: path.join(__dirname, "./preloadDist.js"),
    },
  });
  // win.loadFile("index.html");
  win.loadURL(
    isDev
      ? "http://localhost:3000"
      : `file://${path.join(__dirname, "../build/index.html")}`
  );
  // Open the DevTools.
  if (!isDev) {
    win.webContents.openDevTools({ mode: "undocked" });
  }

}

app.whenReady().then(createWindow);

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

function restartApp() {
  console.log("restarting app..");
  app.exit();
  app.relaunch();
}

//IPC SECTION
ipcMain.handle("notify", (event, args) => {
  console.log("from react I got" + args);
  console.log("hello from electron via react"); //this one works as expected
});
ipcMain.on("splashDone", function () {
  console.log("splash done");
});

ipcMain.on("relaunchApp", function () {
  restartApp();
});

ipcMain.on("closeAll", function () {
  app.quit();
});

ipcMain.on("callAnim", function (args) {
  win.webContents.send("showAnimation", args);// trying to send data directly to
//react here but don't know whether its right way or not
});
</code>```

and my preload file preloadDist.js is in below format

```<code> const { ipcRenderer, contextBridge } = require("electron");

contextBridge.exposeInMainWorld("electron", {
  notificationApi: {
    sendNotification(message) {
      ipcRenderer.invoke("notify", message);
    },
  },
  batteryApi: {},
  filesApi: {},
  splashStatus: {
    splashDone() {
      ipcRenderer.invoke("splashDone")
    }
  },
});
</code>```

and react to call function of or to send data I am do this
for example to send notification data :

```<code><button
   className="speak_border"
   onMouseEnter={() => setHovermic(true)}
   onMouseLeave={() => setHovermic(false)}
   onClick={() => {
   soundwave();
   window.electron.notificationApi.sendNotification(
   "From react Hi!");
 }}
>
</code>```

and to receive data I am not able to figure out but as I am doing win.webContents.send("showListenAnimation", args);
I am not able to understand how this will be received at the react end

what I tried is:

```<code>useEffect(() => {
try {
  window.electron.on(
    "showAnimation",
    function (event, data) {
      if (data) {
        setAnim(true);
      }
      if (!data) {
        setAnim(false);
      }
    }
  );

} catch (e) {
  console.log("issue with on getting data");
}
</code>```

});

But this way I am getting error and not able to figure out the way to receive, but sending data from react to electron is working perfectly fine!
Please guide on this and how to achieve with about preload.js and electron.js
format.

ContentLicense: CC BY-SA 4.0

Body:
I am trying achieve something where I can directly send data to react and where in react whenever it receives it does something.

So my electron.js is in below format.

    // ./public/electron.js
const path = require("path");
const { app, BrowserWindow, ipcMain} = require("electron");
const isDev = false; //require("electron-is-dev"); //false

let splash = null;
let win = null;
let etmf_obj = null;

function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 1920,
    height: 1080,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: true,
      enableRemoteModule: true,
      preload: path.join(__dirname, "./preloadDist.js"),
    },
  });
  // win.loadFile("index.html");
  win.loadURL(
    isDev
      ? "http://localhost:3000"
      : `file://${path.join(__dirname, "../build/index.html")}`
  );
  // Open the DevTools.
  if (!isDev) {
    win.webContents.openDevTools({ mode: "undocked" });
  }

}

app.whenReady().then(createWindow);

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

function restartApp() {
  console.log("restarting app..");
  app.exit();
  app.relaunch();
}

//IPC SECTION
ipcMain.handle("notify", (event, args) => {
  console.log("from react I got" + args);
  console.log("hello from electron via react"); //this one works as expected
});
ipcMain.on("splashDone", function () {
  console.log("splash done");
});

ipcMain.on("relaunchApp", function () {
  restartApp();
});

ipcMain.on("closeAll", function () {
  app.quit();
});

ipcMain.on("callAnim", function (args) {
  win.webContents.send("showAnimation", args);// trying to send data directly to
//react here but don't know whether its right way or not
});

and my preload file preloadDist.js is in below format

 const { ipcRenderer, contextBridge } = require("electron");

contextBridge.exposeInMainWorld("electron", {
  notificationApi: {
    sendNotification(message) {
      ipcRenderer.invoke("notify", message);
    },
  },
  batteryApi: {},
  filesApi: {},
  splashStatus: {
    splashDone() {
      ipcRenderer.invoke("splashDone")
    }
  },
});

and react to call function of or to send data I am do this
for example to send notification data :

<button
   className="speak_border"
   onMouseEnter={() => setHovermic(true)}
   onMouseLeave={() => setHovermic(false)}
   onClick={() => {
   soundwave();
   window.electron.notificationApi.sendNotification(
   "From react Hi!");
 }}
>

and to receive data I am not able to figure out but as I am doing win.webContents.send("showListenAnimation", args);
I am not able to understand how this will be received at the react end

what I tried is:

useEffect(() => {
try {
  window.electron.on(
    "showAnimation",
    function (event, data) {
      if (data) {
        setAnim(true);
      }
      if (!data) {
        setAnim(false);
      }
    }
  );

} catch (e) {
  console.log("issue with on getting data");
}

});

But this way I am getting error and not able to figure out the way to receive, but sending data from react to electron is working perfectly fine!
Please guide on this and how to achieve with about preload.js and electron.js
format.


问:
Write a CSV based on another CSV file creating an additional empty row?
I have a system that creates csv files nightly and sends them off to a SMTP server.

Customer has requested that we make a separate text file with differently formatted timestamps, this time to ISO format, and send it to a separate SMTP server.  Due to some poor programming, constraints and prior technical debt it is much easier for me to let the system go on with it's normal process, but read the created CSV, modify the time stamp columns to the right format, and create the new csv like that and then send it off.

I almost have it working but for some reason my function is adding an additional empty row in between every row.

My function:

```<code>def convertFileToIsoFormat(read_filePath, write_filePath):
    import csv
    import datetime
    from __future__ import with_statement
    with open(read_filePath) as csvfile:
        reader = csv.reader(csvfile, delimiter='\t')
        for row in reader:
            modifiedRow = row
            columnsToModify = [4,7,11]
            for column in columnsToModify:
                modifiedRow[column] = datetime.datetime.strptime(modifiedRow[column], '%Y-%m-%d %H:%M:%S').isoformat()
            # Special column with different format
            modifiedRow[22] = datetime.datetime.strptime(modifiedRow[21], '%m/%d/%Y %H:%M:%S %p').isoformat()
            with open(write_filePath, 'a') as newcsv:
                writer = csv.writer(newcsv, delimiter='\t')
                writer.writewrow(modifiedRow)
</code>```

This works in making the file, and in Notepad on this Windows Server 2012 the file looks right, but in my newer Windows 10 notepad I see the extra rows, and in NotePad++ on either computer I see the extra rows, so I suspect it has something to do with what the linebreak character is supposed to be for the os but I don't know how to work with that here.

Using python (technically jython) 2.5 for this.  Any thoughts on what I am missing?

Body:
I have a system that creates csv files nightly and sends them off to a SMTP server.

Customer has requested that we make a separate text file with differently formatted timestamps, this time to ISO format, and send it to a separate SMTP server.  Due to some poor programming, constraints and prior technical debt it is much easier for me to let the system go on with it's normal process, but read the created CSV, modify the time stamp columns to the right format, and create the new csv like that and then send it off.

I almost have it working but for some reason my function is adding an additional empty row in between every row.

My function:

def convertFileToIsoFormat(read_filePath, write_filePath):
    import csv
    import datetime
    from __future__ import with_statement
    with open(read_filePath) as csvfile:
        reader = csv.reader(csvfile, delimiter='\t')
        for row in reader:
            modifiedRow = row
            columnsToModify = [4,7,11]
            for column in columnsToModify:
                modifiedRow[column] = datetime.datetime.strptime(modifiedRow[column], '%Y-%m-%d %H:%M:%S').isoformat()
            # Special column with different format
            modifiedRow[22] = datetime.datetime.strptime(modifiedRow[21], '%m/%d/%Y %H:%M:%S %p').isoformat()
            with open(write_filePath, 'a') as newcsv:
                writer = csv.writer(newcsv, delimiter='\t')
                writer.writewrow(modifiedRow)

This works in making the file, and in Notepad on this Windows Server 2012 the file looks right, but in my newer Windows 10 notepad I see the extra rows, and in NotePad++ on either computer I see the extra rows, so I suspect it has something to do with what the linebreak character is supposed to be for the os but I don't know how to work with that here.

Using python (technically jython) 2.5 for this.  Any thoughts on what I am missing?


问:
SqlConnection with VB.NET, is there System.Data.dll missing?
With my VBA experience I´m trying VB.NET now. First I need a connection to my MS SQL Server.

```<code>Imports System.Data.SqlClient
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim connetionString As String
        Dim cnn As SqlConnection
        connetionString = "Data Source=MyDS;Initial Catalog=MyIC;User ID=MyUser;Password=MyPW"
        cnn = New SqlConnection(connetionString)
        Try
            cnn.Open()
            MsgBox("Connection Open ! ")
            cnn.Close()
        Catch ex As Exception
            MsgBox("Can not open connection ! ")
        End Try
    End Sub
End Class
</code>```

The error: Type "SqlConnection" is not defined.
SqlConnection is also red underlined directly in the Dim cnn - line.
Also there is no intellisense suggestion for it.

I came across System.Data.dll several times on google searches. Is it missing in my system? I tried to import it without success.
Then I searched it in
C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5
and
C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0
It isn´t there.
Is System.Data.dll my problem?

Win10, Visual Studio Version 17.4.1 (64-Bit)

Maybe I´ve installed Visual Studio incomplete? Or is there an other reason for my problem?

Thank you very much for your time and a hot tip :-)

Body:
With my VBA experience I´m trying VB.NET now. First I need a connection to my MS SQL Server.

Imports System.Data.SqlClient
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim connetionString As String
        Dim cnn As SqlConnection
        connetionString = "Data Source=MyDS;Initial Catalog=MyIC;User ID=MyUser;Password=MyPW"
        cnn = New SqlConnection(connetionString)
        Try
            cnn.Open()
            MsgBox("Connection Open ! ")
            cnn.Close()
        Catch ex As Exception
            MsgBox("Can not open connection ! ")
        End Try
    End Sub
End Class

The error: Type "SqlConnection" is not defined.
SqlConnection is also red underlined directly in the Dim cnn - line.
Also there is no intellisense suggestion for it.

I came across System.Data.dll several times on google searches. Is it missing in my system? I tried to import it without success.
Then I searched it in
C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5
and
C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0
It isn´t there.
Is System.Data.dll my problem?

Win10, Visual Studio Version 17.4.1 (64-Bit)

Maybe I´ve installed Visual Studio incomplete? Or is there an other reason for my problem?

Thank you very much for your time and a hot tip :-)


问:
Error for caret linear model : Cross Validation?
```<code>caret::train(charges~age+bmi+children+smoker,
            data = PC_Train,
            method = "lm",
            trControl = trainControl(method = "cv",
                                     number = 5))
</code>```

Error in trainControl(method = "cv", number = 5) :
could not find function "trainControl"

How do I fix this error?

The dataset is found here:
https://www.kaggle.com/datasets/annetxu/health-insurance-cost-prediction

Body:
caret::train(charges~age+bmi+children+smoker,
            data = PC_Train,
            method = "lm",
            trControl = trainControl(method = "cv",
                                     number = 5))

Error in trainControl(method = "cv", number = 5) :
could not find function "trainControl"

How do I fix this error?

The dataset is found here:
https://www.kaggle.com/datasets/annetxu/health-insurance-cost-prediction


问:
Flak wrappers for authentication
I am trying to put a validate wrapper around my flask endpoints to check if the user has permissions to the data.  I want to define the permissions required in the decorator and then the wrapper verifies the user has those roles.

```<code>def create_app(config):
    app=Flask(__name__)
    app.config.from_object(config)

    db.init_app(app)

    JWTManager(app)
    app.config["JWT_ROLE_CLAIM"] = "roles"
    jwt.init_app(app)

    api.add_namespace(auth_ns)
    api.add_namespace(tasks_ns)

    return app

</code>```
```<code>from flask_jwt_extended import get_jwt_claims

def requires_roles(*roles):
    def wrapper(f):
        @wraps(f)
        def wrapped(*args, **kwargs):
            # Get the user's roles from the JWT token
            user_roles = get_jwt_claims().get("roles")

            # Check if the user has any of the required roles
            if any(role in user_roles for role in roles):
                # Call the endpoint function and return its result
                return f(*args, **kwargs)
            else:
                # Return a 403 Forbidden response
                return "Forbidden", 403
        return wrapped
    return wrapper
</code>```
```<code>@auth_ns.route('/authtest')
@requires_roles("admin", "manager")
class AuthtestResource(Resource):
    # @jwt_required()
    def get(self):
        return make_response(jsonify({"msg":"Authenticated success"}),200)
</code>```

I get this error: cannot import name 'get_jwt_claims' from 'flask_jwt_extended'

I am not very familiar with decorators, what am I doing wrong here?

I have tried creating a decorator and using an AI tool to help me  write the code

Title: Flak wrappers for authentication

Body:
I am trying to put a validate wrapper around my flask endpoints to check if the user has permissions to the data.  I want to define the permissions required in the decorator and then the wrapper verifies the user has those roles.

def create_app(config):
    app=Flask(__name__)
    app.config.from_object(config)

    db.init_app(app)

    JWTManager(app)
    app.config["JWT_ROLE_CLAIM"] = "roles"
    jwt.init_app(app)

    api.add_namespace(auth_ns)
    api.add_namespace(tasks_ns)

    return app

from flask_jwt_extended import get_jwt_claims

def requires_roles(*roles):
    def wrapper(f):
        @wraps(f)
        def wrapped(*args, **kwargs):
            # Get the user's roles from the JWT token
            user_roles = get_jwt_claims().get("roles")

            # Check if the user has any of the required roles
            if any(role in user_roles for role in roles):
                # Call the endpoint function and return its result
                return f(*args, **kwargs)
            else:
                # Return a 403 Forbidden response
                return "Forbidden", 403
        return wrapped
    return wrapper

@auth_ns.route('/authtest')
@requires_roles("admin", "manager")
class AuthtestResource(Resource):
    # @jwt_required()
    def get(self):
        return make_response(jsonify({"msg":"Authenticated success"}),200)

I get this error: cannot import name 'get_jwt_claims' from 'flask_jwt_extended'

I am not very familiar with decorators, what am I doing wrong here?

I have tried creating a decorator and using an AI tool to help me  write the code


问:
Dockerized Logic App dont work when container is running, but work in debug mode on VS Code
I am trying to put inside a docker image an Azure Logic Apps.
I was following some Microsoft tutorials:
This for creating the Logic Apps (is a bit outdate, but is mainly valid): https://microsoft.github.io/AzureTipsAndTricks/blog/tip304.html
And this for make the docker image: https://techcommunity.microsoft.com/t5/azure-developer-community-blog/azure-tips-and-tricks-how-to-run-logic-apps-in-a-docker/ba-p/3545220
The only diference between this tutorials and my poc is that I am using the node mode of the Logic Apps, instead of Net Core, and the dockerfile that I am using:

```<code>FROM mcr.microsoft.com/azure-functions/node:3.0
ENV AzureWebJobsStorage DefaultEndpointsProtocol=https;AccountName=logicappsexamples;AccountKey=AHaGR5SQZYdB2LgS2+pPbsFQO3eZDZ25T5EV3mcc1ZWJXOk7QTCKEpjDcyD6lp2J9MYo+c1OcpLu+ASt8aoEWg==;EndpointSuffix=core.windows.net
ENV AzureWebJobsScriptRoot=/home/site/wwwroot \
    AzureFunctionsJobHost__Logging__Console__IsEnabled=true \
    FUNCTIONS_V2_COMPATIBILITY_MODE=true
ENV WEBSITE_HOSTNAME localhost
ENV WEBSITE_SITE_NAME test
ENV AZURE_FUNCTIONS_ENVIRONMENT Development

COPY . /home/site/wwwroot
RUN cd /home/site/wwwroot
</code>```

The logic app is simple, just put a message in a queue when you call to an url. In debug mode on VSCode all work fine. But the problem come when run the dockerized logic app.

The problems come when I run the image. The logic App have to use a queue called "test", but when the container end to set up, it create a new queue:

[![enter image description here][1]][1]

An in the last step of the last tutorial (https://techcommunity.microsoft.com/t5/azure-developer-community-blog/azure-tips-and-tricks-how-to-run-logic-apps-in-a-docker/ba-p/3545220) when I call to the trigger url, I dont recibe anything in neither od the queue.

I have receibed this logs from the running container:

```<code>info: Host.Triggers.Workflows[206]
      Workflow action ends.
      flowName='Stateless1',
      actionName='Put_a_message_on_a_queue_(V2)',
      flowId='2731d82fc1324e4fb0df69fd5c549d72',
      flowSequenceId='08585288407219836302',
      flowRunSequenceId='08585288406768053370693349962CU00',
      correlationId='ebf4e18e-405f-41c8-bb6a-bdf84d4a7a16',
      status='Failed',
      statusCode='BadRequest',
      error='', durationInMilliseconds='910',
      inputsContentSize='-1',
      outputsContentSize='-1',
      extensionVersion='1.2.18.1',
      siteName='test',
      slotName='',
      actionTrackingId='1439f372-4ce0-4709-b9ab-ee18db8839ae',
      clientTrackingId='08585288406768053370693349962CU00',
      properties='{
            "$schema":"2016-06-01",
            "startTime":"2023-01-03T17:16:48.9639703Z",
            "endTime":"2023-01-03T17:16:49.8743232Z",
            "status":"Failed",
            "code":"BadRequest",
            "executionClusterType":"Classic",
            "resource":{
                  "workflowId":"2731d82fc1324e4fb0df69fd5c549d72",
                  "workflowName":"Stateless1",
                  "runId":"08585288406768053370693349962CU00",
                  "actionName":"Put_a_message_on_a_queue_(V2)"
                  },
            "correlation":{
                  "actionTrackingId":"1439f372-4ce0-4709-b9ab-ee18db8839ae",
                  "clientTrackingId":"08585288406768053370693349962CU00"
                  },
            "api":{}
            }',
      actionType='ApiConnection',
      sequencerType='Linear',
      flowScaleUnit='cu00',
      platformOptions='RunDistributionAcrossPartitions, RepetitionsDistributionAcrossSequencers, RunIdTruncationForJobSequencerIdDisabled, RepetitionPreaggregationEnabled',
      retryHistory='',
      failureCause='',
      overrideUsageConfigurationName='',
      hostName='',
      activityId='46860f56-96bc-462a-b9bc-3aed4ad6464c'.

info: Host.Triggers.Workflows[202]
      Workflow run ends.
      flowName='Stateless1',
      flowId='2731d82fc1324e4fb0df69fd5c549d72',
      flowSequenceId='08585288407219836302',
      flowRunSequenceId='08585288406768053370693349962CU00',
      correlationId='ebf4e18e-405f-41c8-bb6a-bdf84d4a7a16',
      extensionVersion='1.2.18.1',
      siteName='test',
      slotName='',
      status='Failed',
      statusCode='ActionFailed',
      error='{
            "code":"ActionFailed",
            "message":"An action failed. No dependent actions succeeded."
            }',
      durationInMilliseconds='1202',
      clientTrackingId='08585288406768053370693349962CU00',
      properties='{
            "$schema":"2016-06-01",
            "startTime":"2023-01-03T17:16:48.7228752Z",
            "endTime":"2023-01-03T17:16:50.0174324Z",
            "status":"Failed",
            "code":"ActionFailed",
            "executionClusterType":"Classic",
            "resource":{
                  "workflowId":"2731d82fc1324e4fb0df69fd5c549d72",
                  "workflowName":"Stateless1",
                  "runId":"08585288406768053370693349962CU00",
                  "originRunId":"08585288406768053370693349962CU00"
                  },
            "correlation":{
                  "clientTrackingId":"08585288406768053370693349962CU00"
                  },
            "error":{
                  "code":"ActionFailed",
                  "message":"An action failed. No dependent actions succeeded."
                  }
            }',
      sequencerType='Linear',
      flowScaleUnit='cu00',
      platformOptions='RunDistributionAcrossPartitions, RepetitionsDistributionAcrossSequencers, RunIdTruncationForJobSequencerIdDisabled, RepetitionPreaggregationEnabled',
      kind='Stateless',
      runtimeOperationOptions='None',
      usageConfigurationName='',
      hostName='',
      activityId='c6ca440e-fef5-457a-a4cb-9d5a3d806518'.
info: Host.Triggers.Workflows[203]
      Workflow trigger starts.
      flowName='Stateless1',
      triggerName='manual',
      flowId='2731d82fc1324e4fb0df69fd5c549d72',
      flowSequenceId='08585288407219836302',
      extensionVersion='1.2.18.1',
      siteName='test',
      slotName='',
      status='',
      statusCode='',
      error='',
      durationInMilliseconds='-1',
      flowRunSequenceId='08585288406768053370693349962CU00',
      inputsContentSize='-1',
      outputsContentSize='-1',
      clientTrackingId='08585288406768053370693349962CU00',
      properties='{
            "$schema":"2016-06-01",
            "startTime":"2023-01-03T17:16:48.6768387Z",
            "status":"Succeeded",
            "fired":true,
            "resource":{
                  "workflowId":"2731d82fc1324e4fb0df69fd5c549d72",
                  "workflowName":"Stateless1",
                  "runId":"08585288406768053370693349962CU00",
                  "triggerName":"manual"
            },
            "correlation":{
                  "clientTrackingId":"08585288406768053370693349962CU00"
                  },
            "api":{}
      }',
      triggerType='Request',
      flowScaleUnit='cu00',
      triggerKind='Http',
      sourceTriggerHistoryName='',
      failureCause='',
      hostName='',
      activityId='ebf4e18e-405f-41c8-bb6a-bdf84d4a7a16'.
info: Host.Triggers.Workflows[204]
      Workflow trigger ends.
      flowName='Stateless1',
      triggerName='manual',
      flowId='2731d82fc1324e4fb0df69fd5c549d72',
      flowSequenceId='08585288407219836302',
      status='Succeeded',
      statusCode='',
      error='',
      extensionVersion='1.2.18.1',
      siteName='test',
      slotName='',
      durationInMilliseconds='1348',
      flowRunSequenceId='08585288406768053370693349962CU00',
      inputsContentSize='-1',
      outputsContentSize='-1',
      clientTrackingId='08585288406768053370693349962CU00',
      properties='{
            "$schema":"2016-06-01",
            "startTime":"2023-01-03T17:16:48.6768387Z",
            "endTime":"2023-01-03T17:16:50.0319177Z",
            "status":"Succeeded",
            "fired":true,
            "resource":{
                  "workflowId":"2731d82fc1324e4fb0df69fd5c549d72",
                  "workflowName":"Stateless1",
                  "runId":"08585288406768053370693349962CU00",
                  "triggerName":"manual"
                  },
            "correlation":{
                  "clientTrackingId":"08585288406768053370693349962CU00"
                  },
            "api":{}
      }',
      triggerType='Request',
      flowScaleUnit='cu00',
      triggerKind='Http',
      sourceTriggerHistoryName='',
      failureCause='',
      overrideUsageConfigurationName='',
      hostName='',
      activityId='ebf4e18e-405f-41c8-bb6a-bdf84d4a7a16'.
info: Function.Stateless1[2]
      Executed 'Functions.Stateless1' (Succeeded, Id=10af0f54-765a-4954-a42f-373ceb58c94b, Duration=1545ms)
</code>```

So, what I am doing bad? I mean, It look like as the info to de queue name (test) is not property passed to the docker imagen and for this reason, the docker image create a new one... but how I can fix it?

I would greatly appreciate any help... I cant find anything clear in internet.

Thanks!

Body:
I am trying to put inside a docker image an Azure Logic Apps.
I was following some Microsoft tutorials:
This for creating the Logic Apps (is a bit outdate, but is mainly valid): https://microsoft.github.io/AzureTipsAndTricks/blog/tip304.html
And this for make the docker image: https://techcommunity.microsoft.com/t5/azure-developer-community-blog/azure-tips-and-tricks-how-to-run-logic-apps-in-a-docker/ba-p/3545220
The only diference between this tutorials and my poc is that I am using the node mode of the Logic Apps, instead of Net Core, and the dockerfile that I am using:

FROM mcr.microsoft.com/azure-functions/node:3.0
ENV AzureWebJobsStorage DefaultEndpointsProtocol=https;AccountName=logicappsexamples;AccountKey=AHaGR5SQZYdB2LgS2+pPbsFQO3eZDZ25T5EV3mcc1ZWJXOk7QTCKEpjDcyD6lp2J9MYo+c1OcpLu+ASt8aoEWg==;EndpointSuffix=core.windows.net
ENV AzureWebJobsScriptRoot=/home/site/wwwroot \
    AzureFunctionsJobHost__Logging__Console__IsEnabled=true \
    FUNCTIONS_V2_COMPATIBILITY_MODE=true
ENV WEBSITE_HOSTNAME localhost
ENV WEBSITE_SITE_NAME test
ENV AZURE_FUNCTIONS_ENVIRONMENT Development

COPY . /home/site/wwwroot
RUN cd /home/site/wwwroot

The logic app is simple, just put a message in a queue when you call to an url. In debug mode on VSCode all work fine. But the problem come when run the dockerized logic app.

The problems come when I run the image. The logic App have to use a queue called "test", but when the container end to set up, it create a new queue:

[![enter image description here][1]][1]

An in the last step of the last tutorial (https://techcommunity.microsoft.com/t5/azure-developer-community-blog/azure-tips-and-tricks-how-to-run-logic-apps-in-a-docker/ba-p/3545220) when I call to the trigger url, I dont recibe anything in neither od the queue.

I have receibed this logs from the running container:

info: Host.Triggers.Workflows[206]
      Workflow action ends.
      flowName='Stateless1',
      actionName='Put_a_message_on_a_queue_(V2)',
      flowId='2731d82fc1324e4fb0df69fd5c549d72',
      flowSequenceId='08585288407219836302',
      flowRunSequenceId='08585288406768053370693349962CU00',
      correlationId='ebf4e18e-405f-41c8-bb6a-bdf84d4a7a16',
      status='Failed',
      statusCode='BadRequest',
      error='', durationInMilliseconds='910',
      inputsContentSize='-1',
      outputsContentSize='-1',
      extensionVersion='1.2.18.1',
      siteName='test',
      slotName='',
      actionTrackingId='1439f372-4ce0-4709-b9ab-ee18db8839ae',
      clientTrackingId='08585288406768053370693349962CU00',
      properties='{
            "$schema":"2016-06-01",
            "startTime":"2023-01-03T17:16:48.9639703Z",
            "endTime":"2023-01-03T17:16:49.8743232Z",
            "status":"Failed",
            "code":"BadRequest",
            "executionClusterType":"Classic",
            "resource":{
                  "workflowId":"2731d82fc1324e4fb0df69fd5c549d72",
                  "workflowName":"Stateless1",
                  "runId":"08585288406768053370693349962CU00",
                  "actionName":"Put_a_message_on_a_queue_(V2)"
                  },
            "correlation":{
                  "actionTrackingId":"1439f372-4ce0-4709-b9ab-ee18db8839ae",
                  "clientTrackingId":"08585288406768053370693349962CU00"
                  },
            "api":{}
            }',
      actionType='ApiConnection',
      sequencerType='Linear',
      flowScaleUnit='cu00',
      platformOptions='RunDistributionAcrossPartitions, RepetitionsDistributionAcrossSequencers, RunIdTruncationForJobSequencerIdDisabled, RepetitionPreaggregationEnabled',
      retryHistory='',
      failureCause='',
      overrideUsageConfigurationName='',
      hostName='',
      activityId='46860f56-96bc-462a-b9bc-3aed4ad6464c'.

info: Host.Triggers.Workflows[202]
      Workflow run ends.
      flowName='Stateless1',
      flowId='2731d82fc1324e4fb0df69fd5c549d72',
      flowSequenceId='08585288407219836302',
      flowRunSequenceId='08585288406768053370693349962CU00',
      correlationId='ebf4e18e-405f-41c8-bb6a-bdf84d4a7a16',
      extensionVersion='1.2.18.1',
      siteName='test',
      slotName='',
      status='Failed',
      statusCode='ActionFailed',
      error='{
            "code":"ActionFailed",
            "message":"An action failed. No dependent actions succeeded."
            }',
      durationInMilliseconds='1202',
      clientTrackingId='08585288406768053370693349962CU00',
      properties='{
            "$schema":"2016-06-01",
            "startTime":"2023-01-03T17:16:48.7228752Z",
            "endTime":"2023-01-03T17:16:50.0174324Z",
            "status":"Failed",
            "code":"ActionFailed",
            "executionClusterType":"Classic",
            "resource":{
                  "workflowId":"2731d82fc1324e4fb0df69fd5c549d72",
                  "workflowName":"Stateless1",
                  "runId":"08585288406768053370693349962CU00",
                  "originRunId":"08585288406768053370693349962CU00"
                  },
            "correlation":{
                  "clientTrackingId":"08585288406768053370693349962CU00"
                  },
            "error":{
                  "code":"ActionFailed",
                  "message":"An action failed. No dependent actions succeeded."
                  }
            }',
      sequencerType='Linear',
      flowScaleUnit='cu00',
      platformOptions='RunDistributionAcrossPartitions, RepetitionsDistributionAcrossSequencers, RunIdTruncationForJobSequencerIdDisabled, RepetitionPreaggregationEnabled',
      kind='Stateless',
      runtimeOperationOptions='None',
      usageConfigurationName='',
      hostName='',
      activityId='c6ca440e-fef5-457a-a4cb-9d5a3d806518'.
info: Host.Triggers.Workflows[203]
      Workflow trigger starts.
      flowName='Stateless1',
      triggerName='manual',
      flowId='2731d82fc1324e4fb0df69fd5c549d72',
      flowSequenceId='08585288407219836302',
      extensionVersion='1.2.18.1',
      siteName='test',
      slotName='',
      status='',
      statusCode='',
      error='',
      durationInMilliseconds='-1',
      flowRunSequenceId='08585288406768053370693349962CU00',
      inputsContentSize='-1',
      outputsContentSize='-1',
      clientTrackingId='08585288406768053370693349962CU00',
      properties='{
            "$schema":"2016-06-01",
            "startTime":"2023-01-03T17:16:48.6768387Z",
            "status":"Succeeded",
            "fired":true,
            "resource":{
                  "workflowId":"2731d82fc1324e4fb0df69fd5c549d72",
                  "workflowName":"Stateless1",
                  "runId":"08585288406768053370693349962CU00",
                  "triggerName":"manual"
            },
            "correlation":{
                  "clientTrackingId":"08585288406768053370693349962CU00"
                  },
            "api":{}
      }',
      triggerType='Request',
      flowScaleUnit='cu00',
      triggerKind='Http',
      sourceTriggerHistoryName='',
      failureCause='',
      hostName='',
      activityId='ebf4e18e-405f-41c8-bb6a-bdf84d4a7a16'.
info: Host.Triggers.Workflows[204]
      Workflow trigger ends.
      flowName='Stateless1',
      triggerName='manual',
      flowId='2731d82fc1324e4fb0df69fd5c549d72',
      flowSequenceId='08585288407219836302',
      status='Succeeded',
      statusCode='',
      error='',
      extensionVersion='1.2.18.1',
      siteName='test',
      slotName='',
      durationInMilliseconds='1348',
      flowRunSequenceId='08585288406768053370693349962CU00',
      inputsContentSize='-1',
      outputsContentSize='-1',
      clientTrackingId='08585288406768053370693349962CU00',
      properties='{
            "$schema":"2016-06-01",
            "startTime":"2023-01-03T17:16:48.6768387Z",
            "endTime":"2023-01-03T17:16:50.0319177Z",
            "status":"Succeeded",
            "fired":true,
            "resource":{
                  "workflowId":"2731d82fc1324e4fb0df69fd5c549d72",
                  "workflowName":"Stateless1",
                  "runId":"08585288406768053370693349962CU00",
                  "triggerName":"manual"
                  },
            "correlation":{
                  "clientTrackingId":"08585288406768053370693349962CU00"
                  },
            "api":{}
      }',
      triggerType='Request',
      flowScaleUnit='cu00',
      triggerKind='Http',
      sourceTriggerHistoryName='',
      failureCause='',
      overrideUsageConfigurationName='',
      hostName='',
      activityId='ebf4e18e-405f-41c8-bb6a-bdf84d4a7a16'.
info: Function.Stateless1[2]
      Executed 'Functions.Stateless1' (Succeeded, Id=10af0f54-765a-4954-a42f-373ceb58c94b, Duration=1545ms)

So, what I am doing bad? I mean, It look like as the info to de queue name (test) is not property passed to the docker imagen and for this reason, the docker image create a new one... but how I can fix it?

I would greatly appreciate any help... I cant find anything clear in internet.

Thanks!


问:
How to Pass value along with file upload through webclient C#
Now currently uploading a file only through below code .. what actually looking is need to send a value "myValue" too how can i achieve this

```<code>      string message, title, defaultValue;
        string myValue;

        message = "Enter Image name please";

        title = "Image name";

        defaultValue = "1";
            myValue =Interaction.InputBox(message, title, defaultValue,100,100);
using (System.Net.WebClient Client = new System.Net.WebClient())
        {
            Client.Headers.Add("Content-Type", "binary/octet-stream");
            Client.Headers.Add("SESSION-KEY", App.Session_Key);

        try
        {
            byte[] result = Client.UploadFile(Screenshot.Properties.Resources.APIURL + "Upload.php", "POST", "temp.png");
</code>```

here i need to send "myValue " too while file upload

Body:
Now currently uploading a file only through below code .. what actually looking is need to send a value "myValue" too how can i achieve this

      string message, title, defaultValue;
        string myValue;

        message = "Enter Image name please";

        title = "Image name";

        defaultValue = "1";
            myValue =Interaction.InputBox(message, title, defaultValue,100,100);
using (System.Net.WebClient Client = new System.Net.WebClient())
        {
            Client.Headers.Add("Content-Type", "binary/octet-stream");
            Client.Headers.Add("SESSION-KEY", App.Session_Key);

        try
        {
            byte[] result = Client.UploadFile(Screenshot.Properties.Resources.APIURL + "Upload.php", "POST", "temp.png");

here i need to send "myValue " too while file upload


问:
Inject Symfony Service in a Bundle for Akeneo Pim
I am trying to inject a service from Akeneo to my selfwritten Bundle.
To be exact, i want to use the service defined here  in my bundle instead of an Processor.

```<code>services:
     _defaults:
         autowire: true
         autoconfigure: true
     Acme\CategoryBuilder:
         class: Acme\CategoryBuilder\CategoryBuilder
         arguments:
             - '@pim_catalog.repository.category'
         tags:
             - { name: kernel.event_listener, event: akeneo.storage.post_save, method: onPostSave }
</code>```

and this constructor:

```<code>public function __construct(CategoryRepositoryInterface
$categoryRepositoryInterface){
         $this->categoryRepositoryInterface = $categoryRepositoryInterface;
}
</code>```

in a Class called CategoryBuilder.
This setup does not work and if i try to clear & warmup the cache, i get the Error Response that 0 arguments are passed but 1 was expected.
How can i pass this service to my Bundle?

Edit:

if i run:  php bin/console debug:container pim_catalog.repository.category i get the following output:

```<code>Information for Service "pim_catalog.repository.category"
=========================================================

 Category repository

 ----------------- ------------------------------------------------------------------------------------
  Option            Value
 ----------------- ------------------------------------------------------------------------------------
  Service ID        pim_catalog.repository.category
  Class             Akeneo\Tool\Bundle\ClassificationBundle\Doctrine\ORM\Repository\CategoryRepository
  Tags              pim_repository
  Public            no
  Synthetic         no
  Lazy              no
  Shared            yes
  Abstract          no
  Autowired         no
  Autoconfigured    no
  Factory Service   doctrine.orm.default_entity_manager
  Factory Method    getRepository
 ----------------- ------------------------------------------------------------------------------------

 ! [NOTE] The "pim_catalog.repository.category" service or alias has been removed or inlined when the container was
 !        compiled.
</code>```

Does the Note mean i just cant get this Service? If so, how can i restore it?

Body:
I am trying to inject a service from Akeneo to my selfwritten Bundle.
To be exact, i want to use the service defined here  in my bundle instead of an Processor.

services:
     _defaults:
         autowire: true
         autoconfigure: true
     Acme\CategoryBuilder:
         class: Acme\CategoryBuilder\CategoryBuilder
         arguments:
             - '@pim_catalog.repository.category'
         tags:
             - { name: kernel.event_listener, event: akeneo.storage.post_save, method: onPostSave }

and this constructor:

public function __construct(CategoryRepositoryInterface
$categoryRepositoryInterface){
         $this->categoryRepositoryInterface = $categoryRepositoryInterface;
}

in a Class called CategoryBuilder.
This setup does not work and if i try to clear & warmup the cache, i get the Error Response that 0 arguments are passed but 1 was expected.
How can i pass this service to my Bundle?

Edit:

if i run:  php bin/console debug:container pim_catalog.repository.category i get the following output:

Information for Service "pim_catalog.repository.category"
=========================================================

 Category repository

 ----------------- ------------------------------------------------------------------------------------
  Option            Value
 ----------------- ------------------------------------------------------------------------------------
  Service ID        pim_catalog.repository.category
  Class             Akeneo\Tool\Bundle\ClassificationBundle\Doctrine\ORM\Repository\CategoryRepository
  Tags              pim_repository
  Public            no
  Synthetic         no
  Lazy              no
  Shared            yes
  Abstract          no
  Autowired         no
  Autoconfigured    no
  Factory Service   doctrine.orm.default_entity_manager
  Factory Method    getRepository
 ----------------- ------------------------------------------------------------------------------------

 ! [NOTE] The "pim_catalog.repository.category" service or alias has been removed or inlined when the container was
 !        compiled.

Does the Note mean i just cant get this Service? If so, how can i restore it?


问:
Why does not-changing the while's variable condition not result in a loop? Edited
I've been working on a personal project for a while and recently tried to implement threads to improve performance.
Since it is essential for some instruction to be executed in a certain order I've tried implementing an extremely rudimentary way to wait for one to be finished in order for the next one to start.

While doing so I've encountered the "problem" described in the title in the following lines of code.

```<code>    bool previousDrawn = drawnTriangles[eye][i - 1];

    while (previousDrawn == false) {}
</code>```

Somehow, even when previousDrawn is initialized by drawnTriangles[eye][i - 1]  as false the program doesn't get stuck in a loop.

These lines are part of a function executed multiple times simultaneously by threads, however to my knowledge a thread's variable such as previousDrawn shouldn't be affected by wathever is going on inside the other threads.
This is the only conclusion I could think of since there aren't any instructions neither inside the loop (since it's empty) nor between the loop and previousDrawn's initialization that could modify it's value.
Admittedly drawnTriangles is a vector shared between the threads but I didn't consider it a potential cause since:

I can't see how it could affect the loop since it is read only once while initializing previousDrawn;

Even then, it would be not only extremely unlikely but impossible for 2 threads to read it at the same time based on how the function works;

As I've said before and as it's visible in the code, the components of the shared vector are only read by the threads and to my knowledge threads reading a variable simultaneously doesn't cause problems.

Any help would be greatly appreciated, so please let me know if and what I am getting wrong and/or am missing about this because I'm truly at a loss.

Edit:
I forgot to mention that I had also assumed that it probably wasn't the compiler since I tried modifying the loop's condition as

```<code>while(false == false) {}
</code>```

And the program did freeze.

Body:
I've been working on a personal project for a while and recently tried to implement threads to improve performance.
Since it is essential for some instruction to be executed in a certain order I've tried implementing an extremely rudimentary way to wait for one to be finished in order for the next one to start.

While doing so I've encountered the "problem" described in the title in the following lines of code.

    bool previousDrawn = drawnTriangles[eye][i - 1];

    while (previousDrawn == false) {}

Somehow, even when previousDrawn is initialized by drawnTriangles[eye][i - 1]  as false the program doesn't get stuck in a loop.

These lines are part of a function executed multiple times simultaneously by threads, however to my knowledge a thread's variable such as previousDrawn shouldn't be affected by wathever is going on inside the other threads.
This is the only conclusion I could think of since there aren't any instructions neither inside the loop (since it's empty) nor between the loop and previousDrawn's initialization that could modify it's value.
Admittedly drawnTriangles is a vector shared between the threads but I didn't consider it a potential cause since:

I can't see how it could affect the loop since it is read only once while initializing previousDrawn;

Even then, it would be not only extremely unlikely but impossible for 2 threads to read it at the same time based on how the function works;

As I've said before and as it's visible in the code, the components of the shared vector are only read by the threads and to my knowledge threads reading a variable simultaneously doesn't cause problems.

Any help would be greatly appreciated, so please let me know if and what I am getting wrong and/or am missing about this because I'm truly at a loss.

Edit:
I forgot to mention that I had also assumed that it probably wasn't the compiler since I tried modifying the loop's condition as

while(false == false) {}

And the program did freeze.


问:
Why am I getting "TypeError: 'x' is read-only" error without problems with 'use strict' or 'constant'?
I'm getting the error the following error in the debugger. I believe it to be an issue with what the shuffle() function is calling in line 230 (marked in the 2nd block code) and how the arrays are set up. Maybe a new way to set up these arrays would fix my issues.

ERROR:

Paused on exception

TypeError: 229 is read-only

main.js

function shuffle(array) {
    let currentIndex = array.length,  randomIndex;

    // While there remain elements to shuffle.
    while (currentIndex != 0) {

      // Pick a remaining element.
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex--;

      // And swap it with the current element.
      [array[currentIndex], array[randomIndex]] = [
        array[randomIndex], array[currentIndex]];
    }

    return array;
  }

function loadImageArray(category, abbreviation) {
    let list = [];

    for (let i = 1; i <= 10; i++) {
        list[list.length] = "./faces/" + category + "/" + abbreviation + i + ".JPG";
    }

    return list;
}

//grabs localStorage array if it exists, else creates face array and saves
function fetchArray(key, category, abbreviation){
    let data = [];
    if(localStorage.getItem(key) != null){
        data = localStorage.getItem(key);
    }
    else {
        data = loadImageArray(category, abbreviation);
        localStorage.setItem(key, data);
    }
    return data;
}

//saves localStorage face arrays with key
function setArray(key, array) {
    localStorage.setItem(key, array);
}

let faceAfraid = fetchArray("faceAfraid", "afraid", "AF");

const randomImage = Math.floor(Math.random()*10);
let emotionsArray = [faceAfraid];
for (let i = 0; i < emotionsArray.length; i++){
    //shuffle(emotionsArray[i]);
    if (randomEmotion == i && emotionsArray[randomEmotion][randomImage] != null){
        document.getElementById("faceImg").innerHTML = "";
        emotionsArray[i].splice(i, 1);
        setArray(""+emotionsArray[i],emotionsArray[i]);
    }
}
```
<p><strong>face.html</strong></p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>

<html>

    <head>

        <title>ReTER Application</title>

        <link rel="stylesheet" href="styles.css">

        <script src="main.js" type="module"></script>

    </head>

    <body class="dark" id="face">
        <div id="faceImg" class="emotionImg">
        </div>
    </body>

</html>
</code>```

I've looked up mdn web docs' explanation for this, but that didn't seem to explain my issue because I do not use 'use strict'; anywhere in my JavaScript file.

I have commented out line 230 and it stops on line 234 with a secondary error

Paused on exception

TypeError: emotionsArray[i].splice is not a function

Commenting out that line 230 and 234 removes all debugging errors, but it only displays the alt text for my image. I would also like to point out that I'm aware .innerHTML is not the preferred way to do this, but it was not causing me issues before I changed the way the face arrays were created using fetchArray.

Because these errors only arose after I created fetchArray, it's probably an error with that function, but I'm not sure what to try to fix this.

Body:
I'm getting the error the following error in the debugger. I believe it to be an issue with what the shuffle() function is calling in line 230 (marked in the 2nd block code) and how the arrays are set up. Maybe a new way to set up these arrays would fix my issues.

ERROR:

Paused on exception

TypeError: 229 is read-only

main.js

function shuffle(array) {
    let currentIndex = array.length,  randomIndex;

    // While there remain elements to shuffle.
    while (currentIndex != 0) {

      // Pick a remaining element.
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex--;

      // And swap it with the current element.
      [array[currentIndex], array[randomIndex]] = [
        array[randomIndex], array[currentIndex]];
    }

    return array;
  }

function loadImageArray(category, abbreviation) {
    let list = [];

    for (let i = 1; i <= 10; i++) {
        list[list.length] = "./faces/" + category + "/" + abbreviation + i + ".JPG";
    }

    return list;
}

//grabs localStorage array if it exists, else creates face array and saves
function fetchArray(key, category, abbreviation){
    let data = [];
    if(localStorage.getItem(key) != null){
        data = localStorage.getItem(key);
    }
    else {
        data = loadImageArray(category, abbreviation);
        localStorage.setItem(key, data);
    }
    return data;
}

//saves localStorage face arrays with key
function setArray(key, array) {
    localStorage.setItem(key, array);
}

let faceAfraid = fetchArray("faceAfraid", "afraid", "AF");

const randomImage = Math.floor(Math.random()*10);
let emotionsArray = [faceAfraid];
for (let i = 0; i < emotionsArray.length; i++){
    //shuffle(emotionsArray[i]);
    if (randomEmotion == i && emotionsArray[randomEmotion][randomImage] != null){
        document.getElementById("faceImg").innerHTML = "";
        emotionsArray[i].splice(i, 1);
        setArray(""+emotionsArray[i],emotionsArray[i]);
    }
}

face.html

<!DOCTYPE html>

        <title>ReTER Application</title>

        <link rel="stylesheet" href="styles.css">

I've looked up mdn web docs' explanation for this, but that didn't seem to explain my issue because I do not use 'use strict'; anywhere in my JavaScript file.

I have commented out line 230 and it stops on line 234 with a secondary error

Paused on exception

TypeError: emotionsArray[i].splice is not a function

Commenting out that line 230 and 234 removes all debugging errors, but it only displays the alt text for my image. I would also like to point out that I'm aware .innerHTML is not the preferred way to do this, but it was not causing me issues before I changed the way the face arrays were created using fetchArray.

Because these errors only arose after I created fetchArray, it's probably an error with that function, but I'm not sure what to try to fix this.


问:
how do I split a file into chunks by regexp line separators?
I would like to have a Linux oneliner that runs a "split" command in a slightly different way -- rather than by splitting the file into smaller files by using a constant number of lines or bytes, it will split the file according to a regexp separator that identifies where to insert the breaks and start a new file.

The problem is that most pipe commands work on one stream and can't split a stream into multiple files, unless there is some command that does that.

The closest I got to was:

```<code>cat myfile |
perl -pi -e 's/theseparatingregexp/SPLITHERE/g' |
split -l 1 -t SPLITHERE - myfileprefix
</code>```

but it appears that split command cannot take multi-character delimeters.

Body:
I would like to have a Linux oneliner that runs a "split" command in a slightly different way -- rather than by splitting the file into smaller files by using a constant number of lines or bytes, it will split the file according to a regexp separator that identifies where to insert the breaks and start a new file.

The problem is that most pipe commands work on one stream and can't split a stream into multiple files, unless there is some command that does that.

The closest I got to was:

cat myfile |
perl -pi -e 's/theseparatingregexp/SPLITHERE/g' |
split -l 1 -t SPLITHERE - myfileprefix

but it appears that split command cannot take multi-character delimeters.


问:
MIssing TERMINUS_ERROR_LOGGER argument/dependency - NestJS HealthCheck controller
I'm trying to implement a simple HealtCheck controller in my NestJS api by following the offical example Healthchecks (Terminus): https://docs.nestjs.com/recipes/terminus#setting-up-a-healthcheck but I'm getting this error:

Nest can't resolve dependencies of the HealthCheckService (HealthCheckExecutor, ?). Please make sure that the argument TERMINUS_ERROR_LOGGER at index [1] is available in the HealthCheckModule context.

Since TERMINUS_ERROR_LOGGER seems like some kind of a enum, I'm not able to import it or add it as a provider inside my HealthModule and I haven't found any documentation/blog/post related to this.

Here's my HealthCHeck controller code:

```<code>import { Controller, Get } from '@nestjs/common';
import { HealthCheckService, HttpHealthIndicator, HealthCheck, TypeOrmHealthIndicator } from '@nestjs/terminus';

@Controller('health-check')
export class HealthCheckController {

    constructor(
        private readonly health: HealthCheckService,
        private db: TypeOrmHealthIndicator,
    ) { }

    @Get()
    @HealthCheck()
    readiness() {
        return this.health.check([
            async () => this.db.pingCheck('postgres', { timeout: 300 }),
        ]);
    }
}
</code>```

I just want to create a HealtCheck controller to check if the api is connected to my db and implement future health checks.

Body:
I'm trying to implement a simple HealtCheck controller in my NestJS api by following the offical example Healthchecks (Terminus): https://docs.nestjs.com/recipes/terminus#setting-up-a-healthcheck but I'm getting this error:

Nest can't resolve dependencies of the HealthCheckService (HealthCheckExecutor, ?). Please make sure that the argument TERMINUS_ERROR_LOGGER at index [1] is available in the HealthCheckModule context.

Since TERMINUS_ERROR_LOGGER seems like some kind of a enum, I'm not able to import it or add it as a provider inside my HealthModule and I haven't found any documentation/blog/post related to this.

Here's my HealthCHeck controller code:

import { Controller, Get } from '@nestjs/common';
import { HealthCheckService, HttpHealthIndicator, HealthCheck, TypeOrmHealthIndicator } from '@nestjs/terminus';

@Controller('health-check')
export class HealthCheckController {

    constructor(
        private readonly health: HealthCheckService,
        private db: TypeOrmHealthIndicator,
    ) { }

    @Get()
    @HealthCheck()
    readiness() {
        return this.health.check([
            async () => this.db.pingCheck('postgres', { timeout: 300 }),
        ]);
    }
}

I just want to create a HealtCheck controller to check if the api is connected to my db and implement future health checks.


问:
Set toolbar bottom page of rdlc ReportViewer C#
I would like to generate the toolbar below the report table

enter image description here


问:
Firebase sign in with email link Suspicious/Dangerous
I have decided to switch my customer base over to email link sign in with Firebase rather than Google/Email/Apple that I was previously doing.

I got everything set up, tested, and all was working well. Since I have now released customer wide I am starting to run into issues.

Some customers, including gmail users are getting a Suspicious email alert due to having a firebaseapp.com link in it. Today, I created a brand new project for a customer and went to log in for the first time, Gmail as all good, but now Chrome is giving me a "Deceptive site ahead" error page saying this website does phishing (the subdomain is about 6 hours old).

Can anyone think of an appropriate solution for this, or will I have to do some URL rewriting?

It is frustrating the firebase URLs are so blacklisted across the internet(I have had to omit storage url links for pictures and make custom emails altogether since the domain is banned by Exchange), I would think this should be much easier than it is being made out to be.

When I first ran into the Gmail issue the only thing Firebase support gave me as a solution is to build my own custom email handler. In following that, I assume I would either need to rewrite the domain after generating the sign in link, which I am a bit hesitant to do in case there are domain changes in the future or I wondered if updating my email template domain will solve the problem. When I started this process I realized I needed to update my DNS records for this. The problem here is that I whitelabel apps and have 150 projects or so and each customer gets their own project. The management of this is really not feasible.

I have dynamic links enabled for all projects and use the projectid.page.link domain for them if there is some way I can get that to work as well.


问:
I'm trying to load my cog through 3 folders, however, it doesnt seem to work
My directory goes like this:
bob (folder) -> main (folder) -> commands (folder) -> test (folder) test.py (file)

This code seems to work fine

```<code>async def load1():
    for filename in os.listdir("main/commands"):
        if filename.endswith(".py"):
            await client.load_extension(f"commands.{filename[:-3]}")
</code>```

but i want my code to go through another folder
like this

```<code>async def load1():
    for filename in os.listdir("main/commands/testfolder"):
        if filename.endswith(".py"):
            await client.load_extension(f"testfolder.{filename[:-3]}")
</code>```

when i run this, it gives me the error: ModuleNotFoundError: No module named 'testfolder'

Basically, i want my code to load folders which would contain something like this
commandFolder -> command.py, command.json, command.txt

Is this possible?

Body:
My directory goes like this:
bob (folder) -> main (folder) -> commands (folder) -> test (folder) test.py (file)

This code seems to work fine

async def load1():
    for filename in os.listdir("main/commands"):
        if filename.endswith(".py"):
            await client.load_extension(f"commands.{filename[:-3]}")

but i want my code to go through another folder
like this

async def load1():
    for filename in os.listdir("main/commands/testfolder"):
        if filename.endswith(".py"):
            await client.load_extension(f"testfolder.{filename[:-3]}")

when i run this, it gives me the error: ModuleNotFoundError: No module named 'testfolder'

Basically, i want my code to load folders which would contain something like this
commandFolder -> command.py, command.json, command.txt

Is this possible?


问:
Want to sort posts in a way current user's favorite posts are shown on top
I'm using "Search and filter" plugin, and "WP Favorites" plugin. I'm using following code in custom template

```<code> if ($query->have_posts())

{
    while ($query->have_posts())
    {
        $query->the_post();
        $meta_values = get_post_meta( get_the_ID() );
        $post_meta_value = get_post_meta( get_the_ID(), '_audioigniter_tracks',true );

foreach($post_meta_value as $name) {

$kjkj = get_the_ID();
  echo do_shortcode("[favorite_button post_id='$kjkj']");?>
  <a class="a" href="<?php echo $name['track_url']?>"><?php the_title() ?></a><br/><?php

  }
}
}
</code>```

While in functions.php I'm using following code to sort but it's not working as I'm missing something related to user favorite posts meta

```<code>function myfunctions( $query, $sfid ) {
    //global $wpdb, $query, $wp;

    if($sfid==133203)
    {
        $favs = get_user_favorites();
foreach($post_meta_valuee as $fst) {
        $query['order'] = 'DESC';
        $query['orderby'] = 'meta_value';
        $query['meta_key'] = 'simplefavorites_count';

    }

    return $query;
}
add_filter( 'sf_edit_query_args', 'myfunctions', 20, 2 );
</code>```

Problem is in functions.php code, I'm somehow not able to let the query know info about users favorites (simplefavorites_count is total count by all users, not by current user). So I need help here.

Body:
I'm using "Search and filter" plugin, and "WP Favorites" plugin. I'm using following code in custom template

 if ($query->have_posts())

{
    while ($query->have_posts())
    {
        $query->the_post();
        $meta_values = get_post_meta( get_the_ID() );
        $post_meta_value = get_post_meta( get_the_ID(), '_audioigniter_tracks',true );

foreach($post_meta_value as $name) {

$kjkj = get_the_ID();
  echo do_shortcode("[favorite_button post_id='$kjkj']");?>
  <a class="a" href="<?php echo $name['track_url']?>"><?php the_title() ?>
<?php

  }
}
}

While in functions.php I'm using following code to sort but it's not working as I'm missing something related to user favorite posts meta

function myfunctions( $query, $sfid ) {
    //global $wpdb, $query, $wp;

    if($sfid==133203)
    {
        $favs = get_user_favorites();
foreach($post_meta_valuee as $fst) {
        $query['order'] = 'DESC';
        $query['orderby'] = 'meta_value';
        $query['meta_key'] = 'simplefavorites_count';

    }

    return $query;
}
add_filter( 'sf_edit_query_args', 'myfunctions', 20, 2 );

Problem is in functions.php code, I'm somehow not able to let the query know info about users favorites (simplefavorites_count is total count by all users, not by current user). So I need help here.


问:
How do I set the 'brush hardness' on itext canvas stroke lines?
The base of my exploration into itext7 for Java was the c03e02_premierleague jumpstart tutorial. The following line of code is probably the one that needs some function added to make the line have a sharper edge, but although I have looked through the list of available methods, I could not make out the one that would achieve this.

```<code>canvas.moveTo(llx, lly)
    .lineTo(urx, lly)
    .lineTo(urx, ury - r)
    .curveTo(urx, ury - r * b, urx - r * b, ury, urx - r, ury)
    .lineTo(llx + r, ury)
    .curveTo(llx + r * b, ury, llx, ury - r * b, llx, ury - r)
    .lineTo(llx, lly).stroke();
</code>```

After a few problems like for example the line stroke not closing with closePathStroke(), I saw that the canvas stroke lines method used for the header cells is different from the SolidBorders used for the other cells.

The borders created using a PdfCanvas gray out to the edges of the line, whereas the standard borders go directly from black to white. Clear, sharp edges is what I want on all of those lines.

Here a screenshot zoomed into the top right corner of my slightly modified version of this example (purposefully left in the not properly rendered state to clarify my point).

Body:
The base of my exploration into itext7 for Java was the c03e02_premierleague jumpstart tutorial. The following line of code is probably the one that needs some function added to make the line have a sharper edge, but although I have looked through the list of available methods, I could not make out the one that would achieve this.

canvas.moveTo(llx, lly)
    .lineTo(urx, lly)
    .lineTo(urx, ury - r)
    .curveTo(urx, ury - r * b, urx - r * b, ury, urx - r, ury)
    .lineTo(llx + r, ury)
    .curveTo(llx + r * b, ury, llx, ury - r * b, llx, ury - r)
    .lineTo(llx, lly).stroke();

After a few problems like for example the line stroke not closing with closePathStroke(), I saw that the canvas stroke lines method used for the header cells is different from the SolidBorders used for the other cells.

The borders created using a PdfCanvas gray out to the edges of the line, whereas the standard borders go directly from black to white. Clear, sharp edges is what I want on all of those lines.

Here a screenshot zoomed into the top right corner of my slightly modified version of this example (purposefully left in the not properly rendered state to clarify my point).


问:
Android shell svc data enable working on one phone and not on another one
I'm trying to figure out why an adb shell command is working on one phone and not on a different one.
This is running on a Samsung Galaxy 10

C:\Users\ivan>adb shell

beyond0:/ $ svc data disable

beyond0:/ $ svc data enable

beyond0:/ $ exit

No errors and commands are correctly executed.

On a Samsung Galaxy J3 this is what happens:

C:\Users\ivan>adb shell

shell@j3xnlte:/ $ svc data disable

sh: resetreason: can't execute: Permission denied

Killed

The error tells me a permissions problem... but both phones are not rooted. Commands are executed from the same pc.


问:
How can i get my output to convert as dictionary/json object?
I am working with an API and everything "works" but it comes back as the following

```<code>    with requests.Session() as s:

        resp = s.post(url, json={"user": "s153152","password": "password123"}, headers=headers, verify=False)
        print(resp.status_code)

        timestamp = None
        deleteData = False
        fields = None

        resp2 = s.post(url2, json={
            "timestamp" : timestamp,
            "deleteData" : deleteData,
            "fields":fields}, headers=headers2, verify=False, timeout=45)

        resp2 = resp2.text
        print(type(resp2))
        for data in resp['hostName']:
            print(data)

</code>```

resp2 is a string, it is possible to convert the output to a dictionary?

Expection: Json output so that i can call each individual value from key/pair

When i try the following i am getting jsondecode error:

```<code>resp3 = resp2.text
data = json.loads(resp3)
print(data)
print(type(resp2))
for i in data['hostName']:
    print(i)
</code>```

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Expected data to be returned, however the format of the variable is a string

[")]}',", '    {
"newestTimestamp": "2016-08-29T13:43:59.0000001",
"data": [
{
"hostName": "MULBERRY",
"ipAddresses": [
"192.168.146.131"
],
"locationsWithMatches": "538",
"locationsWithUnprotectedMatches": "93",
"totalMatches": "9706",
"totalUnprotectedMatches": "1319",
"lastSearchTime": "2015-08-11T18:59:45.927",
"id": -2147479361,
"changedTimestamp": "2015-08-11T18:59:45.927",
"dataTypes": [
{
"count": 914,
"name": "Social Security Number"
},
{
"count": 1237,
"name": "Credit Card Number"
}
]
},
{
"hostName": "DYCKMAN",
"ipAddresses": [
"192.168.124.184"
],
"locationsWithMatches": "592",
"locationsWithUnprotectedMatches": "93",
"totalMatches": "11470",
"totalUnprotectedMatches": "1782",
"lastSearchTime": "2015-08-31T05:53:05.28",
"id": -2147479360,
"changedTimestamp": "2015-08-31T05:53:05.28",
"dataTypes": [
{
"count": 955,
"name": "Social Security Number"
},
{
"count": 555,
"name": "Credit Card Number"
},
"classifications": [
{
"count": 24,
"name": "Confidential"
},
{
"count": 12,
"name": "PII"
}
]
}]
}

Body:
I am working with an API and everything "works" but it comes back as the following

    with requests.Session() as s:

        resp = s.post(url, json={"user": "s153152","password": "password123"}, headers=headers, verify=False)
        print(resp.status_code)

        timestamp = None
        deleteData = False
        fields = None

        resp2 = s.post(url2, json={
            "timestamp" : timestamp,
            "deleteData" : deleteData,
            "fields":fields}, headers=headers2, verify=False, timeout=45)

        resp2 = resp2.text
        print(type(resp2))
        for data in resp['hostName']:
            print(data)

resp2 is a string, it is possible to convert the output to a dictionary?

Expection: Json output so that i can call each individual value from key/pair

When i try the following i am getting jsondecode error:

resp3 = resp2.text
data = json.loads(resp3)
print(data)
print(type(resp2))
for i in data['hostName']:
    print(i)

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Expected data to be returned, however the format of the variable is a string

[")]}',", '    {
"newestTimestamp": "2016-08-29T13:43:59.0000001",
"data": [
{
"hostName": "MULBERRY",
"ipAddresses": [
"192.168.146.131"
],
"locationsWithMatches": "538",
"locationsWithUnprotectedMatches": "93",
"totalMatches": "9706",
"totalUnprotectedMatches": "1319",
"lastSearchTime": "2015-08-11T18:59:45.927",
"id": -2147479361,
"changedTimestamp": "2015-08-11T18:59:45.927",
"dataTypes": [
{
"count": 914,
"name": "Social Security Number"
},
{
"count": 1237,
"name": "Credit Card Number"
}
]
},
{
"hostName": "DYCKMAN",
"ipAddresses": [
"192.168.124.184"
],
"locationsWithMatches": "592",
"locationsWithUnprotectedMatches": "93",
"totalMatches": "11470",
"totalUnprotectedMatches": "1782",
"lastSearchTime": "2015-08-31T05:53:05.28",
"id": -2147479360,
"changedTimestamp": "2015-08-31T05:53:05.28",
"dataTypes": [
{
"count": 955,
"name": "Social Security Number"
},
{
"count": 555,
"name": "Credit Card Number"
},
"classifications": [
{
"count": 24,
"name": "Confidential"
},
{
"count": 12,
"name": "PII"
}
]
}]
}


问:
memisc cases() says never satisfied for a test I know is satisfied
I'm using the package memisc to analyze some survey data. There was one set of questions which one group of respondents answered, and another set of questions that a non-overlapping group answered. In my example below, this means that some people answered whether they were an Apple or not, while others answered whether they were a Gala or a Mackintosh or some other specific variety (Other.Text). (The values are 1 or 2 for Apple and 2 or 3 for Gala and Mackintosh instead of proper dummy variable, sorry.)  I need to create a new variable (IsApple) that consolidates them, with a value for all rows. I tried to do it using the memisc function cases(), but it tells me that the "no" condition is never satisfied, even though there are cases that fulfills it.

I tried this:

`

```<code>   library(memisc)
   data <- within(data,
    IsApple <- cases(
        "no" = 0 <- {
                    !(is.na(Apple) & is.na(Mackintosh)) &
                    !(Apple %in% 2 | Mackintosh %in% 3 | Gala %in% 3 | Other.Text %in% c(2, 7)) },
        "yes" = 1 <- Apple == 2 | Mackintosh == 3 | Gala == 3 | Other.Text %in% c(2, 7)
        ))
</code>```

`
I know that there is one case in the "no" condition, but it tells me that the "no" condition is never satisfied. The "yes" condition works. I have tested the boolean expression by using it in subset() and it gives the expected results. Here's the reproducible example:

`

```<code>    library(memisc)

    data <- data.set(
    Apple = c(1, 2, NA, NA, NA, NA, NA),
    Mackintosh = c(NA, NA, 2, 2, 3, 2, 3),
    Gala = c(NA, NA, 3, 2, 3, 3, 2),
    Other.Text = c(NA, NA, 1, 2, 1, 5, 7)
    )

    data <- within(data, {
    foreach(x=c(Apple, Mackintosh, Gala, Other.Text), {
        measurement(x) <- "nominal"
    })}
    )

    #the relevant boolean tests
    #not an apple:
    nrow(subset(data, !(is.na(Apple) & is.na(Mackintosh)) & !(Apple %in% 2 | Mackintosh %in% 3 | Gala %in% 3 | Other.Text %in% c(2, 7))   ))   #1, as expected

    #is an apple:
    nrow(subset(data, Apple == 2 | Mackintosh == 3 | Gala == 3 | Other.Text %in% c(2, 7)))  #6

    #since the tests seem to work, let's try recoding with cases

    data <- within(data,
    IsApple <- cases(
        "no" = 0 <- {
        !(is.na(Apple) & is.na(Mackintosh)) &
        !(Apple %in% 2 | Mackintosh %in% 3 | Gala %in% 3 | Other.Text %in% c(2, 7))},
        "yes" = 1 <- Apple == 2 | Mackintosh == 3 | Gala == 3 | Other.Text %in% c(2, 7)
        ))
    #error message saying the first condition is never fulfulled

    codebook(data$IsApple)  #indeed, nothing got coded at "no".

</code>```

`

I would like to know why the test is not working in cases() when I seem to have the boolean expression right, as shown by subset(). In the meantime I'll work on doing it another way. I really hope I'm missing something simple.  Please let me know if I need to provide data in another format, but I'm not sure how dput works.  Thanks in advance for your help!

```<code></code>```

Body:
I'm using the package memisc to analyze some survey data. There was one set of questions which one group of respondents answered, and another set of questions that a non-overlapping group answered. In my example below, this means that some people answered whether they were an Apple or not, while others answered whether they were a Gala or a Mackintosh or some other specific variety (Other.Text). (The values are 1 or 2 for Apple and 2 or 3 for Gala and Mackintosh instead of proper dummy variable, sorry.)  I need to create a new variable (IsApple) that consolidates them, with a value for all rows. I tried to do it using the memisc function cases(), but it tells me that the "no" condition is never satisfied, even though there are cases that fulfills it.

I tried this:

`

   library(memisc)
   data <- within(data,
    IsApple <- cases(
        "no" = 0 <- {
                    !(is.na(Apple) & is.na(Mackintosh)) &
                    !(Apple %in% 2 | Mackintosh %in% 3 | Gala %in% 3 | Other.Text %in% c(2, 7)) },
        "yes" = 1 <- Apple == 2 | Mackintosh == 3 | Gala == 3 | Other.Text %in% c(2, 7)
        ))

`
I know that there is one case in the "no" condition, but it tells me that the "no" condition is never satisfied. The "yes" condition works. I have tested the boolean expression by using it in subset() and it gives the expected results. Here's the reproducible example:

`

    library(memisc)

    data <- data.set(
    Apple = c(1, 2, NA, NA, NA, NA, NA),
    Mackintosh = c(NA, NA, 2, 2, 3, 2, 3),
    Gala = c(NA, NA, 3, 2, 3, 3, 2),
    Other.Text = c(NA, NA, 1, 2, 1, 5, 7)
    )

    data <- within(data, {
    foreach(x=c(Apple, Mackintosh, Gala, Other.Text), {
        measurement(x) <- "nominal"
    })}
    )

    #the relevant boolean tests
    #not an apple:
    nrow(subset(data, !(is.na(Apple) & is.na(Mackintosh)) & !(Apple %in% 2 | Mackintosh %in% 3 | Gala %in% 3 | Other.Text %in% c(2, 7))   ))   #1, as expected

    #is an apple:
    nrow(subset(data, Apple == 2 | Mackintosh == 3 | Gala == 3 | Other.Text %in% c(2, 7)))  #6

    #since the tests seem to work, let's try recoding with cases

    data <- within(data,
    IsApple <- cases(
        "no" = 0 <- {
        !(is.na(Apple) & is.na(Mackintosh)) &
        !(Apple %in% 2 | Mackintosh %in% 3 | Gala %in% 3 | Other.Text %in% c(2, 7))},
        "yes" = 1 <- Apple == 2 | Mackintosh == 3 | Gala == 3 | Other.Text %in% c(2, 7)
        ))
    #error message saying the first condition is never fulfulled

    codebook(data$IsApple)  #indeed, nothing got coded at "no".

`

I would like to know why the test is not working in cases() when I seem to have the boolean expression right, as shown by subset(). In the meantime I'll work on doing it another way. I really hope I'm missing something simple.  Please let me know if I need to provide data in another format, but I'm not sure how dput works.  Thanks in advance for your help!


问:
stateNotFound returned when I fire $state.go from an iframe and inside a promise child to parent
State UI router is not working inside a promise and after being triggered from an iframe .

```<code>     //https://www.codeproject.com/Tips/585663/Communication-with-Cross-Domain-IFrame-A-Cross-Bro
  // Here "addEventListener" is for standards-compliant web browsers and "attachEvent" is for IE Browsers.
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];
  // "attachEvent"for "onmessage" as the event ,"addEventListener" for "message" as the event
  var messageEvent = eventMethod === "attachEvent" ? "onmessage" : "message";
  // Listen to message from child IFrame window
  eventer(messageEvent, function(e) {
    // dont show docusign iframe now,
    // since in all the below cases we dont want to show the iframe
    //Check only the events from docusign
    if (_.contains(['signing_complete', 'cancel'], e.data)) {
      switch (e.data) {
        case 'signing_complete':
    RestService.putResource(apiProperties.appsUrl + context.outputs.appId + '/environment', data).then(function(result) {
      if (result) {
        $scope.context.outputs.docusignMessage = 'Document signed successfully.';
        MessageFactory.addConfirmation("Your application was moved to production successfully.");
          $state.go('customer-ss-workspace-app-details', { id: context.outputs.appId, userId: context.outputs.userId }, { reload: true });
      }

    }, function() {
      $state.go('customer-ss-workspace-app-details', { id: context.outputs.appId, userId: context.outputs.userId });
    }) default:
          NavigationService.clearLoadingOverlay(); }, false);

</code>```

it is a hybrid angularJs/Angular App thats why routes are looking like this. NB the direction is happening from a child to a parent.

```<code>export const appDetailsRoute: RouteDefinition = {
name: 'customer-ss-workspace-app-details',
url: '/my-apps/{id}?{userId}',
parent: 'site',
component: AppDetailsComponent,
ncyBreadcrumb: {
    parent: 'my-apps',
    label: '{{layoutData.breadCrumbName}}'
}};

export const moveToProdFollowingAppsRoute: RouteDefinition = {
 name: 'customer-self-service-workspace-my-apps-move-following-apps-to-production',
  url: '/my-apps/{id}/move-following-apps-to-production?{userId}',
  parent: 'site',
  ncyBreadcrumb: {
    parent: 'customer-ss-workspace-app-details',
    label: 'Request production environment'
  },
  component: MoveToProdFollowingAppsComponent,
  resolve: [{
    token: 'validationApis',
    deps: [RestrictedApiService, ApiService],
    resolveFn: MoveToProductionService.getRestrictedAPIsResolver
  }]
}
</code>```

returned message is state not found (used this reference for debug https://gist.github.com/hmbilal/b7a74eadf01586c702cd )

The same portion of code of redirection is working fine outside of this scenario.
everything else is working fine, scope values are detected fine.
no angularjs or javascript error are displayed.

Body:
State UI router is not working inside a promise and after being triggered from an iframe .

     //https://www.codeproject.com/Tips/585663/Communication-with-Cross-Domain-IFrame-A-Cross-Bro
  // Here "addEventListener" is for standards-compliant web browsers and "attachEvent" is for IE Browsers.
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];
  // "attachEvent"for "onmessage" as the event ,"addEventListener" for "message" as the event
  var messageEvent = eventMethod === "attachEvent" ? "onmessage" : "message";
  // Listen to message from child IFrame window
  eventer(messageEvent, function(e) {
    // dont show docusign iframe now,
    // since in all the below cases we dont want to show the iframe
    //Check only the events from docusign
    if (_.contains(['signing_complete', 'cancel'], e.data)) {
      switch (e.data) {
        case 'signing_complete':
    RestService.putResource(apiProperties.appsUrl + context.outputs.appId + '/environment', data).then(function(result) {
      if (result) {
        $scope.context.outputs.docusignMessage = 'Document signed successfully.';
        MessageFactory.addConfirmation("Your application was moved to production successfully.");
          $state.go('customer-ss-workspace-app-details', { id: context.outputs.appId, userId: context.outputs.userId }, { reload: true });
      }

    }, function() {
      $state.go('customer-ss-workspace-app-details', { id: context.outputs.appId, userId: context.outputs.userId });
    }) default:
          NavigationService.clearLoadingOverlay(); }, false);

it is a hybrid angularJs/Angular App thats why routes are looking like this. NB the direction is happening from a child to a parent.

export const appDetailsRoute: RouteDefinition = {
name: 'customer-ss-workspace-app-details',
url: '/my-apps/{id}?{userId}',
parent: 'site',
component: AppDetailsComponent,
ncyBreadcrumb: {
    parent: 'my-apps',
    label: '{{layoutData.breadCrumbName}}'
}};

export const moveToProdFollowingAppsRoute: RouteDefinition = {
 name: 'customer-self-service-workspace-my-apps-move-following-apps-to-production',
  url: '/my-apps/{id}/move-following-apps-to-production?{userId}',
  parent: 'site',
  ncyBreadcrumb: {
    parent: 'customer-ss-workspace-app-details',
    label: 'Request production environment'
  },
  component: MoveToProdFollowingAppsComponent,
  resolve: [{
    token: 'validationApis',
    deps: [RestrictedApiService, ApiService],
    resolveFn: MoveToProductionService.getRestrictedAPIsResolver
  }]
}

returned message is state not found (used this reference for debug https://gist.github.com/hmbilal/b7a74eadf01586c702cd )

The same portion of code of redirection is working fine outside of this scenario.
everything else is working fine, scope values are detected fine.
no angularjs or javascript error are displayed.