问:
Numpy add array of shape NxD to NxK into the first D in array NxK
I have two arrays

```<code>a = np.array([[0, 0, 2, 3, 4],
              [0, 1, 2, 3, 4],
              [0, 2, 2, 3, 4]])
</code>```

and

```<code>b = np.array([[1, 1],
              [2, 2],
              [3, 3]])
</code>```

I want to one array where I am adding the values of b to the first two columns in a like this:

```<code>c = np.array([[1, 1, 2, 3, 4],
              [2, 3, 2, 3, 4],
              [3, 5, 2, 3, 4]])
</code>```

if it helps you can think of the first two columns in a as the x,y coordinates and b as dx, dy.

My current method is as follows:

```<code>c = np.concatenate([a[:, 0:2] + b, a[:, 2:]],1)
</code>```

but I am looking for a better method

Thank you

Body:
I have two arrays

a = np.array([[0, 0, 2, 3, 4],
              [0, 1, 2, 3, 4],
              [0, 2, 2, 3, 4]])

and

b = np.array([[1, 1],
              [2, 2],
              [3, 3]])

I want to one array where I am adding the values of b to the first two columns in a like this:

c = np.array([[1, 1, 2, 3, 4],
              [2, 3, 2, 3, 4],
              [3, 5, 2, 3, 4]])

if it helps you can think of the first two columns in a as the x,y coordinates and b as dx, dy.

My current method is as follows:

c = np.concatenate([a[:, 0:2] + b, a[:, 2:]],1)

but I am looking for a better method

Thank you

Body:
You can use np.pad to add zeros to b to make its shape the same as a's, then add them:

>>> a + np.pad(b, ((0, 0), (0, 3)))
array([[1, 1, 2, 3, 4],
       [2, 3, 2, 3, 4],
       [3, 5, 2, 3, 4]])

In general (for 2-D):

>>> a = np.array([[0, 0, 2, 3, 4],
...               [0, 1, 2, 3, 4],
...               [0, 2, 2, 3, 4]])
>>> b = np.array([[1, 1],
...               [2, 2],
...               [3, 3],
...               [4, 4],
...               [5, 5]])
>>> a_shape, b_shape = a.shape, b.shape
>>> max_w = max(a_shape[0], b_shape[0])
>>> max_h = max(a_shape[1], b_shape[1])
>>> padded_a = np.pad(a,
                      ((0, np.abs(a_shape[0] - max_w)),
                       (0, np.abs(a_shape[1] - max_h))))
>>> padded_a
array([[0, 0, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 2, 2, 3, 4],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
>>> padded_b = np.pad(b,
                      ((0, np.abs(b_shape[0] - max_w)),
                       (0, np.abs(b_shape[1] - max_h))))
>>> padded_b
array([[1, 1, 0, 0, 0],
       [2, 2, 0, 0, 0],
       [3, 3, 0, 0, 0],
       [4, 4, 0, 0, 0],
       [5, 5, 0, 0, 0]])
>>> padded_a + padded_b
array([[1, 1, 2, 3, 4],
       [2, 3, 2, 3, 4],
       [3, 5, 2, 3, 4],
       [4, 4, 0, 0, 0],
       [5, 5, 0, 0, 0]])

In general (2-D, using a zeros array and adding to it):

>>> c = np.zeros((max_h, max_w), dtype=a.dtype)
>>> c[:a_shape[0], :a_shape[1]] += a
>>> c[:b_shape[0], :b_shape[1]] += b
>>> c
array([[1, 1, 2, 3, 4],
       [2, 3, 2, 3, 4],
       [3, 5, 2, 3, 4],
       [4, 4, 0, 0, 0],
       [5, 5, 0, 0, 0]])


来源: stackexchange

问:
Rotating Line around Point in p5.js
Goal: I'm trying to create a triangle given two angles (a0,b0). To do so, I'm trying to rotate a vector r0 by some angle a0 around one of the vertices of r0. Here's a diagram illustrating my idea.

Problem: However, when I rotate the line, it seems to rotate around the origin. I've read many, many articles on how to fix this, but none of the suggested solutions (i.e., translate then rotate, push(), pop()) don't seem to work, perhaps because I'm dealing with a line segment here. Below is my code.

MWE Code:

let angle = 0;

function setup() {
  createCanvas(600, 400);
  angleMode(DEGREES);
}

function draw() {
  let v1 = createVector(width / 2 - 50, height / 2);
  let v2 = createVector(width / 2 + 50, height / 2);

  background(255);
  stroke(0);
  strokeWeight(4);
  let r0 = line(v1.x, v1.y, v2.x, v2.y);
  rotate(20);
  let r1 = line(v1.x, v1.y, v2.x, v2.y);
  strokeWeight(10);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/p5@1.4.1/lib/p5.min.js"></script></code>```

Any help is appreciated.

答:
rotate rotates around the origin of the coordinate system. To rotate around a pivot point, you must:

move the pivot to the origin

rotate the object

move the pivot back to its place in the scene

```<code>translate(v1.x, v1.y);
rotate(-1 * mouseX);
translate(-v1.x, -v1.y);
</code>```

let angle = 0;

function setup() {
  createCanvas(600, 300);
  angleMode(DEGREES);
}

function draw() {
  let v1 = createVector(width / 2 - 50, height / 2);
  let v2 = createVector(width / 2 + 50, height / 2);

  background(255);
  stroke(0);
  strokeWeight(4);

  push();
  translate(v1.x, v1.y);
  rotate(-1 * mouseX);
  translate(-v1.x, -v1.y);
  let r0 = line(v1.x, v1.y, v2.x, v2.y);
  strokeWeight(10);
  let p1 = point(v1.x, v1.y);
  let p2 = point(v2.x, v2.y);
  pop();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/p5@1.4.1/lib/p5.min.js"></script></code>```

For individual model transformations, you must push() the current matrix before specifying the transformations and pop() the matrix after drawing the objects. So you can draw different objects with different transformations.

ContentLicense: CC BY-SA 4.0

Title: Rotating Line around Point in p5.js

Body:
Goal: I'm trying to create a triangle given two angles (a0,b0). To do so, I'm trying to rotate a vector r0 by some angle a0 around one of the vertices of r0. Here's a diagram illustrating my idea.

Problem: However, when I rotate the line, it seems to rotate around the origin. I've read many, many articles on how to fix this, but none of the suggested solutions (i.e., translate then rotate, push(), pop()) don't seem to work, perhaps because I'm dealing with a line segment here. Below is my code.

MWE Code:

let angle = 0;

function setup() {
  createCanvas(600, 400);
  angleMode(DEGREES);
}

function draw() {
  let v1 = createVector(width / 2 - 50, height / 2);
  let v2 = createVector(width / 2 + 50, height / 2);

  background(255);
  stroke(0);
  strokeWeight(4);
  let r0 = line(v1.x, v1.y, v2.x, v2.y);
  rotate(20);
  let r1 = line(v1.x, v1.y, v2.x, v2.y);
  strokeWeight(10);
}

Any help is appreciated.

Body:
rotate rotates around the origin of the coordinate system. To rotate around a pivot point, you must:

move the pivot to the origin

rotate the object

move the pivot back to its place in the scene

translate(v1.x, v1.y);
rotate(-1 * mouseX);
translate(-v1.x, -v1.y);

let angle = 0;

function setup() {
  createCanvas(600, 300);
  angleMode(DEGREES);
}

function draw() {
  let v1 = createVector(width / 2 - 50, height / 2);
  let v2 = createVector(width / 2 + 50, height / 2);

  background(255);
  stroke(0);
  strokeWeight(4);

  push();
  translate(v1.x, v1.y);
  rotate(-1 * mouseX);
  translate(-v1.x, -v1.y);
  let r0 = line(v1.x, v1.y, v2.x, v2.y);
  strokeWeight(10);
  let p1 = point(v1.x, v1.y);
  let p2 = point(v2.x, v2.y);
  pop();
}

<script src="https://cdn.jsdelivr.net/npm/p5@1.4.1/lib/p5.min.js"></script>

For individual model transformations, you must push() the current matrix before specifying the transformations and pop() the matrix after drawing the objects. So you can draw different objects with different transformations.


问:
iOS Property not found on object of type 'AppDelegate *'
I have two viewControllers accessing a NSNumber on the AppDelegate.  One of them can see it, and the other can't.  I am totally confused by this.

The one with the problem has this code.

```<code>AppDelegate *dataStore = (AppDelegate *)[[UIApplication sharedApplication] delegate];
dataStore.downHUD = [NSNumber numberWithFloat:(float)progress];
</code>```

The other has this.

```<code>AppDelegate *dataStore = (AppDelegate *)[[UIApplication sharedApplication] delegate];
dataStore.downHUD = [NSNumber numberWithFloat:(float)0];
</code>```

Both imports the AppDelegate in the .m file but I end up with

Property 'downHUD' not found on object of type 'AppDelegate *'

with the first one.
Anyone that can help me see what's wrong?

I copied and pasted a lot of code into the AppDelegate by mistake, that has been corrected.  Is there some sort of link that could got broken?

答:
If you're using expo this is how to get rid of the bug.
"reactDelegate" was introduced in sdk 44.0.0 so if you're using sdk 43.0.0
here's is how your code should look in your "AppDelegate.m" from line 35 - 46.</p>
```<code>RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge moduleName:@"main" initialProperties:nil];
rootView.backgroundColor = [UIColor whiteColor];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];

[super application:application didFinishLaunchingWithOptions:launchOptions];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two viewControllers accessing a NSNumber on the AppDelegate.  One of them can see it, and the other can't.  I am totally confused by this.

The one with the problem has this code.

AppDelegate *dataStore = (AppDelegate *)[[UIApplication sharedApplication] delegate];
dataStore.downHUD = [NSNumber numberWithFloat:(float)progress];

The other has this.

AppDelegate *dataStore = (AppDelegate *)[[UIApplication sharedApplication] delegate];
dataStore.downHUD = [NSNumber numberWithFloat:(float)0];

Both imports the AppDelegate in the .m file but I end up with

Property 'downHUD' not found on object of type 'AppDelegate *'

with the first one.
Anyone that can help me see what's wrong?

I copied and pasted a lot of code into the AppDelegate by mistake, that has been corrected.  Is there some sort of link that could got broken?

Body:
If you're using expo this is how to get rid of the bug.
"reactDelegate" was introduced in sdk 44.0.0 so if you're using sdk 43.0.0
here's is how your code should look in your "AppDelegate.m" from line 35 - 46.

RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge moduleName:@"main" initialProperties:nil];
rootView.backgroundColor = [UIColor whiteColor];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];

[super application:application didFinishLaunchingWithOptions:launchOptions];


问:
Any way to edit sass/scss file from styles tab in Chrome DevTools
Editing sass/scss is working via source maps only through code editor in devtools.

But when i make changes in elements -> styles tab, these changes are not saved to sass/scss file.

For example, if I change border-radius to another value, it will not be saved to scss file.

Here is my scss code

```<code>.SiteBuilder .e-row__select {
  position: relative;

  &:after {
    content: '';
  }

  select {
    border-radius: 4px;
  }
}
</code>```

答:
The styles you see from inspector are coming only from css files.

You can see the "sass/scss" source for each css property because there is a *.css.map associated with the current css file. The *.css.map file is generated from the sass compiler.

Every change you make on the Styles tab is not saved anywhere.

In order to make css changes you could use Chrome Devtools "Local Overrides" or "Workspaces". But even on this case you could edit the css or scss files from the Sources tab, not from the inspector.

Body:
Editing sass/scss is working via source maps only through code editor in devtools.

But when i make changes in elements -> styles tab, these changes are not saved to sass/scss file.

For example, if I change border-radius to another value, it will not be saved to scss file.

Here is my scss code

.SiteBuilder .e-row__select {
  position: relative;

  &:after {
    content: '';
  }

  select {
    border-radius: 4px;
  }
}


问:
Informatica Looping
I am looking for information on looping in Informatica. Specifically, I need to check if a source table has been loaded, if it has, move to next step, if not wait X minutes and check the status table again.  I would prefer direction to a place I can learn this on my own, but I need to confirm this is even possible as I have not found anything on my google searches.</p>

答:
In general, looping is not supported in Informatica PowerCenter.

One way is to use scripts, as discussed by Koushik.

Another way to do that is to have a Continuously Running Workflow with a timer. This is configurable on Scheduler tab of your workflow:

Such configuration makes the workflow start again right after it succeeds. Over and over again.

Workflow would look like:

```<code>Start -> s_check_source -> Decision -> timer
                                   |-> s_do_other_stuff -> timer
</code>```

This way it will check source. Then if it has not been loaded trigger the timer. Thet it will succeed and get triggered again.
If source turns out to be loaded, it will trigger the other session, complete and probably you'd need another timer here to wait till next day. Or basically till whenever you'd like the workflow to be triggered again.

Title: Informatica Looping

Body:
In general, looping is not supported in Informatica PowerCenter.

One way is to use scripts, as discussed by Koushik.

Another way to do that is to have a Continuously Running Workflow with a timer. This is configurable on Scheduler tab of your workflow:

Such configuration makes the workflow start again right after it succeeds. Over and over again.

Workflow would look like:

Start -> s_check_source -> Decision -> timer
                                   |-> s_do_other_stuff -> timer

This way it will check source. Then if it has not been loaded trigger the timer. Thet it will succeed and get triggered again.
If source turns out to be loaded, it will trigger the other session, complete and probably you'd need another timer here to wait till next day. Or basically till whenever you'd like the workflow to be triggered again.


问:
Why does Rust require Copy and Clone traits for simple enum
The following code will not compile unless Copy and Clone traits are derived in the enum. Why is this a requirement given that the enum is basically an i8 and according to the documentation, integers automatically implement the Copy trait? Related to this, since the size of MyEnum should be well known at compile time, shouldn't it go onto the stack? Doesn't the Clone trait imply that it goes on the heap?

#[derive(Debug, Copy, Clone)]
#[repr(i8)]
enum MyEnum {
    Some1,
}

fn main() {
    let x = MyEnum::Some1;
    let y = x;
    println!("x={:?} y={:?}", x, y);
}
```

答:
Clone has nothing to do with the heap. Clone does not imply heap-allocated for any type, be they structs, enums, and whether they have a #[repr] attribute or not. Clone is just a normal trait.

And traits aren't implemented automatically, ever, because when writing a library, this would be an implicit part of your public interface. That is, an type could be implicitly, and unexpectedly, Clone without the library author intending to make it Clone. This limits how the type could change in the future, and the library author might inadvertently break their public interface by changing the content of the type and losing that implicit trait implementation. Rust always prefers explicitness over hidden things.


问:
How to access pristine prop of reduxForm from inside the Redux state?
I use multiple instances of redux-form's Field inside my form with TextField of redux-form-material-ui as a renderable component:

```<code><Field
     component={TextField}
     floatingLabelText='Title:'
     name='title'
/>
</code>```

When a component that the form resides in is being wrapped with reduxForm(), we get props.pristine, props.dirty etc inside this component.

However, I want to perform some action, depending on the value of pristine, in another non-reduxForm component OR Redux state, but I am unable to do so.

I tried passing it as a prop to Field:

```<code><Field
    component={TextField}
    floatingLabelText='Title:'
    name='title'
    pristine={props.pristine}
/>
</code>```

But pristine property still does not appear neither as a prop inside state.form.formName, nor as a prop
inside state.form.formName.registeredFields.title:

Question:

Is there a way to get pristine property of my form inside another component or inside redux state?

答:
To access the prestine prop inside another component:

If you use Class based component:

Import all necessary stuff:

```<code>Import { connect } from "react-redux";
Import { isPristine } from "redux-form";
</code>```

Inside your mapStateToProps function:

```<code>const mapStateToProps = state => ({
  pristine: isPristine('yourFormName')(state), // Checks whole form
  pristineField: isPristine('yourFormName')(state, ["fieldName"]), // Checks particular field
});

connect(mapStateToProps, mapDispatchToProps)(YourFormComponent)
</code>```

If you use Functional based component:

Import all necessary stuff:

```<code>import { useSelector } from "react-redux";
import { isPristine } from "redux-form";
</code>```

Inside the functional component:

```<code>const pristine = useSelector((state) => isPristine("formName")(state));
</code>```

You can see all available selectors that redux-form provides here

Body:
I use multiple instances of redux-form's Field inside my form with TextField of redux-form-material-ui as a renderable component:

<Field
     component={TextField}
     floatingLabelText='Title:'
     name='title'
/>

When a component that the form resides in is being wrapped with reduxForm(), we get props.pristine, props.dirty etc inside this component.

However, I want to perform some action, depending on the value of pristine, in another non-reduxForm component OR Redux state, but I am unable to do so.

I tried passing it as a prop to Field:

<Field
    component={TextField}
    floatingLabelText='Title:'
    name='title'
    pristine={props.pristine}
/>

But pristine property still does not appear neither as a prop inside state.form.formName, nor as a prop
inside state.form.formName.registeredFields.title:

Question:

Is there a way to get pristine property of my form inside another component or inside redux state?

Body:
To access the prestine prop inside another component:

If you use Class based component:

Import all necessary stuff:

Import { connect } from "react-redux";
Import { isPristine } from "redux-form";

Inside your mapStateToProps function:

const mapStateToProps = state => ({
  pristine: isPristine('yourFormName')(state), // Checks whole form
  pristineField: isPristine('yourFormName')(state, ["fieldName"]), // Checks particular field
});

connect(mapStateToProps, mapDispatchToProps)(YourFormComponent)

If you use Functional based component:

Import all necessary stuff:

import { useSelector } from "react-redux";
import { isPristine } from "redux-form";

Inside the functional component:

const pristine = useSelector((state) => isPristine("formName")(state));

You can see all available selectors that redux-form provides here


问:
How do I read the image currently on the framebuffer in Qt/C?
Is there any way I can read the content of the framebuffer in Qt or anyway in C? I read it is possible to write the content of /dev/fb0 to a file and then load it. But is it possible to avoid saving it to memory and simply copy to a new memory location to use in Qt?
Thanks!</p>

答:
The ordinary Qt distribution is not likely to have special support for reading a framebuffer on Linux.  It layers on top of X11 and is trying to provide cross-platform capability (as things like /dev/fb0 won't have meaning on Windows, for instance).  So you would use higher level abstractions, such as the QPixmap::grabWindow() that @BerkDemirkir points out...probably a lot of hops through layers before the framebuffer.

(Note: If you are writing an ordinary cross platform Qt app intended to run in a windowed environment, that's certainly the route you want to go for a simple screen capture task!!)

On the other hand, Qt/Embedded is designed for Linux and to work with the QWS instead of X11.  The mindset is that there's no windowing system and your app owns the whole screen.  It writes directly to the framebuffer through a QScreen object, which has a base() method that can actually give you a pointer to the underlying memory:

http://doc.qt.nokia.com/4.7-snapshot/qscreen.html#base

Those are probably the only "Qt" ways to do these kinds of things.  If you want an API instead of going through to /dev/fb0 directly you might investigate something like EZFB.  (I didn't dig deep enough to know if it's useful or not, just found it with a query something like "linux framebuffer API")

http://freshmeat.net/projects/ezfb/


问:
Is there an option to change view of pagerAdapter in onTouchListener?
I've created a PagerAdapter class which implements View.OnTouchListener. In this class I have an ImageView that is setOnTouchListener to the implemented listener. Problem is that I tried to change the size or image of that ImageView but it won't change when touched. However the click is triggered and if I add something other than view change it will run it. The class where this is used only uses this, all changes are made here.

There are no errors popping in console nor warnings in code.

(apart from the clickAccessibility which shouldn't be responsible - I've tested it with performClicks in code and it behaved the same)

And so is there an option to change view of pagerAdapter in onTouchListener? ..if not is there a different way to do the thing I am trying to make here differently?
(please provide an example)

Thanks for any help in advance.

```<code>public class SliderAdapter extends PagerAdapter implements View.OnTouchListener{

private ImageView infoIcon;

@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {

   layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   View view = layoutInflater.inflate(R.layout.nutrition_recipe_layout, container, false);

   infoIcon = view.findViewById(R.id.mainInfoIconButton);
   infoIcon.setOnTouchListener(this);

   container.addView(view);

   return view;
}

@Override
public boolean onTouch(View view, MotionEvent event) {
    if (view.getId() == R.id.mainInfoIconButton) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
             LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,44,view.getResources().getDisplayMetrics()),
                        (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,44,view.getResources().getDisplayMetrics()));
             infoIcon.setLayoutParams(params);
             infoIcon.setImageResource(R.drawable.icon_info);

             return true;
         } else if (event.getAction() == MotionEvent.ACTION_UP) {
             LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,48,view.getResources().getDisplayMetrics()),
                        (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,48,view.getResources().getDisplayMetrics()));
             infoIcon.setLayoutParams(params);
             infoIcon.setImageResource(R.drawable.icon_info);

             Log.i("MTAG", "Click Triggered"); //this gets printed in console

             return true;
         }
       return false;
    }

return false;
}

</code>```

答:
There is no need to put ImageView infoIcon; outside the method.

```<code>public class SliderAdapter extends PagerAdapter implements View.OnTouchListener {

    LayoutInflater layoutInflater;
    Context context;

    public SliderAdapter(Context context) {
        this.context = context;
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    public int getCount() {
        return 2;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {

        View view = layoutInflater.inflate(R.layout.nutrition_recipe_layout, container, false);

        ImageView infoIcon = view.findViewById(R.id. mainInfoIconButton);
        infoIcon.setOnTouchListener(this);

        container.addView(view);

        return view;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        if (view.getId() == R.id.mainInfoIconButton) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();

                params.width = dp2px(context, 120);
                params.height = dp2px(context, 120);
                view.setLayoutParams(params);

                return true;
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
                params.width = dp2px(context, 100);
                params.height = dp2px(context, 100);
                view.setLayoutParams(params);

                LogUtil.i("MTAG", "Click Triggered"); //this gets printed in console

                return true;
            }
            return false;
        }

        return false;
    }

    private int dp2px(Context context, int value) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, context.getResources().getDisplayMetrics());
    }

}
</code>```

Body:
I've created a PagerAdapter class which implements View.OnTouchListener. In this class I have an ImageView that is setOnTouchListener to the implemented listener. Problem is that I tried to change the size or image of that ImageView but it won't change when touched. However the click is triggered and if I add something other than view change it will run it. The class where this is used only uses this, all changes are made here.

There are no errors popping in console nor warnings in code.

(apart from the clickAccessibility which shouldn't be responsible - I've tested it with performClicks in code and it behaved the same)

And so is there an option to change view of pagerAdapter in onTouchListener? ..if not is there a different way to do the thing I am trying to make here differently?
(please provide an example)

Thanks for any help in advance.

public class SliderAdapter extends PagerAdapter implements View.OnTouchListener{

private ImageView infoIcon;

@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {

   layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   View view = layoutInflater.inflate(R.layout.nutrition_recipe_layout, container, false);

   infoIcon = view.findViewById(R.id.mainInfoIconButton);
   infoIcon.setOnTouchListener(this);

   container.addView(view);

   return view;
}

@Override
public boolean onTouch(View view, MotionEvent event) {
    if (view.getId() == R.id.mainInfoIconButton) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
             LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,44,view.getResources().getDisplayMetrics()),
                        (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,44,view.getResources().getDisplayMetrics()));
             infoIcon.setLayoutParams(params);
             infoIcon.setImageResource(R.drawable.icon_info);

             return true;
         } else if (event.getAction() == MotionEvent.ACTION_UP) {
             LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,48,view.getResources().getDisplayMetrics()),
                        (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,48,view.getResources().getDisplayMetrics()));
             infoIcon.setLayoutParams(params);
             infoIcon.setImageResource(R.drawable.icon_info);

             Log.i("MTAG", "Click Triggered"); //this gets printed in console

             return true;
         }
       return false;
    }

return false;
}

Body:
There is no need to put ImageView infoIcon; outside the method.

public class SliderAdapter extends PagerAdapter implements View.OnTouchListener {

    LayoutInflater layoutInflater;
    Context context;

    public SliderAdapter(Context context) {
        this.context = context;
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    public int getCount() {
        return 2;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {

        View view = layoutInflater.inflate(R.layout.nutrition_recipe_layout, container, false);

        ImageView infoIcon = view.findViewById(R.id. mainInfoIconButton);
        infoIcon.setOnTouchListener(this);

        container.addView(view);

        return view;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        if (view.getId() == R.id.mainInfoIconButton) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();

                params.width = dp2px(context, 120);
                params.height = dp2px(context, 120);
                view.setLayoutParams(params);

                return true;
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
                params.width = dp2px(context, 100);
                params.height = dp2px(context, 100);
                view.setLayoutParams(params);

                LogUtil.i("MTAG", "Click Triggered"); //this gets printed in console

                return true;
            }
            return false;
        }

        return false;
    }

    private int dp2px(Context context, int value) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, context.getResources().getDisplayMetrics());
    }

}


问:
VBA : Can child sub inherit properties from its parent sub
I am creating an Excel macro that populated as template PowerPoint slide deck with some charts from the workbook.

The act of copy and pasting a chart from Excel to PowerPoint takes a lot of lines of code, so I am trying to move this into a subroutine that I call from the main routine, to keep everything modular.  The below illustrates what I am trying to do.

To me, the only arguments that should vary for each call of the PasteChart subroutine is the name of the chart I am copying across (eg Figure1, Figure2, etc) and the placeholder position on the slide (2, 3, etc).  The slide number I want to define before calling the routines as I need to do other things to the slide as well.

To me, the arguments wb, pptApp, ppt, SlideNumber should be inherited from the main routine so that I don't have to keep passing them to the PasteChart subroutine.  Ie, these 4 arguments are going to be the same for all calls of the PasteChart subroutine.

But if I don't pass them as I have below, my macro won't work.

Is there a way to more elegantly structure the below subroutine?  Or in other words, how can I get the PasteChart subroutine to inherit the arguments wb, pptApp, ppt, SlideNumber from the main routine?

Parent Subroutine

```<code>Sub CreateSlideDeck()

    Set wb = ActiveWorkbook()

    Set pptApp = CreateObject("PowerPoint.Application")
    Set ppt = pptApp.Presentations.Open("D:\Template\Template.pptx", untitled:=msoTrue)

    SlideNumber = 3

    Call PasteChart("Figure1", 2, wb, pptApp, ppt, SlideNumber)
    Call PasteChart("Figure2", 3, wb, pptApp, ppt, SlideNumber)

End Sub
</code>```

Child Subroutine

```<code>Sub PasteChart(ChartName, Position, wb, pptApp, ppt, SlideNumber)

    wb.Sheets("Charts").ChartObjects(ChartName).Activate
    ActiveChart.ChartArea.Copy

    pptApp.Activate
    ppt.Slides(SlideNumber).Select
    ppt.Slides(SlideNumber).Shapes.Placeholders(Position).Select
    ppt.Windows(1).view.Paste

End Sub
</code>```

答:
You could use a configuration array - and then iterate:

Sub createSlideDeck()

Set wb = ActiveWorkbook()

Set pptApp = CreateObject("PowerPoint.Application")
Set ppt = pptApp.Presentations.Open("D:\Template\Template.pptx", untitled:=msoTrue)

Dim arr(3, 2)   'array that takes configuration of all charts
'Chartname | Position | Slidenumber
arr(0, 0) = "Figure1": arr(0, 1) = 2: arr(0, 2) = 3
arr(1, 0) = "Figure2": arr(1, 1) = 3: arr(1, 2) = 3
arr(2, 0) = "Figure3": arr(2, 1) = 4: arr(2, 2) = 3

Dim i As Long
For i = 0 To UBound(arr, 1)
    PasteChart arr(i, 0), arr(i, 1), wb, pptApp, ppt, arr(i, 2)
Next

End Sub

```

Body:
I am creating an Excel macro that populated as template PowerPoint slide deck with some charts from the workbook.

The act of copy and pasting a chart from Excel to PowerPoint takes a lot of lines of code, so I am trying to move this into a subroutine that I call from the main routine, to keep everything modular.  The below illustrates what I am trying to do.

To me, the only arguments that should vary for each call of the PasteChart subroutine is the name of the chart I am copying across (eg Figure1, Figure2, etc) and the placeholder position on the slide (2, 3, etc).  The slide number I want to define before calling the routines as I need to do other things to the slide as well.

To me, the arguments wb, pptApp, ppt, SlideNumber should be inherited from the main routine so that I don't have to keep passing them to the PasteChart subroutine.  Ie, these 4 arguments are going to be the same for all calls of the PasteChart subroutine.

But if I don't pass them as I have below, my macro won't work.

Is there a way to more elegantly structure the below subroutine?  Or in other words, how can I get the PasteChart subroutine to inherit the arguments wb, pptApp, ppt, SlideNumber from the main routine?

Parent Subroutine

Sub CreateSlideDeck()

    Set wb = ActiveWorkbook()

    Set pptApp = CreateObject("PowerPoint.Application")
    Set ppt = pptApp.Presentations.Open("D:\Template\Template.pptx", untitled:=msoTrue)

    SlideNumber = 3

    Call PasteChart("Figure1", 2, wb, pptApp, ppt, SlideNumber)
    Call PasteChart("Figure2", 3, wb, pptApp, ppt, SlideNumber)

End Sub

Child Subroutine

Sub PasteChart(ChartName, Position, wb, pptApp, ppt, SlideNumber)

    wb.Sheets("Charts").ChartObjects(ChartName).Activate
    ActiveChart.ChartArea.Copy

    pptApp.Activate
    ppt.Slides(SlideNumber).Select
    ppt.Slides(SlideNumber).Shapes.Placeholders(Position).Select
    ppt.Windows(1).view.Paste

End Sub


问:
Haskell fmt library not found
When I import the Haskell Fmt module, I get the information
"Could not find module 'Fmt'.
It is not a module in the current program, or in any known package".</p>
```<code>GHCi, version 9.2.1: https://www.haskell.org/ghc/  :? for help
ghci> :set -XOverloadedStrings
ghci> import Fmt

<no location info>: error:
Could not find module `Fmt'
It is not a module in the current program, or in any known package.
ghci>
</code>```

答:
Nowadays one uses cabal repl rather than ghci:

```<code>cabal repl --build-depends fmt
...
Prelude> :set -XOverloadedStrings
Prelude> import Fmt
Prelude Fmt> let (a, b, n) = ("foo", "bar", 25)
Prelude Fmt> ("Here are some words: "+|a|+", "+|b|+"\nAlso a number: "+|n|+"") :: String
"Here are some words: foo, bar\nAlso a number: 25"
</code>```

Title: Haskell fmt library not found

Body:
When I import the Haskell Fmt module, I get the information
"Could not find module 'Fmt'.
It is not a module in the current program, or in any known package".

GHCi, version 9.2.1: https://www.haskell.org/ghc/  :? for help
ghci> :set -XOverloadedStrings
ghci> import Fmt

<no location info>: error:
Could not find module `Fmt'
It is not a module in the current program, or in any known package.
ghci>

Body:
Nowadays one uses cabal repl rather than ghci:

cabal repl --build-depends fmt
...
Prelude> :set -XOverloadedStrings
Prelude> import Fmt
Prelude Fmt> let (a, b, n) = ("foo", "bar", 25)
Prelude Fmt> ("Here are some words: "+|a|+", "+|b|+"\nAlso a number: "+|n|+"") :: String
"Here are some words: foo, bar\nAlso a number: 25"


问:
Is there a way that I can return multiple columns from a subquery rather than repeating the subquery for each column? It works but takes too long

As you can see I'm trying to add 4 columns by repeating the subquery,
this works but takes too long to be useful. I tried to put all the
joins at the end but then I only get the records that have values in
[dbo.permit_terms] whereas I want all the records from [dbo.prd]. I hope this makes
sense and will be very grateful for an answer.

```<code>   SELECT WLC.name AS WELLCOMPL
    , WLC.id_subsidiary AS SUB
    , PD.Date
    , PD.days
    , PD.oil
    , PD.water
    , PD.gas
    , PD.interest
    , PD.operator
    , PD.comments
    , (
    SELECT PT.net_working_int_oil
        FROM dbo.prd AS P (NOLOCK)
            left JOIN dbo.wellbore_compl AS W WITH (NOLOCK) ON (P.id_subsidiary = W.id_subsidiary) AND (P.id_wellborecompl = W.id)
            left JOIN dbo.wellstring WITH (NOLOCK) ON W.id_wellstring = dbo.wellstring.id
            left JOIN dbo.wellbore wb WITH (NOLOCK) ON dbo.wellstring.id_wellbore = wb.id
            left JOIN dbo.wellbore_permit WP WITH (NOLOCK) ON wb.id = WP.id_wellbore
            left JOIN dbo.permit  WITH (NOLOCK) ON dbo.permit.id = WP.id_permit
            left JOIN dbo.permit_terms PT WITH (NOLOCK) ON dbo.permit.id = PT.id_permit
        where (p.[date] >= pt.start_date and p.[date] <=pt.end_date)
    --      AND W.[name] = WLC.[name]
            AND p.id = pd.id
            AND pd.id_subsidiary = w.id_subsidiary
            AND P.deletedAt Is Null
            AND W.deletedAt Is Null
            AND dbo.wellstring.deletedAt Is Null
            AND dbo.permit.deletedAt Is Null
            AND wb.deletedAt Is Null
            AND PT.deletedAt Is Null
    )
     as permit_interest
    , (
    SELECT PT.operator
        FROM dbo.prd AS P (NOLOCK)
            left JOIN dbo.wellbore_compl AS W WITH (NOLOCK) ON (P.id_subsidiary = W.id_subsidiary) AND (P.id_wellborecompl = W.id)
            left JOIN dbo.wellstring WITH (NOLOCK) ON W.id_wellstring = dbo.wellstring.id
            left JOIN dbo.wellbore wb WITH (NOLOCK) ON dbo.wellstring.id_wellbore = wb.id
            left JOIN dbo.wellbore_permit WP WITH (NOLOCK) ON wb.id = WP.id_wellbore
            left JOIN dbo.permit  WITH (NOLOCK) ON dbo.permit.id = WP.id_permit
            left JOIN dbo.permit_terms PT WITH (NOLOCK) ON dbo.permit.id = PT.id_permit
        where (p.[date] >= pt.start_date and p.[date] <=pt.end_date)
    --      AND W.[name] = WLC.[name]
            AND p.id = pd.id
            AND pd.id_subsidiary = w.id_subsidiary
            AND P.deletedAt Is Null
            AND W.deletedAt Is Null
            AND dbo.wellstring.deletedAt Is Null
            AND dbo.permit.deletedAt Is Null
            AND wb.deletedAt Is Null
            AND PT.deletedAt Is Null
    )
     as permit_operator
    , (
    SELECT pd.oil*PT.net_working_int_oil/100
        FROM dbo.prd AS P (NOLOCK)
            left JOIN dbo.wellbore_compl AS W WITH (NOLOCK) ON (P.id_subsidiary = W.id_subsidiary) AND (P.id_wellborecompl = W.id)
            left JOIN dbo.wellstring WITH (NOLOCK) ON W.id_wellstring = dbo.wellstring.id
            left JOIN dbo.wellbore wb WITH (NOLOCK) ON dbo.wellstring.id_wellbore = wb.id
            left JOIN dbo.wellbore_permit WP WITH (NOLOCK) ON wb.id = WP.id_wellbore
            left JOIN dbo.permit  WITH (NOLOCK) ON dbo.permit.id = WP.id_permit
            left JOIN dbo.permit_terms PT WITH (NOLOCK) ON dbo.permit.id = PT.id_permit
        where (p.[date] >= pt.start_date and p.[date] <=pt.end_date)
    --      AND W.[name] = WLC.[name]
            AND p.id = pd.id
            AND pd.id_subsidiary = w.id_subsidiary
            AND P.deletedAt Is Null
            AND W.deletedAt Is Null
            AND dbo.wellstring.deletedAt Is Null
            AND dbo.permit.deletedAt Is Null
            AND wb.deletedAt Is Null
            AND PT.deletedAt Is Null
    )
     as Oil_net
    , (
    SELECT pd.gas*PT.net_working_int_gas/100
        FROM dbo.prd AS P (NOLOCK)
            left JOIN dbo.wellbore_compl AS W WITH (NOLOCK) ON (P.id_subsidiary = W.id_subsidiary) AND (P.id_wellborecompl = W.id)
            left JOIN dbo.wellstring WITH (NOLOCK) ON W.id_wellstring = dbo.wellstring.id
            left JOIN dbo.wellbore wb WITH (NOLOCK) ON dbo.wellstring.id_wellbore = wb.id
            left JOIN dbo.wellbore_permit WP WITH (NOLOCK) ON wb.id = WP.id_wellbore
            left JOIN dbo.permit  WITH (NOLOCK) ON dbo.permit.id = WP.id_permit
            left JOIN dbo.permit_terms PT WITH (NOLOCK) ON dbo.permit.id = PT.id_permit
        where (p.[date] >= pt.start_date and p.[date] <=pt.end_date)
    --      AND W.[name] = WLC.[name]
            AND p.id = pd.id
            AND pd.id_subsidiary = w.id_subsidiary
            AND P.deletedAt Is Null
            AND W.deletedAt Is Null
            AND dbo.wellstring.deletedAt Is Null
            AND dbo.permit.deletedAt Is Null
            AND wb.deletedAt Is Null
            AND PT.deletedAt Is Null
    )
    as Gas_net
    FROM (dbo.prd AS PD
    INNER JOIN dbo.wellbore_compl AS WLC ON (PD.id_subsidiary = WLC.id_subsidiary) AND (PD.id_wellborecompl = WLC.id))
    WHERE
     PD.deletedAt Is Null
    AND WLC.deletedAt Is Null
</code>```

答:
This should get you close

```<code>Select WELLCOMPL       = WLC.name
     , SUB             = WLC.id_subsidiary
     , PD.Date
     , PD.days
     , PD.oil
     , PD.water
     , PD.gas
     , PD.interest
     , PD.operator
     , PD.comments
     , permit_interest = tt.net_working_int_oil
     , permit_operator = tt.operator
     , Oil_net         = PD.oil * tt.net_working_int_oil / 100
     , Gas_net         = PD.gas * tt.net_working_int_gas / 100
  From dbo.prd                                  PD With (NoLock)
 Inner Join dbo.wellbore_compl                 WLC With (NoLock) On PD.id_subsidiary = WLC.id_subsidiary
                                                                And pd.id_wellborecompl = WLC.id

 Cross Apply (Select PT.operator
                   , PT.net_working_int_oil
                   , PT.net_working_int_gas
                From dbo.wellstring             ws With (NoLock)
               Inner Join dbo.wellbore          wb With (NoLock) On wb.id = ws.id_wellbore
               Inner Join dbo.wellbore_permit   WP With (NoLock) On WP.id_wellbore = wb.id
               Inner Join dbo.permit             p With (NoLock) On p.id = WP.id_permit
               Inner Join dbo.permit_terms      PT With (NoLock) On PT.id_permit = p.id
         Where ws.id = WLC.id_wellstring        -- this ties us back to the outer query
           And PD.[date] >= pt.Start_Date       -- this ties back to date on outer PD table
           And pd.[date] <= pt.end_date         -- this ties back to date on outer PD table
           And ws.deletedAt Is Null
           And wb.deletedAt Is Null
           And p.deletedAt Is Null
           And PT.deletedAt Is Null
             )                                  tt

 Where PD.deletedAt Is Null
   And WLC.deletedAt Is Null;
</code>```

As already stated - remove NOLOCK hints unless you are sure that you understand the risks associated with using it.

Now you can add any additional columns needed from the permit (PT) table and define your calculations based off those values.  This assumes you will always have related values and are only interested in showing those that actually have values.

If you need to show all, even if there is no wellstring, wellbore, permit, etc... then change the cross apply to an outer apply and you will get NULL values for all of your calculations.

Body:
As you can see I'm trying to add 4 columns by repeating the subquery,
this works but takes too long to be useful. I tried to put all the
joins at the end but then I only get the records that have values in
[dbo.permit_terms] whereas I want all the records from [dbo.prd]. I hope this makes
sense and will be very grateful for an answer.

   SELECT WLC.name AS WELLCOMPL
    , WLC.id_subsidiary AS SUB
    , PD.Date
    , PD.days
    , PD.oil
    , PD.water
    , PD.gas
    , PD.interest
    , PD.operator
    , PD.comments
    , (
    SELECT PT.net_working_int_oil
        FROM dbo.prd AS P (NOLOCK)
            left JOIN dbo.wellbore_compl AS W WITH (NOLOCK) ON (P.id_subsidiary = W.id_subsidiary) AND (P.id_wellborecompl = W.id)
            left JOIN dbo.wellstring WITH (NOLOCK) ON W.id_wellstring = dbo.wellstring.id
            left JOIN dbo.wellbore wb WITH (NOLOCK) ON dbo.wellstring.id_wellbore = wb.id
            left JOIN dbo.wellbore_permit WP WITH (NOLOCK) ON wb.id = WP.id_wellbore
            left JOIN dbo.permit  WITH (NOLOCK) ON dbo.permit.id = WP.id_permit
            left JOIN dbo.permit_terms PT WITH (NOLOCK) ON dbo.permit.id = PT.id_permit
        where (p.[date] >= pt.start_date and p.[date] <=pt.end_date)
    --      AND W.[name] = WLC.[name]
            AND p.id = pd.id
            AND pd.id_subsidiary = w.id_subsidiary
            AND P.deletedAt Is Null
            AND W.deletedAt Is Null
            AND dbo.wellstring.deletedAt Is Null
            AND dbo.permit.deletedAt Is Null
            AND wb.deletedAt Is Null
            AND PT.deletedAt Is Null
    )
     as permit_interest
    , (
    SELECT PT.operator
        FROM dbo.prd AS P (NOLOCK)
            left JOIN dbo.wellbore_compl AS W WITH (NOLOCK) ON (P.id_subsidiary = W.id_subsidiary) AND (P.id_wellborecompl = W.id)
            left JOIN dbo.wellstring WITH (NOLOCK) ON W.id_wellstring = dbo.wellstring.id
            left JOIN dbo.wellbore wb WITH (NOLOCK) ON dbo.wellstring.id_wellbore = wb.id
            left JOIN dbo.wellbore_permit WP WITH (NOLOCK) ON wb.id = WP.id_wellbore
            left JOIN dbo.permit  WITH (NOLOCK) ON dbo.permit.id = WP.id_permit
            left JOIN dbo.permit_terms PT WITH (NOLOCK) ON dbo.permit.id = PT.id_permit
        where (p.[date] >= pt.start_date and p.[date] <=pt.end_date)
    --      AND W.[name] = WLC.[name]
            AND p.id = pd.id
            AND pd.id_subsidiary = w.id_subsidiary
            AND P.deletedAt Is Null
            AND W.deletedAt Is Null
            AND dbo.wellstring.deletedAt Is Null
            AND dbo.permit.deletedAt Is Null
            AND wb.deletedAt Is Null
            AND PT.deletedAt Is Null
    )
     as permit_operator
    , (
    SELECT pd.oil*PT.net_working_int_oil/100
        FROM dbo.prd AS P (NOLOCK)
            left JOIN dbo.wellbore_compl AS W WITH (NOLOCK) ON (P.id_subsidiary = W.id_subsidiary) AND (P.id_wellborecompl = W.id)
            left JOIN dbo.wellstring WITH (NOLOCK) ON W.id_wellstring = dbo.wellstring.id
            left JOIN dbo.wellbore wb WITH (NOLOCK) ON dbo.wellstring.id_wellbore = wb.id
            left JOIN dbo.wellbore_permit WP WITH (NOLOCK) ON wb.id = WP.id_wellbore
            left JOIN dbo.permit  WITH (NOLOCK) ON dbo.permit.id = WP.id_permit
            left JOIN dbo.permit_terms PT WITH (NOLOCK) ON dbo.permit.id = PT.id_permit
        where (p.[date] >= pt.start_date and p.[date] <=pt.end_date)
    --      AND W.[name] = WLC.[name]
            AND p.id = pd.id
            AND pd.id_subsidiary = w.id_subsidiary
            AND P.deletedAt Is Null
            AND W.deletedAt Is Null
            AND dbo.wellstring.deletedAt Is Null
            AND dbo.permit.deletedAt Is Null
            AND wb.deletedAt Is Null
            AND PT.deletedAt Is Null
    )
     as Oil_net
    , (
    SELECT pd.gas*PT.net_working_int_gas/100
        FROM dbo.prd AS P (NOLOCK)
            left JOIN dbo.wellbore_compl AS W WITH (NOLOCK) ON (P.id_subsidiary = W.id_subsidiary) AND (P.id_wellborecompl = W.id)
            left JOIN dbo.wellstring WITH (NOLOCK) ON W.id_wellstring = dbo.wellstring.id
            left JOIN dbo.wellbore wb WITH (NOLOCK) ON dbo.wellstring.id_wellbore = wb.id
            left JOIN dbo.wellbore_permit WP WITH (NOLOCK) ON wb.id = WP.id_wellbore
            left JOIN dbo.permit  WITH (NOLOCK) ON dbo.permit.id = WP.id_permit
            left JOIN dbo.permit_terms PT WITH (NOLOCK) ON dbo.permit.id = PT.id_permit
        where (p.[date] >= pt.start_date and p.[date] <=pt.end_date)
    --      AND W.[name] = WLC.[name]
            AND p.id = pd.id
            AND pd.id_subsidiary = w.id_subsidiary
            AND P.deletedAt Is Null
            AND W.deletedAt Is Null
            AND dbo.wellstring.deletedAt Is Null
            AND dbo.permit.deletedAt Is Null
            AND wb.deletedAt Is Null
            AND PT.deletedAt Is Null
    )
    as Gas_net
    FROM (dbo.prd AS PD
    INNER JOIN dbo.wellbore_compl AS WLC ON (PD.id_subsidiary = WLC.id_subsidiary) AND (PD.id_wellborecompl = WLC.id))
    WHERE
     PD.deletedAt Is Null
    AND WLC.deletedAt Is Null

Body:
This should get you close

Select WELLCOMPL       = WLC.name
     , SUB             = WLC.id_subsidiary
     , PD.Date
     , PD.days
     , PD.oil
     , PD.water
     , PD.gas
     , PD.interest
     , PD.operator
     , PD.comments
     , permit_interest = tt.net_working_int_oil
     , permit_operator = tt.operator
     , Oil_net         = PD.oil * tt.net_working_int_oil / 100
     , Gas_net         = PD.gas * tt.net_working_int_gas / 100
  From dbo.prd                                  PD With (NoLock)
 Inner Join dbo.wellbore_compl                 WLC With (NoLock) On PD.id_subsidiary = WLC.id_subsidiary
                                                                And pd.id_wellborecompl = WLC.id

 Cross Apply (Select PT.operator
                   , PT.net_working_int_oil
                   , PT.net_working_int_gas
                From dbo.wellstring             ws With (NoLock)
               Inner Join dbo.wellbore          wb With (NoLock) On wb.id = ws.id_wellbore
               Inner Join dbo.wellbore_permit   WP With (NoLock) On WP.id_wellbore = wb.id
               Inner Join dbo.permit             p With (NoLock) On p.id = WP.id_permit
               Inner Join dbo.permit_terms      PT With (NoLock) On PT.id_permit = p.id
         Where ws.id = WLC.id_wellstring        -- this ties us back to the outer query
           And PD.[date] >= pt.Start_Date       -- this ties back to date on outer PD table
           And pd.[date] <= pt.end_date         -- this ties back to date on outer PD table
           And ws.deletedAt Is Null
           And wb.deletedAt Is Null
           And p.deletedAt Is Null
           And PT.deletedAt Is Null
             )                                  tt

 Where PD.deletedAt Is Null
   And WLC.deletedAt Is Null;

As already stated - remove NOLOCK hints unless you are sure that you understand the risks associated with using it.

Now you can add any additional columns needed from the permit (PT) table and define your calculations based off those values.  This assumes you will always have related values and are only interested in showing those that actually have values.

If you need to show all, even if there is no wellstring, wellbore, permit, etc... then change the cross apply to an outer apply and you will get NULL values for all of your calculations.


问:
Laravel Sail with Laravel Nova: ...vendor/laravel/nova/src/NovaCoreServiceProvider.php not found
I recently tried to deploy my laravel Nova project in docker, and my search brought me to laravel sail.

So having the default docker-compose.yml file included in the project, I ran the 'sail up' command in my project working directory

./vendor/bin/sail up

This command downloaded and setup the images specified in the docker-compose.yml file

```<code>version: '3'
services:
    laravel.test:
        build:
            context: ./vendor/laravel/sail/runtimes/8.1
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
        image: sail-8.1/app
        extra_hosts:
            - 'host.docker.internal:host-gateway'
        ports:
            - '${APP_PORT:-80}:80'
        environment:
            WWWUSER: '${WWWUSER}'
            LARAVEL_SAIL: 1
            XDEBUG_MODE: '${SAIL_XDEBUG_MODE:-off}'
            XDEBUG_CONFIG: '${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}'
        volumes:
            - '.:/var/www/html'
        networks:
            - sail
        depends_on:
            - mysql
            - redis
            - meilisearch
            - selenium
    mysql:
        image: 'mysql/mysql-server:8.0'
        ports:
            - '${FORWARD_DB_PORT:-3306}:3306'
        environment:
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ROOT_HOST: "%"
            MYSQL_DATABASE: '${DB_DATABASE}'
            MYSQL_USER: '${DB_USERNAME}'
            MYSQL_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ALLOW_EMPTY_PASSWORD: 1
        volumes:
            - 'sailmysql:/var/lib/mysql'
        networks:
            - sail
        healthcheck:
            test: ["CMD", "mysqladmin", "ping", "-p${DB_PASSWORD}"]
            retries: 3
            timeout: 5s
    redis:
        image: 'redis:alpine'
        ports:
            - '${FORWARD_REDIS_PORT:-6379}:6379'
        volumes:
            - 'sailredis:/data'
        networks:
            - sail
        healthcheck:
            test: ["CMD", "redis-cli", "ping"]
            retries: 3
            timeout: 5s
    meilisearch:
        image: 'getmeili/meilisearch:latest'
        platform: linux/x86_64
        ports:
            - '${FORWARD_MEILISEARCH_PORT:-7700}:7700'
        volumes:
            - 'sailmeilisearch:/data.ms'
        networks:
            - sail
        healthcheck:
            test: ["CMD", "wget", "--no-verbose", "--spider",  "http://localhost:7700/health"]
            retries: 3
            timeout: 5s
    mailhog:
        image: 'mailhog/mailhog:latest'
        ports:
            - '${FORWARD_MAILHOG_PORT:-1025}:1025'
            - '${FORWARD_MAILHOG_DASHBOARD_PORT:-8025}:8025'
        networks:
            - sail
    selenium:
        image: 'selenium/standalone-chrome'
        volumes:
            - '/dev/shm:/dev/shm'
        networks:
            - sail
networks:
    sail:
        driver: bridge
volumes:
</code>```

Then created and launched docker containers from the images

```<code>Creating network "my-project_sail" with driver "bridge"
Creating my-project_meilisearch_1 ... done
Creating my-project_redis_1       ... done
Creating my-project_selenium_1    ... done
Creating my-project_mailhog_1     ... done
Creating my-project_mysql_1       ... done
Creating my-project_laravel.test_1 ... done
</code>```

All the containers were executed successfully except for the my-project_laravel.test_1 container which looped continuously displaying the following error

```<code>laravel.test_1  | 2022-01-01 09:54:41,943 INFO success: php entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
laravel.test_1  |
laravel.test_1  | In ClassLoader.php line 571:
laravel.test_1  |
laravel.test_1  |   include(/var/www/html/vendor/composer/../laravel/nova/src/NovaCoreServicePr
laravel.test_1  |   ovider.php): Failed to open stream: No such file or directory
laravel.test_1  |
laravel.test_1  |
laravel.test_1  | 2022-01-01 09:54:45,682 INFO exited: php (exit status 1; not expected)
laravel.test_1  | 2022-01-01 09:54:46,691 INFO spawned: 'php' with pid 26
laravel.test_1  | 2022-01-01 09:54:47,693 INFO success: php entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
laravel.test_1  |
laravel.test_1  | In ClassLoader.php line 571:
laravel.test_1  |
laravel.test_1  |   include(/var/www/html/vendor/composer/../laravel/nova/src/NovaCoreServicePr
laravel.test_1  |   ovider.php): Failed to open stream: No such file or directory
laravel.test_1  |
laravel.test_1  |
laravel.test_1  | 2022-01-01 09:54:51,307 INFO exited: php (exit status 1; not expected)
laravel.test_1  | 2022-01-01 09:54:52,322 INFO spawned: 'php' with pid 33
</code>```

What I've tried so far

I executed the below command to actually display the content of the '/var/www/html/vendor/laravel' directory within the container

```<code>$ docker exec my-project_laravel.test_1 ls /var/www/html/vendor/laravel/
framework
nova
sail
sanctum
serializable-closure
tinker
ui
</code>```

But listing the contents of the nova directory displayed above yields "No such file or directory"

```<code>$ docker exec my-project_laravel.test_1 ls /var/www/html/vendor/laravel/nova/
ls: cannot access '/var/www/html/vendor/laravel/nova/': No such file or directory
</code>```

After inspecting the vendor/laravel directory in the project on the host machine (Windows 11), I discovered the nova directory's icon indicates that it's a shortcut but when I open its properties, I don't see the shortcut tab. And the folder has content

This is the content of the vendor/laravel directory

Any help from this point would be great

答:
I ran into the same problem and in the docs I found this command:

```<code>docker run --rm \
    -u "$(id -u):$(id -g)" \
    -v $(pwd):/var/www/html \
    -w /var/www/html \
    laravelsail/php81-composer:latest \
    composer install --ignore-platform-reqs
</code>```

Replace the php version number with yours than run this command in wsl.

Body:
I recently tried to deploy my laravel Nova project in docker, and my search brought me to laravel sail.

So having the default docker-compose.yml file included in the project, I ran the 'sail up' command in my project working directory

./vendor/bin/sail up

This command downloaded and setup the images specified in the docker-compose.yml file

version: '3'
services:
    laravel.test:
        build:
            context: ./vendor/laravel/sail/runtimes/8.1
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
        image: sail-8.1/app
        extra_hosts:
            - 'host.docker.internal:host-gateway'
        ports:
            - '${APP_PORT:-80}:80'
        environment:
            WWWUSER: '${WWWUSER}'
            LARAVEL_SAIL: 1
            XDEBUG_MODE: '${SAIL_XDEBUG_MODE:-off}'
            XDEBUG_CONFIG: '${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}'
        volumes:
            - '.:/var/www/html'
        networks:
            - sail
        depends_on:
            - mysql
            - redis
            - meilisearch
            - selenium
    mysql:
        image: 'mysql/mysql-server:8.0'
        ports:
            - '${FORWARD_DB_PORT:-3306}:3306'
        environment:
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ROOT_HOST: "%"
            MYSQL_DATABASE: '${DB_DATABASE}'
            MYSQL_USER: '${DB_USERNAME}'
            MYSQL_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ALLOW_EMPTY_PASSWORD: 1
        volumes:
            - 'sailmysql:/var/lib/mysql'
        networks:
            - sail
        healthcheck:
            test: ["CMD", "mysqladmin", "ping", "-p${DB_PASSWORD}"]
            retries: 3
            timeout: 5s
    redis:
        image: 'redis:alpine'
        ports:
            - '${FORWARD_REDIS_PORT:-6379}:6379'
        volumes:
            - 'sailredis:/data'
        networks:
            - sail
        healthcheck:
            test: ["CMD", "redis-cli", "ping"]
            retries: 3
            timeout: 5s
    meilisearch:
        image: 'getmeili/meilisearch:latest'
        platform: linux/x86_64
        ports:
            - '${FORWARD_MEILISEARCH_PORT:-7700}:7700'
        volumes:
            - 'sailmeilisearch:/data.ms'
        networks:
            - sail
        healthcheck:
            test: ["CMD", "wget", "--no-verbose", "--spider",  "http://localhost:7700/health"]
            retries: 3
            timeout: 5s
    mailhog:
        image: 'mailhog/mailhog:latest'
        ports:
            - '${FORWARD_MAILHOG_PORT:-1025}:1025'
            - '${FORWARD_MAILHOG_DASHBOARD_PORT:-8025}:8025'
        networks:
            - sail
    selenium:
        image: 'selenium/standalone-chrome'
        volumes:
            - '/dev/shm:/dev/shm'
        networks:
            - sail
networks:
    sail:
        driver: bridge
volumes:

Then created and launched docker containers from the images

Creating network "my-project_sail" with driver "bridge"
Creating my-project_meilisearch_1 ... done
Creating my-project_redis_1       ... done
Creating my-project_selenium_1    ... done
Creating my-project_mailhog_1     ... done
Creating my-project_mysql_1       ... done
Creating my-project_laravel.test_1 ... done

All the containers were executed successfully except for the my-project_laravel.test_1 container which looped continuously displaying the following error

laravel.test_1  | 2022-01-01 09:54:41,943 INFO success: php entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
laravel.test_1  |
laravel.test_1  | In ClassLoader.php line 571:
laravel.test_1  |
laravel.test_1  |   include(/var/www/html/vendor/composer/../laravel/nova/src/NovaCoreServicePr
laravel.test_1  |   ovider.php): Failed to open stream: No such file or directory
laravel.test_1  |
laravel.test_1  |
laravel.test_1  | 2022-01-01 09:54:45,682 INFO exited: php (exit status 1; not expected)
laravel.test_1  | 2022-01-01 09:54:46,691 INFO spawned: 'php' with pid 26
laravel.test_1  | 2022-01-01 09:54:47,693 INFO success: php entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
laravel.test_1  |
laravel.test_1  | In ClassLoader.php line 571:
laravel.test_1  |
laravel.test_1  |   include(/var/www/html/vendor/composer/../laravel/nova/src/NovaCoreServicePr
laravel.test_1  |   ovider.php): Failed to open stream: No such file or directory
laravel.test_1  |
laravel.test_1  |
laravel.test_1  | 2022-01-01 09:54:51,307 INFO exited: php (exit status 1; not expected)
laravel.test_1  | 2022-01-01 09:54:52,322 INFO spawned: 'php' with pid 33

What I've tried so far

I executed the below command to actually display the content of the '/var/www/html/vendor/laravel' directory within the container

$ docker exec my-project_laravel.test_1 ls /var/www/html/vendor/laravel/
framework
nova
sail
sanctum
serializable-closure
tinker
ui

But listing the contents of the nova directory displayed above yields "No such file or directory"

$ docker exec my-project_laravel.test_1 ls /var/www/html/vendor/laravel/nova/
ls: cannot access '/var/www/html/vendor/laravel/nova/': No such file or directory

After inspecting the vendor/laravel directory in the project on the host machine (Windows 11), I discovered the nova directory's icon indicates that it's a shortcut but when I open its properties, I don't see the shortcut tab. And the folder has content

This is the content of the vendor/laravel directory

Any help from this point would be great

Body:
I ran into the same problem and in the docs I found this command:

docker run --rm \
    -u "$(id -u):$(id -g)" \
    -v $(pwd):/var/www/html \
    -w /var/www/html \
    laravelsail/php81-composer:latest \
    composer install --ignore-platform-reqs

Replace the php version number with yours than run this command in wsl.


问:
Save a big list of lists in python 3 to a binary file
I have a big list of lists like this in Python 3:

```<code>array = [[262,231],[123,222],[237272,292]...]
</code>```

I want to save this in binary in python
I tried this:

```<code>output = open("pratica3.dat", "wb")
inbytes = bytes(array)
output.write(inbytes)
</code>```

But this gives an error:
TypeError: 'list' object cannot be interpreted as an integer

And if I try to run through the list and save, this gives me annother error of out of range 256

答:
Try with pickle it will work fine

import pickle  # import pickle

fptr = open("filename", "wb")  # open file in write binary mode
pickle.dump(my_list, ftpt)  # dump list data into file
fptr.close()  # close file pointer

fptr = open("filename", "rb")  # open file in read binary mode
test_list = pickle.load(fptr)  # read binary data from file and store in list
print(test_list)  # print the data
fptr.close()
```

Body:
I have a big list of lists like this in Python 3:

array = [[262,231],[123,222],[237272,292]...]

I want to save this in binary in python
I tried this:

output = open("pratica3.dat", "wb")
inbytes = bytes(array)
output.write(inbytes)

But this gives an error:
TypeError: 'list' object cannot be interpreted as an integer

And if I try to run through the list and save, this gives me annother error of out of range 256


问:
Checking one DataFrame's Column of Lists Against Another DataFrame's Column of Lists
I have 2 DataFrames, and each ones has a column of lists.

I need to check each list from df2 to see if there is a list in df1 that contains all its elements.

ie. df2 row 1 has a list of [1,5]. I need to check against all the lists of df1 to see if ANY of them contain both 1 and 5.

For any lists from df2 that had a full match, they get marked 'clean' in the df2['bucket'] column.

My problem: With larger data sets, this is currently very slow. My hope is that someone can suggest a faster approach.

```<code>import pandas as pd

list1 = [
    ['a', [1, 5, 10, 14, 15]],
    ['l',  [7, 13, 25, 46, 50]],
    ['o',  [2, 4, 6, 19, 36]],
    ['d',  [1, 19, 24, 26, 29]]]

df1 = pd.DataFrame(list1, columns =['Fruits', 'Values'])

list2 = [
    ['a', [1, 5]],
    ['r',  [2, 4, 5]],
    ['e',  [2, 9]],
    ['f',  [2, 6, 36]],
    ['w',  [2, 6, 37]],
    ['a',  [24, 29]],
    ['q',  [1, 14, 15]]]

df2 = pd.DataFrame(list2, columns =['Fruits', 'Values'])

df1['bucket'] = ""

list1_row_count = df1.shape[0]
list2_row_count = df2.shape[0]

for x in range(list2_row_count):
    break_out = False
    for _ in range(list1_row_count):
        if break_out == True : break
        df1_list = df1['Values'].iloc[_]
        df2_list = df2['Values'].iloc[x]
        check =  all(item in df1_list for item in df2_list)

        if check is True:
            df2.loc[x, 'bucket'] = 'clean'
            break_out = True
        else :
            df2.loc[x, 'bucket'] = 'mixed'

print(df1)
print('')
print(df2)
</code>```

答:
You can try use to_numpy(), which is quite fast:

def process(a, b):
  def compare(a, i):
    idx = 0
    while idx < a.shape[0]:
      if all(x in a[idx] for x in i): return 'clean'
      idx +=1
    return 'mixed'
  return [compare(a, i) for i in b]

df2['bucket'] = process(df1.Values.to_numpy(), df2.Values.to_numpy())
```
```  Fruits       Values bucket
0      a       [1, 5]  clean
1      r    [2, 4, 5]  mixed
2      e       [2, 9]  mixed
3      f   [2, 6, 36]  clean
4      w   [2, 6, 37]  mixed
5      a     [24, 29]  clean
6      q  [1, 14, 15]  clean
```

Body:
I have 2 DataFrames, and each ones has a column of lists.

I need to check each list from df2 to see if there is a list in df1 that contains all its elements.

ie. df2 row 1 has a list of [1,5]. I need to check against all the lists of df1 to see if ANY of them contain both 1 and 5.

For any lists from df2 that had a full match, they get marked 'clean' in the df2['bucket'] column.

My problem: With larger data sets, this is currently very slow. My hope is that someone can suggest a faster approach.

import pandas as pd

list1 = [
    ['a', [1, 5, 10, 14, 15]],
    ['l',  [7, 13, 25, 46, 50]],
    ['o',  [2, 4, 6, 19, 36]],
    ['d',  [1, 19, 24, 26, 29]]]

df1 = pd.DataFrame(list1, columns =['Fruits', 'Values'])

list2 = [
    ['a', [1, 5]],
    ['r',  [2, 4, 5]],
    ['e',  [2, 9]],
    ['f',  [2, 6, 36]],
    ['w',  [2, 6, 37]],
    ['a',  [24, 29]],
    ['q',  [1, 14, 15]]]

df2 = pd.DataFrame(list2, columns =['Fruits', 'Values'])

df1['bucket'] = ""

list1_row_count = df1.shape[0]
list2_row_count = df2.shape[0]

for x in range(list2_row_count):
    break_out = False
    for _ in range(list1_row_count):
        if break_out == True : break
        df1_list = df1['Values'].iloc[_]
        df2_list = df2['Values'].iloc[x]
        check =  all(item in df1_list for item in df2_list)

        if check is True:
            df2.loc[x, 'bucket'] = 'clean'
            break_out = True
        else :
            df2.loc[x, 'bucket'] = 'mixed'

print(df1)
print('')
print(df2)

Body:
You can try use to_numpy(), which is quite fast:

def process(a, b):
  def compare(a, i):
    idx = 0
    while idx < a.shape[0]:
      if all(x in a[idx] for x in i): return 'clean'
      idx +=1
    return 'mixed'
  return [compare(a, i) for i in b]

df2['bucket'] = process(df1.Values.to_numpy(), df2.Values.to_numpy())

  Fruits       Values bucket
0      a       [1, 5]  clean
1      r    [2, 4, 5]  mixed
2      e       [2, 9]  mixed
3      f   [2, 6, 36]  clean
4      w   [2, 6, 37]  mixed
5      a     [24, 29]  clean
6      q  [1, 14, 15]  clean


问:
React loses focus on input after the first character
Everytime I type, i lose the focus of the input text. I have other components which are working fine; but this one is losing focus. Any idea why would this happen?

I tried creating separate components and rendering them in my switch but still not working.

I have other components rendered with Switch statements and are working fine.

```<code>const FactionDetail = ({Faction}) => {
const [tab, setTab] = React.useState(0)
const [selectedMember, setSelectedMember] = React.useState(null)

const [receipt, setReceipt] = React.useState('')
const [selectedRank, setSelectedRank] = React.useState(null)

const [newRankDetails, setNewRankDetails] = React.useState({
    rankName: '',
    wage: 0,
    hasPerm: false
})

const menuOption = (tabId) =>{
    setTab(tabId)
}

const selectMember = (e) =>{
    setSelectedMember(e)
}

const renderDropdownOptions = () =>{
    let i  = 0
    for (const rank in Faction.ranks){
        i++
        return <option key = {i} value = {rank}>{rank}</option>
    }
}

React.useEffect(() =>{
    if(selectedMember != null && selectedRank != selectedMember.rank){
        setSelectedRank(selectedMember.rank)
    }
}, [selectedMember])

const RightBody = () =>{
    switch(tab){
        case 0: // Dashboard
            return <>

            </>
        case 1: //Members
            return <> </>

        case 2: //Manage
            return <>
                <div className ='CreateRanks'>
                    <label>Rank Name</label>
                    <input style ={{width:'80px'}} onChange = {(e) => setNewRankDetails((prev) => {return {...prev, rankName: e.target.value}})} value = {newRankDetails.rankName}></input>
                    <label>Wage</label>
                    <input style ={{width:'80px'}} onChange = {(e) => setNewRankDetails((prev) => {return {...prev, wage: e.target.value}})} value = {newRankDetails.wage}></input>
                    <label>Has Perm</label>
                    <input type="checkbox" onChange = {(e) => setNewRankDetails((prev) => {return {...prev, hasPerm: e.target.checked}})} value = {newRankDetails.hasPerm} />
                    <button onClick = {() =>{ updateClient('factions:createNewRank', newRankDetails)}}>Create</button>
                </div>

            </>
        default:
            return<>{tab}</>
    }
}
</code>```

答:
```<code><input style ={{width:'80px'}} onChange = {(e) => saveDetails(e, 'Rank Name')} value = {newRankDetails.rankName}></input>

const saveDetails=(e, param:string)=>{
e.preventDefault();
if(param==='Rank Name'){
setNewRankDetails((prev) =>  {...prev, rankName: e.target.value})
}else if(param==='Wage'){
setNewRankDetails((prev) =>  {...prev, wage: e.target.value})
}
}
</code>```

Body:
Everytime I type, i lose the focus of the input text. I have other components which are working fine; but this one is losing focus. Any idea why would this happen?

I tried creating separate components and rendering them in my switch but still not working.

I have other components rendered with Switch statements and are working fine.

const FactionDetail = ({Faction}) => {
const [tab, setTab] = React.useState(0)
const [selectedMember, setSelectedMember] = React.useState(null)

const [receipt, setReceipt] = React.useState('')
const [selectedRank, setSelectedRank] = React.useState(null)

const [newRankDetails, setNewRankDetails] = React.useState({
    rankName: '',
    wage: 0,
    hasPerm: false
})

const menuOption = (tabId) =>{
    setTab(tabId)
}

const selectMember = (e) =>{
    setSelectedMember(e)
}

const renderDropdownOptions = () =>{
    let i  = 0
    for (const rank in Faction.ranks){
        i++
        return <option key = {i} value = {rank}>{rank}</option>
    }
}

React.useEffect(() =>{
    if(selectedMember != null && selectedRank != selectedMember.rank){
        setSelectedRank(selectedMember.rank)
    }
}, [selectedMember])

const RightBody = () =>{
    switch(tab){
        case 0: // Dashboard
            return <>

            </>
        case 1: //Members
            return <> </>

        case 2: //Manage
            return <>

                    Rank Name
                    <input style ={{width:'80px'}} onChange = {(e) => setNewRankDetails((prev) => {return {...prev, rankName: e.target.value}})} value = {newRankDetails.rankName}></input>
                    Wage
                    <input style ={{width:'80px'}} onChange = {(e) => setNewRankDetails((prev) => {return {...prev, wage: e.target.value}})} value = {newRankDetails.wage}></input>
                    Has Perm
                    <input type="checkbox" onChange = {(e) => setNewRankDetails((prev) => {return {...prev, hasPerm: e.target.checked}})} value = {newRankDetails.hasPerm} />
                    <button onClick = {() =>{ updateClient('factions:createNewRank', newRankDetails)}}>Create</button>

            </>
        default:
            return<>{tab}</>
    }
}


问:
Error in time library in python and can't install time
I have this code

```<code>class Timer():
def __init__(self, synch=None):
    self.synch = synch or (lambda: None)
    self.synch()
    self.times = [time.time()]
    self.total_time = 0.0

def __call__(self, include_in_total=True):
    self.synch()
    self.times.append(time.time())
    delta_t = self.times[-1] - self.times[-2]
    if include_in_total:
        self.total_time += delta_t
    return delta_t
</code>```

and I get the error

self.times = [time.time()]
NameError: name 'time' is not defined

I have imported time but haven't installed it cause I was told it's built in.
When I try to install it I get the error

no such option: --build-dir

when I downgrade pip to 20.2.4 it tells me that I cant install time without the newest version of pip.
What should I do?

答: I would leave a comment but I don't have enough reputation.  However, the time module is built in.  I don't understand why you are trying to install time via pip.  Try making a very simple python file that simply returns the result of time.time().  If that works, then something is wrong with your code.  If that doesn't work, then the time module is likely missing from your python installation.

Body:
I have this code

class Timer():
def __init__(self, synch=None):
    self.synch = synch or (lambda: None)
    self.synch()
    self.times = [time.time()]
    self.total_time = 0.0

def __call__(self, include_in_total=True):
    self.synch()
    self.times.append(time.time())
    delta_t = self.times[-1] - self.times[-2]
    if include_in_total:
        self.total_time += delta_t
    return delta_t

and I get the error

self.times = [time.time()]
NameError: name 'time' is not defined

I have imported time but haven't installed it cause I was told it's built in.
When I try to install it I get the error

no such option: --build-dir

when I downgrade pip to 20.2.4 it tells me that I cant install time without the newest version of pip.
What should I do?


问:
Problem connection with MAMP to MySQL after I changed password in PhpMyAdmin
I have a big issue with MAMP.
I changed the password in phpMyAdmin, big error, now, I'm blocked for starting and connecting MySQL.

I tried to resolve this with terminal, with the file php (username and password of phpmyadmin) and even reinstall MAMP but I have the same problem with the copied folder "db".

I just want to get my database back !

Thanks for helping me.

EDIT : I recovered my database with this
https://gist.github.com/premitheme/c45a036e9c6d62662d081c302f51ff20

答:
I managed to recovery my database with this :

gist.github.com/premitheme/c45a036e9c6d62662d081c302f51ff20 Thank you


问:
Data from back end not showing in front end using django
I am trying to insert data into my frontend but not sure what I did wrong here. Here is the code...

I don't have any errors showing in my terminal or web browser.

my views.py

```<code>from django.shortcuts import render, get_list_or_404

from adopt.models import Adopt

# Create your views here.
def adopt(request):
    return render(request, 'adopts/adopt.html')

def adopt_detail(request, id):
    single_pet = get_list_or_404(Adopt, pk=id)

    data = {
        'single_pet': single_pet,
    }
    return render(request, 'adopts/adopt_detail.html', data)

def search(request):
    adopt = Adopt.objects.order_by('-created_date')

    if 'keyword' in request.GET:
        keyword = request.GET['keyword']
        if keyword:
            adopt = adopt.filter(description__icontains=keyword)
            data = {
                'adopt': adopt,
            }
            return render(request, 'adopts/search.html', data)
</code>```

my models.py

```<code>from django.db import models
from datetime import datetime
from ckeditor.fields import RichTextField

# Create your models here.
class Adopt(models.Model):

    pet_gender = (
        ('F','Female'),
        ('M', 'Male'),
    )

    state_choice = (
        ('AL', 'Alabama'),
        ('AK', 'Alaska'),
        ('AZ', 'Arizona'),
        ('AR', 'Arkansas'),
        ('CA', 'California'),
        ('CO', 'Colorado'),
        ('CT', 'Connecticut'),
        ('DE', 'Delaware'),
        ('DC', 'District Of Columbia'),
        ('FL', 'Florida'),
        ('GA', 'Georgia'),
        ('HI', 'Hawaii'),
        ('ID', 'Idaho'),
        ('IL', 'Illinois'),
        ('IN', 'Indiana'),
        ('IA', 'Iowa'),
        ('KS', 'Kansas'),
        ('KY', 'Kentucky'),
        ('LA', 'Louisiana'),
        ('ME', 'Maine'),
        ('MD', 'Maryland'),
        ('MA', 'Massachusetts'),
        ('MI', 'Michigan'),
        ('MN', 'Minnesota'),
        ('MS', 'Mississippi'),
        ('MO', 'Missouri'),
        ('MT', 'Montana'),
        ('NE', 'Nebraska'),
        ('NV', 'Nevada'),
        ('NH', 'New Hampshire'),
        ('NJ', 'New Jersey'),
        ('NM', 'New Mexico'),
        ('NY', 'New York'),
        ('NC', 'North Carolina'),
        ('ND', 'North Dakota'),
        ('OH', 'Ohio'),
        ('OK', 'Oklahoma'),
        ('OR', 'Oregon'),
        ('PA', 'Pennsylvania'),
        ('RI', 'Rhode Island'),
        ('SC', 'South Carolina'),
        ('SD', 'South Dakota'),
        ('TN', 'Tennessee'),
        ('TX', 'Texas'),
        ('UT', 'Utah'),
        ('VT', 'Vermont'),
        ('VA', 'Virginia'),
        ('WA', 'Washington'),
        ('WV', 'West Virginia'),
        ('WI', 'Wisconsin'),
        ('WY', 'Wyoming'),
    )

    year_choice = []
    for r in range(2000, (datetime.now().year+1)):
        year_choice.append((r,r))

    pet_title = models.CharField(max_length=255)
    state = models.CharField(choices=state_choice, max_length=100)
    city = models.CharField(max_length=100)
    gender = models.CharField(choices=pet_gender, max_length=100, blank=True)
    breed = models.CharField(max_length=100)
    year = models.IntegerField(('year'), choices=year_choice)
    pet_photo = models.ImageField(upload_to='photots/%Y/%m/%d/')
    description = RichTextField()
    price = models.IntegerField()
    created_date = models.DateTimeField(default=datetime.now, blank=True)

    def __str__(self):
        return self.pet_title
</code>```

答:
You are passing in adopt in your view, but you're referencing adopts in your template.  In addition, your queries have the wrong syntax.  The code below should work.

def search(request):
    adopt = Adopt.objects.all().order_by('-created_date')    # CHANGE

    if 'keyword' in request.GET:
        keyword = request.GET['keyword']
        if keyword:
            adopts = Adopt.objects.filter(description__icontains=keyword).order_by('-created_date')   # CHANGE
            data = {
                'adopts': adopts,    # CHANGE
            }
            return render(request, 'adopts/search.html', data)
```

Body:
I am trying to insert data into my frontend but not sure what I did wrong here. Here is the code...

I don't have any errors showing in my terminal or web browser.

my views.py

from django.shortcuts import render, get_list_or_404

from adopt.models import Adopt

# Create your views here.
def adopt(request):
    return render(request, 'adopts/adopt.html')

def adopt_detail(request, id):
    single_pet = get_list_or_404(Adopt, pk=id)

    data = {
        'single_pet': single_pet,
    }
    return render(request, 'adopts/adopt_detail.html', data)

def search(request):
    adopt = Adopt.objects.order_by('-created_date')

    if 'keyword' in request.GET:
        keyword = request.GET['keyword']
        if keyword:
            adopt = adopt.filter(description__icontains=keyword)
            data = {
                'adopt': adopt,
            }
            return render(request, 'adopts/search.html', data)

my models.py

from django.db import models
from datetime import datetime
from ckeditor.fields import RichTextField

# Create your models here.
class Adopt(models.Model):

    pet_gender = (
        ('F','Female'),
        ('M', 'Male'),
    )

    state_choice = (
        ('AL', 'Alabama'),
        ('AK', 'Alaska'),
        ('AZ', 'Arizona'),
        ('AR', 'Arkansas'),
        ('CA', 'California'),
        ('CO', 'Colorado'),
        ('CT', 'Connecticut'),
        ('DE', 'Delaware'),
        ('DC', 'District Of Columbia'),
        ('FL', 'Florida'),
        ('GA', 'Georgia'),
        ('HI', 'Hawaii'),
        ('ID', 'Idaho'),
        ('IL', 'Illinois'),
        ('IN', 'Indiana'),
        ('IA', 'Iowa'),
        ('KS', 'Kansas'),
        ('KY', 'Kentucky'),
        ('LA', 'Louisiana'),
        ('ME', 'Maine'),
        ('MD', 'Maryland'),
        ('MA', 'Massachusetts'),
        ('MI', 'Michigan'),
        ('MN', 'Minnesota'),
        ('MS', 'Mississippi'),
        ('MO', 'Missouri'),
        ('MT', 'Montana'),
        ('NE', 'Nebraska'),
        ('NV', 'Nevada'),
        ('NH', 'New Hampshire'),
        ('NJ', 'New Jersey'),
        ('NM', 'New Mexico'),
        ('NY', 'New York'),
        ('NC', 'North Carolina'),
        ('ND', 'North Dakota'),
        ('OH', 'Ohio'),
        ('OK', 'Oklahoma'),
        ('OR', 'Oregon'),
        ('PA', 'Pennsylvania'),
        ('RI', 'Rhode Island'),
        ('SC', 'South Carolina'),
        ('SD', 'South Dakota'),
        ('TN', 'Tennessee'),
        ('TX', 'Texas'),
        ('UT', 'Utah'),
        ('VT', 'Vermont'),
        ('VA', 'Virginia'),
        ('WA', 'Washington'),
        ('WV', 'West Virginia'),
        ('WI', 'Wisconsin'),
        ('WY', 'Wyoming'),
    )

    year_choice = []
    for r in range(2000, (datetime.now().year+1)):
        year_choice.append((r,r))

    pet_title = models.CharField(max_length=255)
    state = models.CharField(choices=state_choice, max_length=100)
    city = models.CharField(max_length=100)
    gender = models.CharField(choices=pet_gender, max_length=100, blank=True)
    breed = models.CharField(max_length=100)
    year = models.IntegerField(('year'), choices=year_choice)
    pet_photo = models.ImageField(upload_to='photots/%Y/%m/%d/')
    description = RichTextField()
    price = models.IntegerField()
    created_date = models.DateTimeField(default=datetime.now, blank=True)

    def __str__(self):
        return self.pet_title


问:
TCP/IP basics: Destination port relevance
Ok this is kind of embarassing but I just have a rather "noob" question.

In a client server TCP communications, where my system is a client accessing a remote server at say Port XX, isnt the client opening a random port YY in its system to talk to remote port XX?
So when we code we do specify the destination port XX right?

For the client, the port YY itself is chosen when the socket is created, isnt it?

Is there anyway I could monitor/restrict/control any client talking to a particular server?(like say clients talking to servers at specific serving ports??)

Is there any IPTABLE rule or some firewall rule restricting the client?
Can this be done at all??

Are destination ports saved in the socket structures? If so where??

Thanks!

答:
First, server side creates a listening socket, with the chain of socket(2), bind(2), and listen(2) calls, then waits for incoming client connection requests with the accept(2) call. Once a client connects (socket(2) and then connect(2) on the client side) and the TCP/IP stacks of the client and the server machines complete the three way handshake, the accept(2) returns new socket descriptor - that's the server's end of the connected socket. Both bind(2) on the server side, and connect(2) on the client side take server's address and port.

Now, the full TCP connection is described by four numbers - server address, server port, client address, and client port. The first two must obviously be known to the client prior to the connection attempt (otherwise, where do we go?). The client address and port, while could be specified explicitly with the bind(2), are usually assigned dynamically - the address is the IP address of the outgoing network interface, as determined by the routing table, and the port selected out of range of ephemeral ports.

The netstat(8) command shows you established connections. Adding -a flag lets you see listening sockets, -n flag disables DNS and service resolution, so you just see numeric addresses and ports.

Linux iptables(8) allows you to restrict where clients are allowed to connect to. You can restrict based on source and destination ports, addresses, and more.

You can get socket local binding with getsockname(2) call, remote binding is given by getpeername(2).

Hope this makes it a bit more clear.


问:
Remove element class with a matching id of radio button if unchecked
I've been trying to find an answer but it isn't giving me any answers and all I found is for checkboxes I tried this but .removeClass doesn't work plus I have to copy and paste every single thing. I  know there's a more compact way how do it but i don't know how to

$("#group1").change(function() {
  if ($(this).is(":checked")) {
    $(".group1").addClass("red");
  } else {
    $(".group2").removeClass("orange");
  }
});

$("#group2").change(function() {
  if ($(this).is(":checked")) {
    $(".group2").addClass("orange");
  } else {
    $(".group2").removeClass("orange");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  width: 100px;
  height: 100px;
  border: 1px solid
}

.red {
  background-color: red
}

.orange {
  background-color: orange
}</code>```

<input type="radio" name="numbers" value="first" id="group1" />
1

<input type="radio" name="numbers" value="second" id="group2" />
2

```

答:
$("#group1").change(function() {
  if ($(this).is(":checked")) {
    $(".group1").addClass("red");
    $(".group2").removeClass("orange");
  }
});

$("#group2").change(function() {
  if ($(this).is(":checked")) {
    $(".group2").addClass("orange");
    $(".group1").removeClass("red");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  width: 100px;
  height: 100px;
  border: 1px solid
}

.red {
  background-color: red
}

.orange {
  background-color: orange
}</code>```

<input type="radio" name="numbers" value="first" id="group1" />
1

<input type="radio" name="numbers" value="second" id="group2" />
2

```

Body:
I've been trying to find an answer but it isn't giving me any answers and all I found is for checkboxes I tried this but .removeClass doesn't work plus I have to copy and paste every single thing. I  know there's a more compact way how do it but i don't know how to

$("#group1").change(function() {
  if ($(this).is(":checked")) {
    $(".group1").addClass("red");
  } else {
    $(".group2").removeClass("orange");
  }
});

$("#group2").change(function() {
  if ($(this).is(":checked")) {
    $(".group2").addClass("orange");
  } else {
    $(".group2").removeClass("orange");
  }
});

div {
  width: 100px;
  height: 100px;
  border: 1px solid
}

.red {
  background-color: red
}

.orange {
  background-color: orange
}

<input type="radio" name="numbers" value="first" id="group1" />
1

<input type="radio" name="numbers" value="second" id="group2" />
2

Body:
$("#group1").change(function() {
  if ($(this).is(":checked")) {
    $(".group1").addClass("red");
    $(".group2").removeClass("orange");
  }
});

$("#group2").change(function() {
  if ($(this).is(":checked")) {
    $(".group2").addClass("orange");
    $(".group1").removeClass("red");
  }
});

div {
  width: 100px;
  height: 100px;
  border: 1px solid
}

.red {
  background-color: red
}

.orange {
  background-color: orange
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="radio" name="numbers" value="first" id="group1" />
<label for="id1">1</label>

<input type="radio" name="numbers" value="second" id="group2" />
<label for="id2">2</label>

<div class="group1"></div>
<div class="group2"></div>


问:
Illuminate\Contracts\Container\BindingResolutionException - Target class [CommandMakeCommand] does not exist
Using Laravel 8.75 and trying to upgrade to php 8.1 in composer.json to "php": "^8.1" and receive the error of Illuminate\Contracts\Container\BindingResolutionException - Target class [CommandMakeCommand] does not exist.

```<code>Loading composer repositories with package information
Updating dependencies
Nothing to modify in lock file
Installing dependencies from lock file (including require-dev)
Nothing to install, update or remove
Package swiftmailer/swiftmailer is abandoned, you should avoid using it.
Use symfony/mailer instead.
Generating optimized autoload files

Illuminate\Foundation\ComposerScripts::postAutoloadDump
@php artisan package:discover --ansi

Illuminate\Contracts\Container\BindingResolutionException

Target class [CommandMakeCommand] does not exist.

at
</code>```

vendor/laravel/framework/src/Illuminate/Container/Container.php:879

```<code>875▕
876▕         try {
877▕             $reflector = new ReflectionClass($concrete);
878▕         } catch (ReflectionException $e) {
879▕             throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e);
880▕         }
881▕
882▕         // If the type is not instantiable, the developer is attempting to resolve
883▕         // an abstract type such as an Interface or Abstract Class and there is

  +13 vendor frames
 14  artisan:37
 Illuminate\Foundation\Console\Kernel::handle()
Script @php artisan package:discover --ansi handling the post-autoload-
dump event returned with error code 1
</code>```

答: i also had same problem, in my case nwidart/laravel-modules package upgraded to 8.3 version, i downgraded to 8.2 version and problem solved</p>

Body:
Using Laravel 8.75 and trying to upgrade to php 8.1 in composer.json to "php": "^8.1" and receive the error of Illuminate\Contracts\Container\BindingResolutionException - Target class [CommandMakeCommand] does not exist.

Loading composer repositories with package information
Updating dependencies
Nothing to modify in lock file
Installing dependencies from lock file (including require-dev)
Nothing to install, update or remove
Package swiftmailer/swiftmailer is abandoned, you should avoid using it.
Use symfony/mailer instead.
Generating optimized autoload files

Illuminate\Foundation\ComposerScripts::postAutoloadDump
@php artisan package:discover --ansi

Illuminate\Contracts\Container\BindingResolutionException

Target class [CommandMakeCommand] does not exist.

at

vendor/laravel/framework/src/Illuminate/Container/Container.php:879

875▕
876▕         try {
877▕             $reflector = new ReflectionClass($concrete);
878▕         } catch (ReflectionException $e) {
879▕             throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e);
880▕         }
881▕
882▕         // If the type is not instantiable, the developer is attempting to resolve
883▕         // an abstract type such as an Interface or Abstract Class and there is

  +13 vendor frames
 14  artisan:37
 Illuminate\Foundation\Console\Kernel::handle()
Script @php artisan package:discover --ansi handling the post-autoload-
dump event returned with error code 1