问:
Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'
I am using Laravel to connect to MySQL database and got this exception:

```<code>PDOException
SQLSTATE[HY000] [1049] Unknown database 'forge'
</code>```

and this is my config.database.php

```<code>'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'laravel',
            'username'  => 'Anastasie',
            'password'  => 'A@Laurent',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
</code>```

why is the error referring to PDO database? and why the forge database name? I have already changed it.

Should I do anything to tell Laravel that I am using MySQL database?

Update 1

I found this line
`protected $table = 'users';`
in my user.php file and I have changed it to
`protected $table = 'user';` because the table in my database is `user` not `users`

Update 2

I wrote this in my Route
```<code>Route::resource('users', 'UsersController');
</code>```

and I added UsersController.php in my controllers folder

and inside UsersController.php I have this:

```<code>class UsersController extends BaseController {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $users = User::all();
        return View::make('users.index', compact('users'));
    }
</code>```

and I call this url http://localhost:8082/laravel/public/users/

I am using Windows 7 with Laravel 4.2

答:
Here is my response to the problem described in the question.

in cmd write:

```<code>php artisan cache:clear
</code>```

then try to do this code in your terminal

```<code>php artisan serve
</code>```

note:
this will start again the server

Body:
I am using Laravel to connect to MySQL database and got this exception:

PDOException
SQLSTATE[HY000] [1049] Unknown database 'forge'

and this is my config.database.php

'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'laravel',
            'username'  => 'Anastasie',
            'password'  => 'A@Laurent',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

why is the error referring to PDO database? and why the forge database name? I have already changed it.

Should I do anything to tell Laravel that I am using MySQL database?

Update 1

I found this line
`protected $table = 'users';`
in my user.php file and I have changed it to
`protected $table = 'user';` because the table in my database is `user` not `users`

Update 2

I wrote this in my Route

Route::resource('users', 'UsersController');

and I added UsersController.php in my controllers folder

and inside UsersController.php I have this:

class UsersController extends BaseController {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $users = User::all();
        return View::make('users.index', compact('users'));
    }

and I call this url http://localhost:8082/laravel/public/users/

I am using Windows 7 with Laravel 4.2

Body:
Here is my response to the problem described in the question.

in cmd write:

php artisan cache:clear

then try to do this code in your terminal

php artisan serve

note:
this will start again the server


来源: stackexchange

问:
1 customer login for 2 web applications with individual login authentication and databases, possibly more
How to make 2 separate back end apps served as one site, each handling different requests, ideally 1 embedded into the other, sharing a session once user is logged in?

Currently there is one bespoke website/CMS application (app 1) not unlike a blog with a login form and signup. It uses oauth internally to connect to an API for the database on a seperate app. Blog posts are public on the website, customers login to the main site and can upload posts and see their editorial progress, receive feedback and more before the post can be made live, and Admin use a CMS to access what is submitted by customers and manage the posts including proxying in to users as needed to make changes.

I now have another web application (app 2) to replace some of the functionality in the original CMS. It has its own CMS and frontend, login, and users stored in its database.

I need a way to integrate the two of them so that customers login to app 1 and when they navigate to their post creating/editing they are seamlessly using app 2, no additional login, all using the original apps user auth. Admin can visit both apps CMS, ideally also with a single login.

My first thought was I need another app/service to manage authentication and act as a gateway to the other apps serving pages?

I see a lot about Single Sign On but it seems to relate more to using an external account to access my site "login with Facebook".

What pattern for the infrastructure and code would be applicable in this instance? All apps are built on PHP, hosted on Linux.

答:
Single Sign-On (SSO) is what you want, you're on the right track. Read up on protocols such as SAML or OpenID Connect, pick one that you feel comfortable with and has support in your toolset, implement a small test case and go from there. SAML with PHP has a really nice toolkit: simpleSAMLphp

With SAML, you have an identity provider service that authenticates users via, say, a login form and a backend user database and one or more service providers. Each service provider is an app that enjoys the benefits of SSO. The identity provider could be implemented as a stand-alone app/service or it can be embedded into one of your apps, likely app 1. App 2 will be a service provider. Assuming you'll have implemented all of this correctly, your users will be able to click on a link in app 1 that lands them in app 2 without re-authentication.

ContentLicense: CC BY-SA 4.0


问:
Return Promise after job execution in Node.js
I´m creating a small Node.js application for some monitoring stuff. The following operation has to be made with this app:

A job scheduler (using node-schedule module) is retrieving data from a web service within a time period and inserting the content into an array (for further processing). After finishing the job a promise should resolve the complete array in order to use it in my main program.

Here is my coding so far. With this coding the promise gets resolved before finishing the job and the array is empty. Can you give me any hints how to solve this?

```<code>async function dataRetrieval(start, end, rule){
   let array = [];
   return new Promise(function (resolve) {
       schedule.scheduleJob({start: start, end: end, rule: rule}, async function (){
           let data = await service.getData();
           array.push(data);
       });
       resolve(array);
   });
}
</code>```

答:
The problem is that you are resolving it outside the callback completion. You need to resolve it inside the callback.

Something like this

```<code>async function dataRetrieval(start, end, rule){
    let array = [];
    return new Promise(function (resolve) {
        schedule.scheduleJob({start: start, end: end, rule: rule}, async function (){
            let data = await service.getData();
            array.push(data);
            resolve(array);
        });
    });
 }
</code>```

Body:
I´m creating a small Node.js application for some monitoring stuff. The following operation has to be made with this app:

A job scheduler (using node-schedule module) is retrieving data from a web service within a time period and inserting the content into an array (for further processing). After finishing the job a promise should resolve the complete array in order to use it in my main program.

Here is my coding so far. With this coding the promise gets resolved before finishing the job and the array is empty. Can you give me any hints how to solve this?

async function dataRetrieval(start, end, rule){
   let array = [];
   return new Promise(function (resolve) {
       schedule.scheduleJob({start: start, end: end, rule: rule}, async function (){
           let data = await service.getData();
           array.push(data);
       });
       resolve(array);
   });
}

Body:
The problem is that you are resolving it outside the callback completion. You need to resolve it inside the callback.

Something like this

async function dataRetrieval(start, end, rule){
    let array = [];
    return new Promise(function (resolve) {
        schedule.scheduleJob({start: start, end: end, rule: rule}, async function (){
            let data = await service.getData();
            array.push(data);
            resolve(array);
        });
    });
 }


问:
unresolved external symbol _MsiLocateComponentW@12
I know that simply posting code and asking for a solution isn't a good idea, but I have no idea what's causing this.

I'm trying to find the installation path of PowerPoint based on this code, however, the compiler gives this error:

```<code>error LNK2019: unresolved external symbol _MsiLocateComponentW@12 referenced in function _WinMain@16
</code>```

I'm using Visual Studio 2019 and IntelliSense doesn't notice the error, only the compiler. Here's the code:

#include <Windows.h>
#include <msi.h>

int APIENTRY WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nShowCmd) {
    LPCWSTR PowerPoint = L"{CC29E94B-7BC2-11D1-A921-00A0C91E2AA2}";

    DWORD size = 300;
    INSTALLSTATE installstate;
    LPWSTR sPath;

    sPath = new wchar_t[size];
    installstate = MsiLocateComponent(PowerPoint, sPath, &size);

    if (installstate == INSTALLSTATE_LOCAL || installstate == INSTALLSTATE_SOURCE)
        MessageBox(NULL, sPath, L"PowerPoint path", MB_OK | MB_ICONASTERISK );
    delete[] sPath;
    return 0;
}
```

As you can see, I included the msi.h header. What's wrong with my code?

答:
You are getting a linker error, not a compiler error.

Make sure your project is linking to msi.lib. Using msi.h is not enough by itself.

msi.h tells the compiler what the function LOOKS LIKE so that your code can make calls to it.

But you also need to tell the linker WHERE the function is actually located. msi.lib tells the linker that the function is exported from msi.dll, so then the linker can link your function call to that DLL.

To link to msi.lib, you can either specify msi.lib as an "Additional Dependency" for Linker Input in your project options, or you can use a #pragma comment(lib, "msi.lib") statement directly in your code.

Body:
I know that simply posting code and asking for a solution isn't a good idea, but I have no idea what's causing this.

I'm trying to find the installation path of PowerPoint based on this code, however, the compiler gives this error:

error LNK2019: unresolved external symbol _MsiLocateComponentW@12 referenced in function _WinMain@16

I'm using Visual Studio 2019 and IntelliSense doesn't notice the error, only the compiler. Here's the code:

#include <Windows.h>
#include <msi.h>

int APIENTRY WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nShowCmd) {
    LPCWSTR PowerPoint = L"{CC29E94B-7BC2-11D1-A921-00A0C91E2AA2}";

    DWORD size = 300;
    INSTALLSTATE installstate;
    LPWSTR sPath;

    sPath = new wchar_t[size];
    installstate = MsiLocateComponent(PowerPoint, sPath, &size);

    if (installstate == INSTALLSTATE_LOCAL || installstate == INSTALLSTATE_SOURCE)
        MessageBox(NULL, sPath, L"PowerPoint path", MB_OK | MB_ICONASTERISK );
    delete[] sPath;
    return 0;
}

As you can see, I included the msi.h header. What's wrong with my code?


问:
Excluding intervals from a real number line
A long time ago I asked the following question:

Python: delete substring by indices

Last week I was asked a very similar question, but with continuous real-number line.

Imagine you are given an interval (X, Y), and a bunch of sub-intervals blocks=[(x1, y1), (x2, y2), ...]. Your goal is to find a list of intervals remaining=[(a1, b1), (a2, b2), ..] that is (1) in (X, Y), but (2) not in any of the sub-intervals in blocks. The intervals in blocks can overlap.

In other words, the function signature looks something like:

```<code>def delete_blocks_from_interval(X, Y, blocks):
    ```
    X: start of the given interval
    Y: end of the given interval
    blocks: list of intervals (x, y) to be removed, can overlap

    returns remaining = [(a, b), ...] intervals remaining after removal of blocks
    ```
    pass
</code>```

I can construct a graph of connected intervals in blocks, and find both the minimum of the start and the maximum of end for each connected component in the graph. But this is quadratic in length of blocks. I wonder if there is a better-runtime algorithm.

Please also discuss what code routine you think is more efficient for the algorithm if you will.

Many many thanks.

As requested, please consider the following illustrative inputs:

X = -1

Y = 20

blocks = [(1, 10), (4, 5), (9, 11), (16, 17.5)]

the expected output is remaining = [(-1, 1), (11, 16), (17.5, 20)]

答:
python-ranges is a library I wrote that excels at this particular use case. It isn't the most efficient code you could possibly write (it essentially uses @wwii's algorithm below, in fact) but it is nice and terse.

```<code>from ranges import Range, RangeSet

...

def delete_blocks_from_interval(X, Y, blocks):
    # make a Range
    orig = Range(X, Y)
    # make a RangeSet out of the 2-tuple blocks
    #   (using the unpacking operator to interpret 2-tuples as positional args for Range())
    # and then find the difference from the original set
    #   (like with sets, the - operator is a shorthand for .difference())
    remaining = orig - RangeSet(
        Range(*block) for block in blocks
    )
    # return each range in the RangeSet as a tuple
    return [(rng.start, rng.end) for rng in remaining.ranges()]

</code>```

Body:
A long time ago I asked the following question:

Python: delete substring by indices

Last week I was asked a very similar question, but with continuous real-number line.

Imagine you are given an interval (X, Y), and a bunch of sub-intervals blocks=[(x1, y1), (x2, y2), ...]. Your goal is to find a list of intervals remaining=[(a1, b1), (a2, b2), ..] that is (1) in (X, Y), but (2) not in any of the sub-intervals in blocks. The intervals in blocks can overlap.

In other words, the function signature looks something like:

def delete_blocks_from_interval(X, Y, blocks):
    ```
    X: start of the given interval
    Y: end of the given interval
    blocks: list of intervals (x, y) to be removed, can overlap

    returns remaining = [(a, b), ...] intervals remaining after removal of blocks
    ```
    pass

I can construct a graph of connected intervals in blocks, and find both the minimum of the start and the maximum of end for each connected component in the graph. But this is quadratic in length of blocks. I wonder if there is a better-runtime algorithm.

Please also discuss what code routine you think is more efficient for the algorithm if you will.

Many many thanks.

As requested, please consider the following illustrative inputs:

X = -1

Y = 20

blocks = [(1, 10), (4, 5), (9, 11), (16, 17.5)]

the expected output is remaining = [(-1, 1), (11, 16), (17.5, 20)]

Body:
python-ranges is a library I wrote that excels at this particular use case. It isn't the most efficient code you could possibly write (it essentially uses @wwii's algorithm below, in fact) but it is nice and terse.

from ranges import Range, RangeSet

...

def delete_blocks_from_interval(X, Y, blocks):
    # make a Range
    orig = Range(X, Y)
    # make a RangeSet out of the 2-tuple blocks
    #   (using the unpacking operator to interpret 2-tuples as positional args for Range())
    # and then find the difference from the original set
    #   (like with sets, the - operator is a shorthand for .difference())
    remaining = orig - RangeSet(
        Range(*block) for block in blocks
    )
    # return each range in the RangeSet as a tuple
    return [(rng.start, rng.end) for rng in remaining.ranges()]


问:
Rename dataframe in Python for loop
I am trying to rename a dataframe in each iteration of my for loop. For column "item" in the "data" dataframe, I would like to generate dataframes up to the number of unique items in "item" column.</p>

```<code>for item in data.item.unique():
    data+"item" = data[data["item"] == item]
</code>```

答:
IIUC, you can just use groupby:

```<code>frames = {k:d for k,d in data.groupby('item')}
</code>```

Title: Rename dataframe in Python for loop

Body:
I am trying to rename a dataframe in each iteration of my for loop. For column "item" in the "data" dataframe, I would like to generate dataframes up to the number of unique items in "item" column.

for item in data.item.unique():
    data+"item" = data[data["item"] == item]

Body:
IIUC, you can just use groupby:

frames = {k:d for k,d in data.groupby('item')}


问:
Reversing a given array and adding to it to given array using python
Given an array A of N numbers, you have to write a program which prints the sum of the elements of array A with the corresponding elements of the reverse of array A.
If array A has elements [1,2,3], then reverse of the array A will be [3,2,1] and the resultant array should be [4,4,4].

Input Format:

The first line of the input contains a number N representing the number of elements in array A.
The second line of the input contains N numbers separated by a space. (after the last elements, there is no space)

Output Format:

Print the resultant array elements separated by a space. (no space after the last element)

Example:

Input:

```<code>4
2 5 3 1
</code>```

Output:

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

答:
```<code>n = int(input())

list1 = list(map(int, input().strip().split()))[:n]

list2 = list1[::-1]

sum_list = []

for (item1, item2) in zip(list1, list2):

    sum_list.append(item1+item2)

print(*sum_list, sep=' ')
</code>```

Body:
Given an array A of N numbers, you have to write a program which prints the sum of the elements of array A with the corresponding elements of the reverse of array A.
If array A has elements [1,2,3], then reverse of the array A will be [3,2,1] and the resultant array should be [4,4,4].

Input Format:

The first line of the input contains a number N representing the number of elements in array A.
The second line of the input contains N numbers separated by a space. (after the last elements, there is no space)

Output Format:

Print the resultant array elements separated by a space. (no space after the last element)

Example:

Input:

4
2 5 3 1

Output:

3883


问:
java install tomcat as service
I'm planning to develop an application installer which, as a part of installation, installs Apache Tomcat on Linux. Does anyone know how can I programmatically install Tomcat as service on Linux.
Best</p>

答:
If you have Tomcat installed already, you probably need to put a start up script for Tomcat in /etc/init.d

This article has a decent start up script.

http://www.howtogeek.com/howto/linux/installing-tomcat-6-on-ubuntu/

ContentLicense: CC BY-SA 3.0

Title: java install tomcat as service


答:
My advice is use dictionaries.

Your answer is this:

```<code>for i in data.item.unique():
    globals()[f'data{i}'] = data[data["item"] == i]
</code>```

Title: Rename dataframe in Python for loop

Body:
My advice is use dictionaries.

Your answer is this:

for i in data.item.unique():
    globals()[f'data{i}'] = data[data["item"] == i]


问:
Smooth movement in processing?
I want this code to effectively increase the smoothness of the transition between directions (it only works with one key at a time) so that I can use multiple keys. The problem is that whenever I change direction the "Player" stops and then continues in the new direction. I want the "Player" to smoothly transition between directions without having to fully release the active key before pressing the new one.

Main code:

```<code>Ball ball;
Player player1;
Player player2;

void setup() {

  size(1368,768);
  frameRate(60);
  noStroke();

  ball = new Ball(width/2, height/2, 30);
  player1 = new Player(0, height/2, 30, 150);
  player2 = new Player(width-30, height/2, 30, 150);

  ball.speedX = -10;
  ball.speedY = random(-5,5);

}

void draw() {

  background(0);

  ball.display();
  ball.move();
  player1.run();
  player2.run();

  //Collision
  if (ball.top() < 0) {
    ball.speedY = -ball.speedY;
  }

  if (ball.bottom() > height) {
    ball.speedY = -ball.speedY;
  }

  if (ball.left() < 0) {
    ball.speedX = 0;
    ball.speedY = 0;
  }

  if (ball.right() > width) {
    ball.speedX = 0;
    ball.speedY = 0;
  }

}

void keyPressed() {

  player1.pressed((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
  player2.pressed((keyCode == UP), (keyCode == DOWN));

}

void keyReleased() {

  player1.released((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
  player2.released((keyCode == UP), (keyCode == DOWN));

}
</code>```

Player class code:

```<code>class Player {

  float x, y;
  int dy = 0;
  float w, h;
  float speedY = 5;
  color c;

  //Constructor
  Player(float tempX, float tempY, float tempW, float tempH){

    x = tempX;
    y = tempY;
    w = tempW;
    h = tempH;
    speedY = 0;
    c = (255);

  }

  void run() {

    display();
    move();

  }

  void display() {

    fill(c);
    rect(x, y-h/2, w, h);

  }

  void move() {

    y += dy * speedY;

  }

  void pressed(boolean up, boolean down) {

    if (up) {dy = -1;}
    if (down) {dy = 1;}

  }

  void released(boolean up, boolean down) {

    if (up) {dy = 0;}
    if (down) {dy = 0;}

  }

}
</code>```

Thanks in advance!

答:
If you want smooth transitions, you're going to have to give up "adding a fixed integer distance" in the key handlers, and instead track which keys are down or not, and then accelerating/decelerating your player every time draw() runs. As simple illustration:

Box box;
boolean[] active = new boolean[256];

void setup() {
  size(500,500);
  box = new Box(width/2, height/2);
}

void draw() {
  pushStyle();
  background(0);
  box.update(active);  // First, make the box update its velocity,
  box.draw();          // then, tell the box to draw itself.
  popStyle();
}

void keyPressed() { active[keyCode] = true; }
void keyReleased() { active[keyCode] = false; }
```

<p>With a simple box class:</p>

<pre class="lang-java prettyprint-override"><code>class Box {
  final float MAX_SPEED = 1, ACCELERATION = 0.1, DECELERATION = 0.5;
  float x, y;
  float dx=0, dy=0;

  Box(float _x, float _y) { x=_x; y=_y; }

  void draw() {
    // We first update our position, based on current speed,
    x += dx;
    y += dy;
    // and then we draw ourselves.
    noStroke();
    fill(255);
    rect(x,y,30,30);
  }

  void update(boolean[] keys) {
    if (keys[38]) { dy -= ACCELERATION ; }
    else if (keys[40]) { dy += ACCELERATION ; }
    else { dy *= DECELERATION; }

    if (keys[37]) { dx -= ACCELERATION ; }
    else if (keys[39]) { dx += ACCELERATION ; }
    else { dx *= DECELERATION; }

    dx = constrain(dx, -MAX_SPEED, MAX_SPEED);
    dy = constrain(dy, -MAX_SPEED, MAX_SPEED);
  }
}
</code>```

The important part here is the update code, which updates the box's x and y velocity such that if a directional key is currently pressed, we increase the speeed (dx/dy) in that direction. Importantly, if no keys are pressed we also dampen the speed to that it returns to 0.

Finally, to make sure we don't end up with infinite speed, we cap the maximum allowed velocity.

Title: Smooth movement in processing?

Body:
I want this code to effectively increase the smoothness of the transition between directions (it only works with one key at a time) so that I can use multiple keys. The problem is that whenever I change direction the "Player" stops and then continues in the new direction. I want the "Player" to smoothly transition between directions without having to fully release the active key before pressing the new one.

Main code:

Ball ball;
Player player1;
Player player2;

void setup() {

  size(1368,768);
  frameRate(60);
  noStroke();

  ball = new Ball(width/2, height/2, 30);
  player1 = new Player(0, height/2, 30, 150);
  player2 = new Player(width-30, height/2, 30, 150);

  ball.speedX = -10;
  ball.speedY = random(-5,5);

}

void draw() {

  background(0);

  ball.display();
  ball.move();
  player1.run();
  player2.run();

  //Collision
  if (ball.top() < 0) {
    ball.speedY = -ball.speedY;
  }

  if (ball.bottom() > height) {
    ball.speedY = -ball.speedY;
  }

  if (ball.left() < 0) {
    ball.speedX = 0;
    ball.speedY = 0;
  }

  if (ball.right() > width) {
    ball.speedX = 0;
    ball.speedY = 0;
  }

}

void keyPressed() {

  player1.pressed((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
  player2.pressed((keyCode == UP), (keyCode == DOWN));

}

void keyReleased() {

  player1.released((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
  player2.released((keyCode == UP), (keyCode == DOWN));

}

Player class code:

class Player {

  float x, y;
  int dy = 0;
  float w, h;
  float speedY = 5;
  color c;

  //Constructor
  Player(float tempX, float tempY, float tempW, float tempH){

    x = tempX;
    y = tempY;
    w = tempW;
    h = tempH;
    speedY = 0;
    c = (255);

  }

  void run() {

    display();
    move();

  }

  void display() {

    fill(c);
    rect(x, y-h/2, w, h);

  }

  void move() {

    y += dy * speedY;

  }

  void pressed(boolean up, boolean down) {

    if (up) {dy = -1;}
    if (down) {dy = 1;}

  }

  void released(boolean up, boolean down) {

    if (up) {dy = 0;}
    if (down) {dy = 0;}

  }

}

Thanks in advance!

Body:
If you want smooth transitions, you're going to have to give up "adding a fixed integer distance" in the key handlers, and instead track which keys are down or not, and then accelerating/decelerating your player every time draw() runs. As simple illustration:

Box box;
boolean[] active = new boolean[256];

void setup() {
  size(500,500);
  box = new Box(width/2, height/2);
}

void draw() {
  pushStyle();
  background(0);
  box.update(active);  // First, make the box update its velocity,
  box.draw();          // then, tell the box to draw itself.
  popStyle();
}

void keyPressed() { active[keyCode] = true; }
void keyReleased() { active[keyCode] = false; }

With a simple box class:

class Box {
  final float MAX_SPEED = 1, ACCELERATION = 0.1, DECELERATION = 0.5;
  float x, y;
  float dx=0, dy=0;

  Box(float _x, float _y) { x=_x; y=_y; }

  void draw() {
    // We first update our position, based on current speed,
    x += dx;
    y += dy;
    // and then we draw ourselves.
    noStroke();
    fill(255);
    rect(x,y,30,30);
  }

  void update(boolean[] keys) {
    if (keys[38]) { dy -= ACCELERATION ; }
    else if (keys[40]) { dy += ACCELERATION ; }
    else { dy *= DECELERATION; }

    if (keys[37]) { dx -= ACCELERATION ; }
    else if (keys[39]) { dx += ACCELERATION ; }
    else { dx *= DECELERATION; }

    dx = constrain(dx, -MAX_SPEED, MAX_SPEED);
    dy = constrain(dy, -MAX_SPEED, MAX_SPEED);
  }
}

The important part here is the update code, which updates the box's x and y velocity such that if a directional key is currently pressed, we increase the speeed (dx/dy) in that direction. Importantly, if no keys are pressed we also dampen the speed to that it returns to 0.

Finally, to make sure we don't end up with infinite speed, we cap the maximum allowed velocity.


问:
How to share received data from socket in fragments?
I open a Bluetooth socket in my main activity and receive information from other device.

As i show in image below i have two fragment in my activity.

How can i use information which receive from socket Bluetooth in both fragments .
note : fragment can change and in general i searching for proper way to share received data. I receive data with handler as below:

```<code>private final Handler handler = new Handler() {
    @Override
    public void handleMessage(@NonNull Message msg) {
        switch (msg.what) {
            case BluetoothChatService.MessageConstants.MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                String writeMessage = new String(writeBuf);
                break;
            case BluetoothChatService.MessageConstants.MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                String readMessage = new String(readBuf, 0, msg.arg1);
                break;
            case BluetoothChatService.MessageConstants.MESSAGE_DEVICE_NAME:
                connectedDeviceName = msg.getData().getString(BluetoothChatService.MessageConstants.DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                        + connectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case BluetoothChatService.MessageConstants.MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(),
                        msg.getData().getString(BluetoothChatService.MessageConstants.TOAST),
                        Toast.LENGTH_SHORT).show();
                break;
        }
        super.handleMessage(msg);
    }
};
</code>```

答: You can use offline Databases such as Room . ( do not forget to execute your queries in the background thread. use executors and thread-pools). in addition to this, you also can use intents to transfer data between some fragments. finally, I think the best way to share data between fragments(or generally, modules) is to use an architecture having a shared repository such as MVVM, MVC etc. they both use offline DB as repositories.</p>

Body:
I open a Bluetooth socket in my main activity and receive information from other device.

As i show in image below i have two fragment in my activity.

How can i use information which receive from socket Bluetooth in both fragments .
note : fragment can change and in general i searching for proper way to share received data. I receive data with handler as below:

private final Handler handler = new Handler() {
    @Override
    public void handleMessage(@NonNull Message msg) {
        switch (msg.what) {
            case BluetoothChatService.MessageConstants.MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                String writeMessage = new String(writeBuf);
                break;
            case BluetoothChatService.MessageConstants.MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                String readMessage = new String(readBuf, 0, msg.arg1);
                break;
            case BluetoothChatService.MessageConstants.MESSAGE_DEVICE_NAME:
                connectedDeviceName = msg.getData().getString(BluetoothChatService.MessageConstants.DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                        + connectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case BluetoothChatService.MessageConstants.MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(),
                        msg.getData().getString(BluetoothChatService.MessageConstants.TOAST),
                        Toast.LENGTH_SHORT).show();
                break;
        }
        super.handleMessage(msg);
    }
};


问:
RabbitMQ File Size-based Log Rotation Default Size
I'm new to RabbitMQ and I have an application that uses RabbitMQ as the message broker. Up until this day, I've been using the default settings - no log rotation. I wanted to use the log rotation feature so I set it using:

```<code>{log, [
        {file, [{file, "MyAppLogs.log"},
                {level, info},
                {date, "$D0"},
                {size, 1073741824},
                {count, 30}
                ]}
    ]}
</code>```

Of course testing would take a while if I am to test 1GB file size, so for testing purposes I changed it to 1024 instead. I expected the log will rotate when it reaches 1KB but it did not. I've noticed that the log files would only rotate once the file size reaches 5KB.
So my question is - is the minimum log file size for RabbitMQ file-based log rotation 5KB?
I've looked around the web - especially in the rabbitmq documentation site: https://www.rabbitmq.com/logging.html - however there's no mention of any minimimum size.
Here is the sample output of my the settings that I've used:
Test Settings:

```<code>[{file, [{file, "rabbit.log"},
              {level, info},
              {date, "$D0"},
              {size, 1024},
              {count, 3}
             ]}
     ]}
</code>```

答:
https://groups.google.com/d/topic/rabbitmq-users/wJGMVGB1cAk/discussion

Hi Renya,

Please always let us know what version of RabbitMQ and Erlang you are using. I can tell you're using Windows - what version?

Log rotation is not necessarily precise due to when it happens in the logging process, as well as buffering.

Thanks -
Luke

NOTE: the RabbitMQ team monitors the rabbitmq-users mailing list and only sometimes answers questions on StackOverflow.

Body:
I'm new to RabbitMQ and I have an application that uses RabbitMQ as the message broker. Up until this day, I've been using the default settings - no log rotation. I wanted to use the log rotation feature so I set it using:

{log, [
        {file, [{file, "MyAppLogs.log"},
                {level, info},
                {date, "$D0"},
                {size, 1073741824},
                {count, 30}
                ]}
    ]}

Of course testing would take a while if I am to test 1GB file size, so for testing purposes I changed it to 1024 instead. I expected the log will rotate when it reaches 1KB but it did not. I've noticed that the log files would only rotate once the file size reaches 5KB.
So my question is - is the minimum log file size for RabbitMQ file-based log rotation 5KB?
I've looked around the web - especially in the rabbitmq documentation site: https://www.rabbitmq.com/logging.html - however there's no mention of any minimimum size.
Here is the sample output of my the settings that I've used:
Test Settings:

[{file, [{file, "rabbit.log"},
              {level, info},
              {date, "$D0"},
              {size, 1024},
              {count, 3}
             ]}
     ]}


答:
This is happening because scheduleJob is an asynchronous function, and your resolve call takes place outside of your callback, before the job is finished.

You can use the fireDate value that is passed to the callback from scheduleJob to check if the current execution is the last one. If so, only then, you call resolve with the final data from the callback:

```<code>async function dataRetrieval(start, end, rule){
   let array = [];
   return new Promise(function (resolve) {
       schedule.scheduleJob({start: start, end: end, rule: rule}, async function (fireDate) {
           let data = await service.getData();
           array.push(data);

           if (fireDate >= end) {
               resolve(array);
           }
       });
   });
}
</code>```

Title: Return Promise after job execution in Node.js

Body:
This is happening because scheduleJob is an asynchronous function, and your resolve call takes place outside of your callback, before the job is finished.

You can use the fireDate value that is passed to the callback from scheduleJob to check if the current execution is the last one. If so, only then, you call resolve with the final data from the callback:

async function dataRetrieval(start, end, rule){
   let array = [];
   return new Promise(function (resolve) {
       schedule.scheduleJob({start: start, end: end, rule: rule}, async function (fireDate) {
           let data = await service.getData();
           array.push(data);

           if (fireDate >= end) {
               resolve(array);
           }
       });
   });
}


问:
Organization Restrictions on Creating D365 Managed Solutions
I have been told that "to use managed solutions for deployment through Dynamics 365 requires the developing organization to be a certified ISV for Dynamics with Microsoft.  And furthermore, that a Managed Solution also goes through some sort of vetting process within Microsoft."

This sounds like some sort of misunderstanding to me.

From my understanding of the use cases for unmanaged and managed solutions, there is no such restriction on my creation of managed solutions.  All the documentation I have seen mentions the benefits of using managed solutions but does not go into any sort of detail about having to be a certified ISV or that the solution has to be vetted.

I am new to using D365 and am having a hard time determining if what I have been told has any truth to it.  My question is if anyone can clarify if there really is any sort of certification required by my company to use the concept of managed solutions?

答:
A small confusion.

Customizing & deploying as a Managed solution (part of internal DevOps) within your organization is not needed to go through vetting process.

Partners/ISVs developing & distributing the Managed solutions through Dynamics Marketplace aka Appsource has vetting process, Microsoft will review the solutions before publishing in AppSource. This is to make sure the compliance with respect to standard, policies, security aspects.


问:
How to select columns where value is not zero
How do you select columns where the value is not zero?

If I have 3 columns

```<code>column1|column2|column3
-------+-------+-------
   0   |   50  |   99
</code>```

I want the query to show only columns that have values > 0

so that the result will be

```<code>column2|column3
-------+-------
   50  |   99
</code>```

I have tried this:

```<code>SELECT * FROM `table1` WHERE `column1` != '0'
</code>```

答:
SQL returns tables of data.  Tables have the same columns on every row.  You cannot have a query where a column is missing in a row.

So if this select statement:

```<code>select column1, column2, column3 from table1
</code>```

returns

```<code>column1 | column2 | column3
    1   |    20   |   50
    0   |    12   |    2
    3   |    15   |    0
   10   |     0   |   11
</code>```

what do you expect would be in the first column of the second row if we omit columns with zeros?

The best you can do is replace zeros with NULL.

```<code>select CASE WHEN column1 > 0 THEN column1 ELSE NULL END,
       CASE WHEN column2 > 0 THEN column2 ELSE NULL END,
       CASE WHEN column3 > 0 THEN column3 ELSE NULL END
from table1
</code>```

Which would give us this:

```<code>column1 | column2 | column3
    1   |    20   |   50
  NULL  |    12   |    2
    3   |    15   |  NULL
   10   |   NULL  |   11
</code>```

Body:
How do you select columns where the value is not zero?

If I have 3 columns

column1|column2|column3
-------+-------+-------
   0   |   50  |   99

I want the query to show only columns that have values > 0

so that the result will be

column2|column3
-------+-------
   50  |   99

I have tried this:

SELECT * FROM `table1` WHERE `column1` != '0'

Body:
SQL returns tables of data.  Tables have the same columns on every row.  You cannot have a query where a column is missing in a row.

So if this select statement:

select column1, column2, column3 from table1

returns

column1 | column2 | column3
    1   |    20   |   50
    0   |    12   |    2
    3   |    15   |    0
   10   |     0   |   11

what do you expect would be in the first column of the second row if we omit columns with zeros?

The best you can do is replace zeros with NULL.

select CASE WHEN column1 > 0 THEN column1 ELSE NULL END,
       CASE WHEN column2 > 0 THEN column2 ELSE NULL END,
       CASE WHEN column3 > 0 THEN column3 ELSE NULL END
from table1

Which would give us this:

column1 | column2 | column3
    1   |    20   |   50
  NULL  |    12   |    2
    3   |    15   |  NULL
   10   |   NULL  |   11


问:
an array of datetime values
i have the following code where i try and populate an array with dates from 1988-2016

```<code>from datetime import datetime, timedelta
t = np.arange(datetime(1988,1,1), datetime(2016,1,1), timedelta(days=365)).astype(datetime)
</code>```

This gives me the following output:

```<code>array([datetime.datetime(1988, 1, 1, 0, 0),
       datetime.datetime(1988, 12, 31, 0, 0),
       datetime.datetime(1989, 12, 31, 0, 0),
                 ....
       datetime.datetime(2015, 12, 25, 0, 0)], dtype=object)
</code>```

However, for my output i just want to have the year and not the month or day and i dont want that datetime.datetime at the begining. So i am aming for something like this:

```<code>array([(1988)
      (1989),
      (1990),
        ...
      (2015)], dtype=object)
</code>```

How can i achieve this?

Title: an array of datetime values

Body:
i have the following code where i try and populate an array with dates from 1988-2016

from datetime import datetime, timedelta
t = np.arange(datetime(1988,1,1), datetime(2016,1,1), timedelta(days=365)).astype(datetime)

This gives me the following output:

array([datetime.datetime(1988, 1, 1, 0, 0),
       datetime.datetime(1988, 12, 31, 0, 0),
       datetime.datetime(1989, 12, 31, 0, 0),
                 ....
       datetime.datetime(2015, 12, 25, 0, 0)], dtype=object)

However, for my output i just want to have the year and not the month or day and i dont want that datetime.datetime at the begining. So i am aming for something like this:

array([(1988)
      (1989),
      (1990),
        ...
      (2015)], dtype=object)

How can i achieve this?

Body:
Use numpy.datetime64.

import numpy as np
t = np.arange('1988','2016',dtype='datetime64[Y]')

The variable will have the representation

array(['1988', '1989', '1990', '1991', '1992', '1993', '1994', '1995',
   '1996', '1997', '1998', '1999', '2000', '2001', '2002', '2003',
   '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011',
   '2012', '2013', '2014', '2015'], dtype='datetime64[Y]')

You can then change the formatter of datetime

np.set_printoptions(formatter={'datetime': lambda x: '('+str(x)+')'})

The variable will now be formatted as

array([(1988), (1989), (1990), (1991), (1992), (1993), (1994), (1995),
   (1996), (1997), (1998), (1999), (2000), (2001), (2002), (2003),
   (2004), (2005), (2006), (2007), (2008), (2009), (2010), (2011),
   (2012), (2013), (2014), (2015)], dtype='datetime64[Y]')


问:
WCF Hosting on remote server
I created a WCF service at my machine, I hosted it under IIS, it works fine.
then I compile my service , and i put the compile code at remote server. i hosted it under IIS on remote server. but when i try to consume it in my client at my own machine it generate the following error.

The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (application/soap+xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were: '

then I try to open it at remote server using browser. when i click on the link for wsdl it says bad request or invalid host name. what could be the problem.

答:
The "content type" error is actually produced on the client side because IIS is sending an HTML response to your soap request. The cause is usually the virtual directory in IIS isn't properly configured or that WCF is failing to initialize. The contents of the IIS response can sometimes be really helpful in debugging these issues. To inspect that HTML, use a tool like Fiddler to intercept and review the HTTP traffic during your request.

If the intercepted HTTP traffic isn't helpful, then start troubleshooting IIS by creating a simple HTML only page (something like test.html) in the folder where the WCF service .svc file is located. Try acessing that page through the browser. If the browser correctly shows the page contents then IIS is working and the problem is in the WCF config. Based on your two errors, I'd say you have an IIS config issue in the virtual directory for the service.

Title: WCF Hosting on remote server


问:
has_one and belong_to associations with the same table
I wonder is it ok to have like 2 associations with the same table. For example:

```<code>class CreateTeams < ActiveRecord::Migration[6.0]
  def change
    create_table :teams do |t|
      t.string :name, null: false
      t.references :manager, foreign_key: { to_table: 'users' }
    end
  end
end

class CreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      t.string :name, null: false
      t.references :team
    end
  end
end

class Team < ApplicationRecord
  has_many :users
  belongs_to :manager, class_name: 'User', foreign_key: 'manager_id'
end

class User < ApplicationRecord
  belongs_to :team
  has_one :child_team, class_name: 'Team' # bad name, but just for example
end
</code>```

Or it would be better to create a join table with team_id, user_id, and member_type?

Ruby/Rails versions do not matter but let's assume Ruby is 2.7.0 and Rails is 6.0.0

答:
What you have seems fine.

Though a join table would be more flexible to provide more roles. This also avoids having a circular dependency in setting up teams and users.

```<code>class CreateTeams < ActiveRecord::Migration[6.0]
  def change
    create_table :teams do |t|
      t.string :name, null: false

      t.timestamps
    end
  end
end

class CreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      t.string :name, null: false

      t.timestamps
    end
  end
end

class CreateTeamMembers < ActiveRecord::Migration[6.0]
  def change
    create_table :team_members do |t|
      t.belongs_to :user, null: false, foreign_key: true
      t.belongs_to :team, null: false, foreign_key: true
      t.integer :role, null: false

      t.timestamps

      # Enforce one manager per team
      t.index [:team_id],
        name: :one_manager,
        unique: true,
        where: "role = 0"
    end
  end
end

class TeamMember < ApplicationRecord
  enum role: { manager: 0, player: 1, fan: 2 }

  belongs_to :user
  belongs_to :team
end

class Team < ApplicationRecord
  has_many :users, through: :team_members

  has_many :team_members, dependent: :destroy
  has_one :manager, -> { where(role: :manager) }, class_name: "TeamMember"
  has_many :players, -> { where(role: :player) }, class_name: "TeamMember"
  has_many :fans, -> { where(role: :fan) }, class_name: "TeamMember"
end

class User < ApplicationRecord
  has_many :team_memberships, dependent: :destroy, class_name: "TeamMember"
  has_many :teams, through: :team_memberships
end
</code>```

You could even potentially take advantage of single table inheritance to differentiate your users by their role.

This is something you could migrate to later if necessary.

Body:
I wonder is it ok to have like 2 associations with the same table. For example:

class CreateTeams < ActiveRecord::Migration[6.0]
  def change
    create_table :teams do |t|
      t.string :name, null: false
      t.references :manager, foreign_key: { to_table: 'users' }
    end
  end
end

class CreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      t.string :name, null: false
      t.references :team
    end
  end
end

class Team < ApplicationRecord
  has_many :users
  belongs_to :manager, class_name: 'User', foreign_key: 'manager_id'
end

class User < ApplicationRecord
  belongs_to :team
  has_one :child_team, class_name: 'Team' # bad name, but just for example
end

Or it would be better to create a join table with team_id, user_id, and member_type?

Ruby/Rails versions do not matter but let's assume Ruby is 2.7.0 and Rails is 6.0.0

Body:
What you have seems fine.

Though a join table would be more flexible to provide more roles. This also avoids having a circular dependency in setting up teams and users.

class CreateTeams < ActiveRecord::Migration[6.0]
  def change
    create_table :teams do |t|
      t.string :name, null: false

      t.timestamps
    end
  end
end

class CreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      t.string :name, null: false

      t.timestamps
    end
  end
end

class CreateTeamMembers < ActiveRecord::Migration[6.0]
  def change
    create_table :team_members do |t|
      t.belongs_to :user, null: false, foreign_key: true
      t.belongs_to :team, null: false, foreign_key: true
      t.integer :role, null: false

      t.timestamps

      # Enforce one manager per team
      t.index [:team_id],
        name: :one_manager,
        unique: true,
        where: "role = 0"
    end
  end
end

class TeamMember < ApplicationRecord
  enum role: { manager: 0, player: 1, fan: 2 }

  belongs_to :user
  belongs_to :team
end

class Team < ApplicationRecord
  has_many :users, through: :team_members

  has_many :team_members, dependent: :destroy
  has_one :manager, -> { where(role: :manager) }, class_name: "TeamMember"
  has_many :players, -> { where(role: :player) }, class_name: "TeamMember"
  has_many :fans, -> { where(role: :fan) }, class_name: "TeamMember"
end

class User < ApplicationRecord
  has_many :team_memberships, dependent: :destroy, class_name: "TeamMember"
  has_many :teams, through: :team_memberships
end

You could even potentially take advantage of single table inheritance to differentiate your users by their role.

This is something you could migrate to later if necessary.


答:
Add 2 attributes move_up and move_down to the class Player and set the attributes in
pressed respectively released:

class Player {

    // [...]
    boolean move_up = false, move_down = false;

    void pressed(boolean up, boolean down) {
        if (up)   {move_up   = true;}
        if (down) {move_down = true;}
    }

    void released(boolean up, boolean down) {
        if (up)   {move_up   = false;}
        if (down) {move_down = false;}
    }
}
```

<p>Change <code>speedY</code> dependent on the attributes in <code>move</code>. Continuously reduce the speed if neither <code>move_up</code> not <code>move_down</code> is set (<code>speedY = speedY * 0.95;</code>). That causes that the player smoothly slows down if no key is pressed. If <code>move_up</code> or <code>move_down</code> is pressed the slightly change the speed dependent on the desired direction. Restrict the speed to a certain interval (<code>speedY = max(-5.0, min(5.0, speedY));</code>):    </p>

<pre class="lang-java prettyprint-override"><code>class Player {
    // [...]

    void move() {
        if (!move_up && !move_down) {speedY *= 0.95;}
        if (move_up)                {speedY -= 0.1;}
        if (move_down)              {speedY += 0.1;}
        speedY = max(-5.0, min(5.0, speedY));
        y += speedY;
    }

    // [...]
}
</code>```

Class Player:

class Player {

    float x, y;
    float w, h;
    float speedY = 0.0;
    color c;
    boolean move_up = false, move_down = false;

    //Constructor
    Player(float tempX, float tempY, float tempW, float tempH){

        x = tempX;
        y = tempY;
        w = tempW;
        h = tempH;
        c = (255);
    }

    void run() {
        display();
        move();
    }

    void display() {

        fill(c);
        rect(x, y-h/2, w, h);
        println(y);
    }

    void move() {
        if (!move_up && !move_down) {speedY *= 0.95;}
        if (move_up)                {speedY -= 0.1;}
        if (move_down)              {speedY += 0.1;}
        speedY = max(-5.0, min(5.0, speedY));
        y += speedY;
    }

    void pressed(boolean up, boolean down) {
        if (up)   {move_up   = true;}
        if (down) {move_down = true;}
    }

    void released(boolean up, boolean down) {
        if (up)   {move_up   = false;}
        if (down) {move_down = false;}
    }
}
```

Title: Smooth movement in processing?

Body:
Add 2 attributes move_up and move_down to the class Player and set the attributes in
pressed respectively released:

class Player {

    // [...]
    boolean move_up = false, move_down = false;

    void pressed(boolean up, boolean down) {
        if (up)   {move_up   = true;}
        if (down) {move_down = true;}
    }

    void released(boolean up, boolean down) {
        if (up)   {move_up   = false;}
        if (down) {move_down = false;}
    }
}

Change speedY dependent on the attributes in move. Continuously reduce the speed if neither move_up not move_down is set (speedY = speedY * 0.95;). That causes that the player smoothly slows down if no key is pressed. If move_up or move_down is pressed the slightly change the speed dependent on the desired direction. Restrict the speed to a certain interval (speedY = max(-5.0, min(5.0, speedY));):

class Player {
    // [...]

    void move() {
        if (!move_up && !move_down) {speedY *= 0.95;}
        if (move_up)                {speedY -= 0.1;}
        if (move_down)              {speedY += 0.1;}
        speedY = max(-5.0, min(5.0, speedY));
        y += speedY;
    }

    // [...]
}

Class Player:

class Player {

    float x, y;
    float w, h;
    float speedY = 0.0;
    color c;
    boolean move_up = false, move_down = false;

    //Constructor
    Player(float tempX, float tempY, float tempW, float tempH){

        x = tempX;
        y = tempY;
        w = tempW;
        h = tempH;
        c = (255);
    }

    void run() {
        display();
        move();
    }

    void display() {

        fill(c);
        rect(x, y-h/2, w, h);
        println(y);
    }

    void move() {
        if (!move_up && !move_down) {speedY *= 0.95;}
        if (move_up)                {speedY -= 0.1;}
        if (move_down)              {speedY += 0.1;}
        speedY = max(-5.0, min(5.0, speedY));
        y += speedY;
    }

    void pressed(boolean up, boolean down) {
        if (up)   {move_up   = true;}
        if (down) {move_down = true;}
    }

    void released(boolean up, boolean down) {
        if (up)   {move_up   = false;}
        if (down) {move_down = false;}
    }
}


问:
Call Oracle stored procedure from Select statement?
I have an Oracle stored procedure that gets 2 parameters and returns 2 parameters (status and message).

I am making changes to this legacy application capable of only executing select statements,

My question is it possible to wrap the stored procedure with some function or other stored procedure or a view, or any other object I might not no about, so can I execute the stored procedure using simple a select statement?

Correct execution code will be something like:

```<code>DECLARE
  PRINTER_ID VARCHAR2(200);
  O_STATUS VARCHAR2(200);
  O_MESSAGE VARCHAR2(200);
BEGIN
  PRINTER_ID := '551555115';
  IMPL_XEROX_PRINTER_CHECK(    PRINTER_ID => PRINTER_ID,    O_STATUS => O_STATUS,    O_MESSAGE => O_MESSAGE  );
  DBMS_OUTPUT.PUT_LINE('O_STATUS = ' || O_STATUS);
  DBMS_OUTPUT.PUT_LINE('O_MESSAGE = ' || O_MESSAGE);
END;
</code>```

What I am trying to get is something like:

```<code>Select O_STATUS,O_MESSAGE from IMPL_XEROX_PRINTER_CHECk_WRAPPER where PRINTER_ID = '551555115';
</code>```

The thing is that the SP is inserting some data to a temporary table...
this is the table:

```<code> CREATE TABLE "TEST_PRNT_DATA"    ( "COLUMN1" VARCHAR2(20 BYTE),    "COLUMN2" VARCHAR2(20 BYTE),    "COLUMN3" VARCHAR2(20 BYTE)   )
</code>```

/

This is the stored procedure:

```<code>CREATE OR REPLACE PROCEDURE IMPL_XEROX_PRINTER_CHECK
(
  PRINTER_ID IN VARCHAR2

, O_STATUS  OUT VARCHAR2
, O_MESSAGE OUT VARCHAR2
)  AS
    PROC_STATUS         VARCHAR2(10);
    PROC_ERROR_MESSAGE  VARCHAR2(4000);

    rand_num number;
BEGIN

     dbms_output.put_line('IMPL_XEROX_PRINTER_CHECK ');
     select round(dbms_random.value(1,10)) into rand_num     from dual;

     insert into TEST_PRNT_DATA values(1,2,3);

    IF rand_num < 5 THEN
            PROC_STATUS  := 'TRUE';
            O_STATUS:= 'TRUE';
            PROC_ERROR_MESSAGE := 'ALL IS GOOD';
            O_MESSAGE:= 'ALL IS GOOD';
    ELSE
            PROC_STATUS  := 'FALSE';
            O_STATUS:= 'FALSE';
            PROC_ERROR_MESSAGE := 'SOMTHING WENT WRONG!!! ';
            O_MESSAGE:= 'SOMTHING WENT WRONG!!! ';
    END IF;

END IMPL_XEROX_PRINTER_CHECK;
</code>```

答:
You could create a package with a pipelined table function:

```<code>CREATE OR REPLACE
PACKAGE PACKAGE1
AS
  type status_t is record ( o_status varchar2(10)
                          , o_message varchar2(4000));
  type status_tt is table of status_t;

  function impl_xerox_printer_check_w(printer_id varchar2) RETURN status_tt PIPELINED;

END PACKAGE1;
/
</code>```

With the following implementation:

```<code>CREATE OR REPLACE
PACKAGE BODY PACKAGE1 AS

  function impl_xerox_printer_check_w(printer_id varchar2) RETURN status_tt PIPELINED AS
    status status_t;
  BEGIN
    impl_xerox_printer_check(printer_id, status.o_status, status.o_message);

    PIPE ROW (status);
    RETURN;
  END impl_xerox_printer_check_w;

END PACKAGE1;
/
</code>```

and use it like this:

```<code>with printers as (
  select dbms_random.string('X',10) printer from dual connect by level <=5
)
select *
  from printers
 cross apply table(package1.impl_xerox_printer_check_w(printers.printer));
</code>```

Example output or check out the db<>fiddle:

```<code>PRINTER         O_STATUS   O_MESSAGE
--------------- ---------- ------------------------------
55FBCMHYOS      TRUE       ALL IS GOOD
0Z37VPOSLK      TRUE       ALL IS GOOD
XK1QKTZ8X2      FALSE      SOMTHING WENT WRONG!!!
K0Y6TN9YTR      FALSE      SOMTHING WENT WRONG!!!
8D0505711L      TRUE       ALL IS GOOD
</code>```

Body:
I have an Oracle stored procedure that gets 2 parameters and returns 2 parameters (status and message).

I am making changes to this legacy application capable of only executing select statements,

My question is it possible to wrap the stored procedure with some function or other stored procedure or a view, or any other object I might not no about, so can I execute the stored procedure using simple a select statement?

Correct execution code will be something like:

DECLARE
  PRINTER_ID VARCHAR2(200);
  O_STATUS VARCHAR2(200);
  O_MESSAGE VARCHAR2(200);
BEGIN
  PRINTER_ID := '551555115';
  IMPL_XEROX_PRINTER_CHECK(    PRINTER_ID => PRINTER_ID,    O_STATUS => O_STATUS,    O_MESSAGE => O_MESSAGE  );
  DBMS_OUTPUT.PUT_LINE('O_STATUS = ' || O_STATUS);
  DBMS_OUTPUT.PUT_LINE('O_MESSAGE = ' || O_MESSAGE);
END;

What I am trying to get is something like:

Select O_STATUS,O_MESSAGE from IMPL_XEROX_PRINTER_CHECk_WRAPPER where PRINTER_ID = '551555115';

The thing is that the SP is inserting some data to a temporary table...
this is the table:

 CREATE TABLE "TEST_PRNT_DATA"    ( "COLUMN1" VARCHAR2(20 BYTE),    "COLUMN2" VARCHAR2(20 BYTE),    "COLUMN3" VARCHAR2(20 BYTE)   )

/

This is the stored procedure:

CREATE OR REPLACE PROCEDURE IMPL_XEROX_PRINTER_CHECK
(
  PRINTER_ID IN VARCHAR2

, O_STATUS  OUT VARCHAR2
, O_MESSAGE OUT VARCHAR2
)  AS
    PROC_STATUS         VARCHAR2(10);
    PROC_ERROR_MESSAGE  VARCHAR2(4000);

    rand_num number;
BEGIN

     dbms_output.put_line('IMPL_XEROX_PRINTER_CHECK ');
     select round(dbms_random.value(1,10)) into rand_num     from dual;

     insert into TEST_PRNT_DATA values(1,2,3);

    IF rand_num < 5 THEN
            PROC_STATUS  := 'TRUE';
            O_STATUS:= 'TRUE';
            PROC_ERROR_MESSAGE := 'ALL IS GOOD';
            O_MESSAGE:= 'ALL IS GOOD';
    ELSE
            PROC_STATUS  := 'FALSE';
            O_STATUS:= 'FALSE';
            PROC_ERROR_MESSAGE := 'SOMTHING WENT WRONG!!! ';
            O_MESSAGE:= 'SOMTHING WENT WRONG!!! ';
    END IF;

END IMPL_XEROX_PRINTER_CHECK;

Body:
You could create a package with a pipelined table function:

CREATE OR REPLACE
PACKAGE PACKAGE1
AS
  type status_t is record ( o_status varchar2(10)
                          , o_message varchar2(4000));
  type status_tt is table of status_t;

  function impl_xerox_printer_check_w(printer_id varchar2) RETURN status_tt PIPELINED;

END PACKAGE1;
/

With the following implementation:

CREATE OR REPLACE
PACKAGE BODY PACKAGE1 AS

  function impl_xerox_printer_check_w(printer_id varchar2) RETURN status_tt PIPELINED AS
    status status_t;
  BEGIN
    impl_xerox_printer_check(printer_id, status.o_status, status.o_message);

    PIPE ROW (status);
    RETURN;
  END impl_xerox_printer_check_w;

END PACKAGE1;
/

and use it like this:

with printers as (
  select dbms_random.string('X',10) printer from dual connect by level <=5
)
select *
  from printers
 cross apply table(package1.impl_xerox_printer_check_w(printers.printer));

Example output or check out the db<>fiddle:

PRINTER         O_STATUS   O_MESSAGE
--------------- ---------- ------------------------------
55FBCMHYOS      TRUE       ALL IS GOOD
0Z37VPOSLK      TRUE       ALL IS GOOD
XK1QKTZ8X2      FALSE      SOMTHING WENT WRONG!!!
K0Y6TN9YTR      FALSE      SOMTHING WENT WRONG!!!
8D0505711L      TRUE       ALL IS GOOD


问:
WPF update UI Control asynchronously with a delay?
```<code>public void TextChangedEvent(object sender, EventArgs e)
        {
            TextBox changedTextBox = sender as TextBox;
            List<TextBox> textBoxes = new List<TextBox>();
            //gets Grid that contains all the textboxes
            var parentGrid = VisualHierarchyHelper.FindParent<Grid>(changedTextBox);
            var mainGrid = VisualHierarchyHelper.FindParent<Grid>(parentGrid);
            //ALL 81 textboxes
            var textBoxChildren = VisualHierarchyHelper.FindVisualChildren<TextBox>(mainGrid).ToList();
            for (int i = 0; i < textBoxChildren.Count; i++)
            {
                SendWithDelay(textBoxChildren[i]);
            }
        }

        async Task SendWithDelay(TextBox txt)
        {
            await Task.Delay(1000);
            txt.Background = Brushes.Red;
        }
</code>```

I want 81 grids to get a red background 1 by one, now it just waits a bit and updates everything at once.

Any suggestions?

Note: This code is runnable but it does complain about SendWithDelay(textBoxChildren[i]); not being awaited, if I change this and also change void to async Task it says Error   CS0407 'Task EventHandling.TextChangedEvent(object, EventArgs)' has the wrong return type.

EDIT

This is what I have now:

```<code>public void TextChangedEvent(object sender, EventArgs e)
        {
            TextBox changedTextBox = sender as TextBox;
            List<TextBox> textBoxes = new List<TextBox>();
            //gets Grid that contains all the textboxes
            var parentGrid = VisualHierarchyHelper.FindParent<Grid>(changedTextBox);
            var mainGrid = VisualHierarchyHelper.FindParent<Grid>(parentGrid);
            //ALL 81 textboxes
            var textBoxChildren = VisualHierarchyHelper.FindVisualChildren<TextBox>(mainGrid).ToList();
            for (int i = 0; i < textBoxChildren.Count; i++)
            {
                x SendWithDelay(textBoxChildren[i]);
            }
        }

        async void SendWithDelay(TextBox txt)
        {
            txt.Background = Brushes.Red;
            x await Task.Delay(500);
        }
</code>```

The breakpoints(x) just alternate between each other. Then when they're done everything gets red.

答:
You can make make TextChangedEvent async:

public async void TextChangedEvent(object sender, EventArgs e) {

And await the call to SendWithDelay:

await SendWithDelay(textBoxChildren[i]);

It'll get rid of all the warnings you're getting, but it seems like you want SendWithDelay to be "Fire and forget", this way you can change SendWithDelay to async void instead of async Task:

async Task SendWithDelay(TextBox txt) {

And not await every call to it:

SendWithDelay(textBoxChildren[i]);

Body:
public void TextChangedEvent(object sender, EventArgs e)
        {
            TextBox changedTextBox = sender as TextBox;
            List<TextBox> textBoxes = new List<TextBox>();
            //gets Grid that contains all the textboxes
            var parentGrid = VisualHierarchyHelper.FindParent<Grid>(changedTextBox);
            var mainGrid = VisualHierarchyHelper.FindParent<Grid>(parentGrid);
            //ALL 81 textboxes
            var textBoxChildren = VisualHierarchyHelper.FindVisualChildren<TextBox>(mainGrid).ToList();
            for (int i = 0; i < textBoxChildren.Count; i++)
            {
                SendWithDelay(textBoxChildren[i]);
            }
        }

        async Task SendWithDelay(TextBox txt)
        {
            await Task.Delay(1000);
            txt.Background = Brushes.Red;
        }

I want 81 grids to get a red background 1 by one, now it just waits a bit and updates everything at once.

Any suggestions?

Note: This code is runnable but it does complain about SendWithDelay(textBoxChildren[i]); not being awaited, if I change this and also change void to async Task it says Error   CS0407 'Task EventHandling.TextChangedEvent(object, EventArgs)' has the wrong return type.

EDIT

This is what I have now:

public void TextChangedEvent(object sender, EventArgs e)
        {
            TextBox changedTextBox = sender as TextBox;
            List<TextBox> textBoxes = new List<TextBox>();
            //gets Grid that contains all the textboxes
            var parentGrid = VisualHierarchyHelper.FindParent<Grid>(changedTextBox);
            var mainGrid = VisualHierarchyHelper.FindParent<Grid>(parentGrid);
            //ALL 81 textboxes
            var textBoxChildren = VisualHierarchyHelper.FindVisualChildren<TextBox>(mainGrid).ToList();
            for (int i = 0; i < textBoxChildren.Count; i++)
            {
                x SendWithDelay(textBoxChildren[i]);
            }
        }

        async void SendWithDelay(TextBox txt)
        {
            txt.Background = Brushes.Red;
            x await Task.Delay(500);
        }

The breakpoints(x) just alternate between each other. Then when they're done everything gets red.


问:
NOT HAVING (inverse HAVING) clause with aggregation in Oracle
I am trying to filter the results of a GROUP BY CUBE using the HAVING clause. However I need to keep rows that do not meet a combination of conditions.

I intuitively tried:

```<code>SELECT [...]
FROM [...]
NOT HAVING (flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1)
GROUP BY CUBE [...]
</code>```

Sadly Oracle doesn't recognize NOT HAVING as valid syntax.

From a mathematical standpoint, inversing each individual condition does not yield the same result :

HAVING (flag_1 != 1 AND flag_2 != 1 AND flag_3 != 1)

How can I achieve the logical equivalent of NOT HAVING ?

Note: I found an existing question that was somewhat related, but it was specific to Microsoft Access and the goal was not the same, hence this new question.

答:
The mathematical inverse of your HAVING clause requires that you change the AND's to OR's and, if columns are nullable, null-check as well.

EG (if nulls are possible):

```<code>HAVING (nvl(flag_1,1) != 1 OR NVL(flag_2,1) != 1 OR NVL(flag_3,1) != 1)
</code>```

Body:
I am trying to filter the results of a GROUP BY CUBE using the HAVING clause. However I need to keep rows that do not meet a combination of conditions.

I intuitively tried:

SELECT [...]
FROM [...]
NOT HAVING (flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1)
GROUP BY CUBE [...]

Sadly Oracle doesn't recognize NOT HAVING as valid syntax.

From a mathematical standpoint, inversing each individual condition does not yield the same result :

HAVING (flag_1 != 1 AND flag_2 != 1 AND flag_3 != 1)

How can I achieve the logical equivalent of NOT HAVING ?

Note: I found an existing question that was somewhat related, but it was specific to Microsoft Access and the goal was not the same, hence this new question.

Body:
The mathematical inverse of your HAVING clause requires that you change the AND's to OR's and, if columns are nullable, null-check as well.

EG (if nulls are possible):

HAVING (nvl(flag_1,1) != 1 OR NVL(flag_2,1) != 1 OR NVL(flag_3,1) != 1)


问:
Nested if loop not firing in python
I have a python question and I can't figure out why this is not firing. Below is the code:

```<code>import re
sfname='C:\python_Script\Testmain.txt'
i=0
Var1='AS'
Var2=''
Var3=''

with open("C:\python_Script\Testmain.txt") as file_in:
    lines = []
    for line in file_in:
        lines.append(line)
        if line.startswith('create view [dbo].'):
            print (lines[i])
        if not line.startswith('create view [dbo].'):
            lines[i]=lines[i].replace("_"," ")
            lines[i]= re.sub(r"\bid","key",lines[i])
            Var2=lines[i]
            Var2=re.sub(r"\bkey","Dimension",Var2)
            if not line.endswith("Dimension"):
                Var2='Fact Table'
            Var3=lines[i] +"    "+Var1+"    "+Var2

            print(Var3)
        i+=1
</code>```

the text file I'm reading from is relatively simple it has these attributes in it:

```<code>create view [dbo].Ignore_table
communication_channel_id
user_id
bounce_count
assignment_override_id
create view [dbo].test1
id
test1
</code>```

basically I want to ignore anything with 'create view[dbo].' and create a print statement which replaces the word 'ID' with 'Key' adds an AS and then does 1 of 2 things:
if) Var2 ends with 'Key' replace with the word 'Dimension'.
if) var2 does not end with 'Key' then rename the whole thing 'Fact table'

but for some reason this second if the loop will fire even if it does not end with 'dimension' and it will always be 'Fact Table' Why?

答:
Thank you kederrac, his answer was on point and got me to where I needed to go. I guess I didnt need to nest my if so much. for future googlers:</p>

```<code>import re
sfname='C:\python_Script\Testmain.txt'
Var1='AS'
Var2=''
Var3=''

with open(sfname) as file_in:
for line in file_in:
    line = line.strip()
    if line.startswith('create view [dbo].'):
        print(line)

    else:
        line = line.replace("_", " ")

        # replaces the word 'ID' with 'Key'
        line = re.sub(r"\bid","key",line)
        Var2 = line

        # if) Var2 ends with 'Key' replace with the word 'Dimension'.
        if Var2.endswith("key"):
            Var2 = line.replace("key","Dimension")
        else:
            Var2 = 'Fact Table'

        Var3 = line + "    " + Var1 + "    " + Var2

        print(Var3)
</code>```

Title: Nested if loop not firing in python

Body:
I have a python question and I can't figure out why this is not firing. Below is the code:

import re
sfname='C:\python_Script\Testmain.txt'
i=0
Var1='AS'
Var2=''
Var3=''

with open("C:\python_Script\Testmain.txt") as file_in:
    lines = []
    for line in file_in:
        lines.append(line)
        if line.startswith('create view [dbo].'):
            print (lines[i])
        if not line.startswith('create view [dbo].'):
            lines[i]=lines[i].replace("_"," ")
            lines[i]= re.sub(r"\bid","key",lines[i])
            Var2=lines[i]
            Var2=re.sub(r"\bkey","Dimension",Var2)
            if not line.endswith("Dimension"):
                Var2='Fact Table'
            Var3=lines[i] +"    "+Var1+"    "+Var2

            print(Var3)
        i+=1

the text file I'm reading from is relatively simple it has these attributes in it:

create view [dbo].Ignore_table
communication_channel_id
user_id
bounce_count
assignment_override_id
create view [dbo].test1
id
test1

basically I want to ignore anything with 'create view[dbo].' and create a print statement which replaces the word 'ID' with 'Key' adds an AS and then does 1 of 2 things:
if) Var2 ends with 'Key' replace with the word 'Dimension'.
if) var2 does not end with 'Key' then rename the whole thing 'Fact table'

but for some reason this second if the loop will fire even if it does not end with 'dimension' and it will always be 'Fact Table' Why?

Body:
Thank you kederrac, his answer was on point and got me to where I needed to go. I guess I didnt need to nest my if so much. for future googlers:

import re
sfname='C:\python_Script\Testmain.txt'
Var1='AS'
Var2=''
Var3=''

with open(sfname) as file_in:
for line in file_in:
    line = line.strip()
    if line.startswith('create view [dbo].'):
        print(line)

    else:
        line = line.replace("_", " ")

        # replaces the word 'ID' with 'Key'
        line = re.sub(r"\bid","key",line)
        Var2 = line

        # if) Var2 ends with 'Key' replace with the word 'Dimension'.
        if Var2.endswith("key"):
            Var2 = line.replace("key","Dimension")
        else:
            Var2 = 'Fact Table'

        Var3 = line + "    " + Var1 + "    " + Var2

        print(Var3)


问:
Pandas dataframe column with lists of lists of varying lengths to different columns
I have a following dataframe:

df = pd.DataFrame({'column': [[['a', 0], ['b', 1]], [['b', 2]], [['c', 1], ['b', 2]]]})
df
```

```    column
0   [[a, 0], [b, 1]]
1   [[b, 2]]
2   [[c, 1], [b, 2]]
```

<p>Where I don't know which letters exist and the amount of lists in each row varies. My goal is to get it looking like this:</p>

```     a    b    c
0    0    1    NaN
1    NaN  2    NaN
2    NaN  2    1
```

<p>A first step can be taken using:</p>

<pre class="lang-py prettyprint-override"><code>df['column'].apply(pd.Series)
</code>```

```<code>    0       1
0   [a, 0]  [b, 1]
1   [b, 2]
2   [c, 1]  [b, 2]
</code>```

However, a large part of this problem still stands.

答:
Try this</p>

```<code>df_final = pd.DataFrame(dict(l) for l in df.column)

Out[129]:
     a  b    c
0  0.0  1  NaN
1  NaN  2  NaN
2  NaN  2  1.0
</code>```

Body:
I have a following dataframe:

df = pd.DataFrame({'column': [[['a', 0], ['b', 1]], [['b', 2]], [['c', 1], ['b', 2]]]})
df

    column
0   [[a, 0], [b, 1]]
1   [[b, 2]]
2   [[c, 1], [b, 2]]

Where I don't know which letters exist and the amount of lists in each row varies. My goal is to get it looking like this:

     a    b    c
0    0    1    NaN
1    NaN  2    NaN
2    NaN  2    1

A first step can be taken using:

df['column'].apply(pd.Series)

    0       1
0   [a, 0]  [b, 1]
1   [b, 2]
2   [c, 1]  [b, 2]

However, a large part of this problem still stands.

Body:
Try this

df_final = pd.DataFrame(dict(l) for l in df.column)

Out[129]:
     a  b    c
0  0.0  1  NaN
1  NaN  2  NaN
2  NaN  2  1.0


问:
Is there a function in ms-access sql-query with which one can extract a certain string?
I was wondering if there is a function in MS-Access SQL-Query with which one can extract a given string of each cell of a column (similar to substring() but with a string as criteria).

For example, I would like to extract the keywords SUN and FUN from the following column (named Lyrics)

Lyrics

```<code>AeSUN9SL
Pla4FUNP
L2wqSUNop
ASUNfdNNK
7dssFUN9SL
</code>```

so that I am only left with:
Lyrics

```<code>SUN
FUN
SUN
SUN
FUN
</code>```

in the column. Since the length as well as the number of "unused" characters before and after the string keyword differ,  I could not use left() and right().

Is there another way to solve this problem?

答:
You can use regular expression subtring function
https://www.techonthenet.com/oracle/functions/regexp_substr.php</p>

```<code>select regexp_substr(Lyrics,'(SUN|FUN)', 1,1, 'i') from yourtablenamehere;
</code>```

Body:
I was wondering if there is a function in MS-Access SQL-Query with which one can extract a given string of each cell of a column (similar to substring() but with a string as criteria).

For example, I would like to extract the keywords SUN and FUN from the following column (named Lyrics)

Lyrics

AeSUN9SL
Pla4FUNP
L2wqSUNop
ASUNfdNNK
7dssFUN9SL

so that I am only left with:
Lyrics

SUN
FUN
SUN
SUN
FUN

in the column. Since the length as well as the number of "unused" characters before and after the string keyword differ,  I could not use left() and right().

Is there another way to solve this problem?

Body:
You can use regular expression subtring function
https://www.techonthenet.com/oracle/functions/regexp_substr.php

select regexp_substr(Lyrics,'(SUN|FUN)', 1,1, 'i') from yourtablenamehere;


问:
HTTP Error 500.19 - Internal Server Error Error Code: 0x8007000d
I published my code to our IIS server and I am getting this error. From many recommendation that I read online, I installed Url rewrite but it does not seem to fix the issue. This error points to Web.Config and I don't see any problem with it as it was also auto-generated. Everything works when I test it in IIS Express on Visual Studio 2019. Any idea? see code below:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\forms.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>
</code>```

答:
try installing  DotNetCore.1.0.0-WindowsHosting.exe from this page: https://www.microsoft.com/net/download .

Specific link to download: https://go.microsoft.com/fwlink/?LinkId=817246

Body:
I published my code to our IIS server and I am getting this error. From many recommendation that I read online, I installed Url rewrite but it does not seem to fix the issue. This error points to Web.Config and I don't see any problem with it as it was also auto-generated. Everything works when I test it in IIS Express on Visual Studio 2019. Any idea? see code below:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\forms.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>


问:
NEED EXCEL IN COUNTIF AND COUNTIFS
ı am stuck in formula and ı don't know how to solve this problem.
ı want a write a formula which is check the names if the names are same counts data which is in the other column.
Can you help me please.</p>

答:
In this problem ı use SUM(COUNTIFS( method.

example = sum(countifs(B:B;name which ı described for criteria;E:E;{"and this part ı described all data names which is in E column";"like this";"as far as want"}))

ı tried to explain with best way ı hope this answer will help you.
maybe there is a short way to do this if you solve this with other way please tell us.
Thank You.

Title: NEED EXCEL IN COUNTIF AND COUNTIFS


问:
How do I mount a network volume inside my Docker Windows container
I need to share a network drive inside my Windows docker container under the A: drive.
The network drive I need to shared is not empty, and I would need to access it with and right permissions.
How can I achieve this? I've only found posts about people mapping their C: drive.

Should it be done during build or at runtime?

It tried the obvious

docker run -it --rm --name windows my/image --privileged -v \\ip\mount\my\folder:A:\my\folder

but I get this error:

```<code>[Event Detail: onecore\vm\compute\management\orchestration\vmhostedcontainer\processmanagement.cpp(173)\vmcomputeagent.exe!00007FF6F8AFAE77: (caller: 00007FF6F8AAE4AB) Exception(2) tid(39c) 80070002 The system cannot find the file specified.
    CallContext:[\Bridge_ProcessMessage\VmHostedContainer_ExecuteProcess]
</code>```

I'm using Docker Desktop  2.2.0.0 on Windows 10 Pro 1903

Edit:
I should have set the image after the volumes it seems. With the following command, The error is different:

docker run -it --rm --name windows --privileged -v \\ip\mount\my\folder:A:\my\folder my/image

docker: Error response from daemon: invalid volume specification: '\\ip\mount\my\folder:A:my\folder'

答:
You need to create gMSAs for Docker container. Actually, th IT Team should do it for you (following this tutorial, for example).
They will then provide you with a credentials file. You can then run your docker container with:

```<code>docker run -it --rm --name windows --security-opt "credentialspec=file://my_credentials.json" my/image
</code>```

then, in the container, you can use net use to mount your volume under the  letter you want.
You can't do it in the container run command, however.

Body:
I need to share a network drive inside my Windows docker container under the A: drive.
The network drive I need to shared is not empty, and I would need to access it with and right permissions.
How can I achieve this? I've only found posts about people mapping their C: drive.

Should it be done during build or at runtime?

It tried the obvious

docker run -it --rm --name windows my/image --privileged -v \\ip\mount\my\folder:A:\my\folder

but I get this error:

[Event Detail: onecore\vm\compute\management\orchestration\vmhostedcontainer\processmanagement.cpp(173)\vmcomputeagent.exe!00007FF6F8AFAE77: (caller: 00007FF6F8AAE4AB) Exception(2) tid(39c) 80070002 The system cannot find the file specified.
    CallContext:[\Bridge_ProcessMessage\VmHostedContainer_ExecuteProcess]

I'm using Docker Desktop  2.2.0.0 on Windows 10 Pro 1903

Edit:
I should have set the image after the volumes it seems. With the following command, The error is different:

docker run -it --rm --name windows --privileged -v \\ip\mount\my\folder:A:\my\folder my/image

docker: Error response from daemon: invalid volume specification: '\\ip\mount\my\folder:A:my\folder'

Body:
You need to create gMSAs for Docker container. Actually, th IT Team should do it for you (following this tutorial, for example).
They will then provide you with a credentials file. You can then run your docker container with:

docker run -it --rm --name windows --security-opt "credentialspec=file://my_credentials.json" my/image

then, in the container, you can use net use to mount your volume under the  letter you want.
You can't do it in the container run command, however.


问:
Use JQuery to assign function to Primefaces DataList Children
I'm trying to create a jquery ui sortable in Primefaces and convert my html/jquery example to primefaces jquery. I'm trying to add the sortable() function to each element within the dataList.  Any ideas on how to apply the sortable() (this function is in an external library).

Html Example:

```<code> $(function() {
                   $( "#sortable" ).sortable(/*{placeholder: "ui-state-highlight"}*/);
                   $( "#sortable" ).disableSelection();
           });
           </script>
    </head>
    <body>
    <div class="demo">

    <ul id="sortable">
           <li ><div class="copy">Title</div><div class="box"><img src="images/images1.jpg"/></div><div class="copy">Stuff Stuff Stuff</div></li>
           <li ><div class="copy">Title</div><div class="box"><img src="images/images1.jpg"/></div><div class="copy">Stuff Stuff Stuff</div></li>
           <li ><div class="copy">Title</div><div class="box"><img src="images/images1.jpg"/></div><div class="copy">Stuff Stuff Stuff</div></li>
           <li ><div class="copy">Title</div><div class="box"><img src="images/images1.jpg"/></div><div class="copy">Stuff Stuff Stuff</div></li>
           <li ><div class="copy">Title</div><div class="box"><img src="images/images1.jpg"/></div><div class="copy">Stuff Stuff Stuff</div></li>
           <li ><div class="copy">Title</div><div class="box"><img src="images/images1.jpg"/></div><div class="copy">Stuff Stuff Stuff</div></li>
           <li ><div class="copy">Title</div><div class="box"><img src="images/images1.jpg"/></div><div class="copy">Stuff Stuff Stuff</div></li>
           <li ><div class="copy">Title</div><div class="box"><img src="images/images1.jpg"/></div><div class="copy">Stuff Stuff Stuff</div></li>
       <li ><div class="copy">Title</div><div class="box"><img src="images/images1.jpg"/></div><div class="copy">Stuff Stuff Stuff</div></li>
           <li ><div class="copy">Title</div><div class="box"><img src="images/images1.jpg"/></div><div class="copy">Stuff Stuff Stuff</div></li>
    </ul>
</code>```

primefaces attempt:

```<code><script>
    $ = jQuery
    $(function() {
    $( "#dreamModifyFrm:topTenGrd" ).sortable();
    $( "#dreamModifyFrm:topTenGrd" ).disableSelection();
    });
    </script>
    <h:form id="dreamModifyFrm" binding="#{dreamModify.dreamModifyFrm}">
         <p:dataList id="topTenGrd" var="dream" value="#{dreamModifyBean.topDreams}">
              <h:outputText class="dream-title uppercase" value="#{dream.number}. #{dream.title}" />
              <p:commandLink oncomplete="dreamEditDlg.show()" update=":dreamEditFrm:display">
                    <f:setPropertyActionListener value="#{dream}" target="#{dreamModifyBean.selectedDream}"/>
                    <f:setPropertyActionListener value="true" target="#{dreamModifyBean.editLink}"/>
                    <p:graphicImage value="#{dream.imageThumb}" width="125" height="100" />
              </p:commandLink>

     </p:dataList>
</h:form>
</code>```

答:
Although a little late, an answer may be helpful.

Problem: jQuery's .sortable() function tries to sort the direct child-elements of the selected object. Since primefaces renders some divs around your list, you need to point explicit to the enclosing ul.

Solution:

```<code><script type="text/javascript">
$(function() {
  $( "#dreamModifyFrm:topTenGrd ul" ).sortable();
  $( "#dreamModifyFrm:topTenGrd ul" ).disableSelection();
});
</script>
</code>```

(Note the modified jQuery-Selector)

Edit: Equivalent behaviour for DataTable. There you need to modify the selector by "tbody"

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to create a jquery ui sortable in Primefaces and convert my html/jquery example to primefaces jquery. I'm trying to add the sortable() function to each element within the dataList.  Any ideas on how to apply the sortable() (this function is in an external library).

Html Example:

 $(function() {
                   $( "#sortable" ).sortable(/*{placeholder: "ui-state-highlight"}*/);
                   $( "#sortable" ).disableSelection();
           });
           </script>

Title

Stuff Stuff Stuff

Title

Stuff Stuff Stuff

Title

Stuff Stuff Stuff

Title

Stuff Stuff Stuff

Title

Stuff Stuff Stuff

Title

Stuff Stuff Stuff

Title

Stuff Stuff Stuff

Title

Stuff Stuff Stuff

Title

Stuff Stuff Stuff

Title

Stuff Stuff Stuff

primefaces attempt:

    <h:form id="dreamModifyFrm" binding="#{dreamModify.dreamModifyFrm}">

              <h:outputText class="dream-title uppercase" value="#{dream.number}. #{dream.title}" />

                    <f:setPropertyActionListener value="#{dream}" target="#{dreamModifyBean.selectedDream}"/>
                    <f:setPropertyActionListener value="true" target="#{dreamModifyBean.editLink}"/>

</h:form>

Body:
Although a little late, an answer may be helpful.

Problem: jQuery's .sortable() function tries to sort the direct child-elements of the selected object. Since primefaces renders some divs around your list, you need to point explicit to the enclosing ul.

Solution:

<script type="text/javascript">
$(function() {
  $( "#dreamModifyFrm:topTenGrd ul" ).sortable();
  $( "#dreamModifyFrm:topTenGrd ul" ).disableSelection();
});
</script>

(Note the modified jQuery-Selector)

Edit: Equivalent behaviour for DataTable. There you need to modify the selector by "tbody"


问:
Class-validator is ignoring nested objects
I am using NestJs framework for my project. In my controller I accept POST request and through ValidationPipe I transform body into my CreateHouseDTO. ValidationPipe is using whitelist and transform.

When I try api with JSON like this:

```<code>{
    "name": "Test",
    "floors": [
        {
            "name": "floor1",
            "rooms": [
                {
                    "name": "room1"
                },
                {
                    "name": "room2"
                }
            ]
        }
    ]
}
</code>```

This is what my app logs (console.log output):

```<code>CreateHouseDTO{
    name:'Test',
    floors[ {} ]
}
</code>```

It does even validate the nested objects when I make some mistakes in them. For example if I set name property in Floor object to Null or to some number without quotes.

Is it a bug or am I doing something wrong? Please help me.

My code:

//My DTOs
import {ValidateNested, IsString, IsArray} from "class-validator";
import {Body, Controller, Post} from "@nestjs/common";

export class CreateHouseDTO {
    @IsNotEmpty()
    @IsString()
    public name?: string;

    @ValidateNested({each: true})
    @IsArray()
    @IsNotEmpty()
    public floors?: CreateFloorDTO[];
}

export class CreateFloorDTO {
    @IsString()
    @IsNotEmpty()
    public name?: string;

    @ValidateNested({each: true})
    @IsNotEmpty()
    @IsArray()
    public rooms?: CreateRoomDTO[];
}

export class CreateRoomDTO {
    @IsString()
    @IsNotEmpty()
    public name?: string;
}

//My Controller
@Controller("house")
export class HouseController {
    @Post()
    async create(
        @Body()
            body: CreateHouseDTO
    ) {
        console.log(body); //output I mentioned
        return body;
    }
}
```

答:
You should do it like this:</p>

```<code>export class CreateHouseDTO {
    @IsNotEmpty()
    @IsString()
    public name?: string;

    @ValidateNested({each: true})
    @IsArray()
    @IsNotEmpty()
    @Type(()=>CreateFloorDTO)
    public floors?: CreateFloorDTO[];
}
</code>```

Body:
I am using NestJs framework for my project. In my controller I accept POST request and through ValidationPipe I transform body into my CreateHouseDTO. ValidationPipe is using whitelist and transform.

When I try api with JSON like this:

{
    "name": "Test",
    "floors": [
        {
            "name": "floor1",
            "rooms": [
                {
                    "name": "room1"
                },
                {
                    "name": "room2"
                }
            ]
        }
    ]
}

This is what my app logs (console.log output):

CreateHouseDTO{
    name:'Test',
    floors[ {} ]
}

It does even validate the nested objects when I make some mistakes in them. For example if I set name property in Floor object to Null or to some number without quotes.

Is it a bug or am I doing something wrong? Please help me.

My code:

//My DTOs
import {ValidateNested, IsString, IsArray} from "class-validator";
import {Body, Controller, Post} from "@nestjs/common";

export class CreateHouseDTO {
    @IsNotEmpty()
    @IsString()
    public name?: string;

    @ValidateNested({each: true})
    @IsArray()
    @IsNotEmpty()
    public floors?: CreateFloorDTO[];
}

export class CreateFloorDTO {
    @IsString()
    @IsNotEmpty()
    public name?: string;

    @ValidateNested({each: true})
    @IsNotEmpty()
    @IsArray()
    public rooms?: CreateRoomDTO[];
}

export class CreateRoomDTO {
    @IsString()
    @IsNotEmpty()
    public name?: string;
}

//My Controller
@Controller("house")
export class HouseController {
    @Post()
    async create(
        @Body()
            body: CreateHouseDTO
    ) {
        console.log(body); //output I mentioned
        return body;
    }
}

Body:
You should do it like this:

export class CreateHouseDTO {
    @IsNotEmpty()
    @IsString()
    public name?: string;

    @ValidateNested({each: true})
    @IsArray()
    @IsNotEmpty()
    @Type(()=>CreateFloorDTO)
    public floors?: CreateFloorDTO[];
}