问:
Get the item correspond to a CheckedTextView from Android ListActivity Custom Adapter
I 've the following custom adapter

```<code>public class GroupAdapter extends ArrayAdapter<Group> {
    private ArrayList<Group> items;
    public HashMap<String, String> checkedItems = new HashMap<String, String>();
    ...
    public void setCheckedItem(int item) {
    }
    public HashMap<String, String> getCheckedItems() {
        return checkedItems;
    }
    ...

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    ...
    View v = convertView;
    LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    v = vi.inflate(R.layout.list_groups, null);
    Group bs = items.get(position);
    CheckedTextView ctView = (CheckedTextView) v.findViewById(R.id.listCheckboxview);
    ctView.setText(bs.getGroupName());
    //  ctView.setId(bs.getId());
        ctView.setId(position);
        ctView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                ((CheckedTextView) v).toggle();
                if(((CheckedTextView) v).isChecked()) {
                    Log.e(MY_DEBUG_TAG, "Checked");
                    // I need to get the item currespond to this view to call Adapters's setCheckedItem(item) method
                }
            }
        });
</code>```

and the layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="?android:attr/listPreferredItemHeight"
    android:paddingLeft="5dip" android:paddingRight="5dip"
    android:paddingTop="10dip" android:paddingBottom="10dip"
    android:fastScrollEnabled="true"
    >
    <CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
         android:id="@+id/listCheckboxview"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_weight="1" android:gravity="center|left"
         android:textColor="#0075AB"  android:textStyle="bold"  android:textSize="14dip"
         android:checkMark="?android:attr/listChoiceIndicatorMultiple"
         android:paddingLeft="6dip"
         android:paddingRight="6dip"
         android:clickable="true"
         android:focusable="true"
         android:text=""
         />
</LinearLayout>
</code>```

Im' able to capture the setOnClickListener for the CheckedTextView, Inside the listener, I need to get the item correspond to clicked CheckedTextView to call Adapters's setCheckedItem(item) method. (Please see the comments in the adapter class)

答:
You should set the tag of the checkedTextView.

Like ctView.setTag(items.get(position)); then in the onClick() doing v.getTag() will give you the item group.

Body:
I 've the following custom adapter

public class GroupAdapter extends ArrayAdapter<Group> {
    private ArrayList<Group> items;
    public HashMap<String, String> checkedItems = new HashMap<String, String>();
    ...
    public void setCheckedItem(int item) {
    }
    public HashMap<String, String> getCheckedItems() {
        return checkedItems;
    }
    ...

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    ...
    View v = convertView;
    LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    v = vi.inflate(R.layout.list_groups, null);
    Group bs = items.get(position);
    CheckedTextView ctView = (CheckedTextView) v.findViewById(R.id.listCheckboxview);
    ctView.setText(bs.getGroupName());
    //  ctView.setId(bs.getId());
        ctView.setId(position);
        ctView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                ((CheckedTextView) v).toggle();
                if(((CheckedTextView) v).isChecked()) {
                    Log.e(MY_DEBUG_TAG, "Checked");
                    // I need to get the item currespond to this view to call Adapters's setCheckedItem(item) method
                }
            }
        });

and the layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="?android:attr/listPreferredItemHeight"
    android:paddingLeft="5dip" android:paddingRight="5dip"
    android:paddingTop="10dip" android:paddingBottom="10dip"
    android:fastScrollEnabled="true"
    >
    <CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
         android:id="@+id/listCheckboxview"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_weight="1" android:gravity="center|left"
         android:textColor="#0075AB"  android:textStyle="bold"  android:textSize="14dip"
         android:checkMark="?android:attr/listChoiceIndicatorMultiple"
         android:paddingLeft="6dip"
         android:paddingRight="6dip"
         android:clickable="true"
         android:focusable="true"
         android:text=""
         />
</LinearLayout>

Im' able to capture the setOnClickListener for the CheckedTextView, Inside the listener, I need to get the item correspond to clicked CheckedTextView to call Adapters's setCheckedItem(item) method. (Please see the comments in the adapter class)


来源: stackexchange

问:
Google Trends API - data frequency
I have gained access to the Google Trends API and tried downloading some trends data using the getting started guide's code:

```<code>start_date = '2010-01'
end_date = '2018-01'
response = service.getGraph(terms='apple',restrictions_startDate=start_date,restrictions_endDate=end_date).execute()
pprint.pprint(response)
</code>```

This returns monthly data. Is there a way to get the data in daily frequency?

答:
getGraph returns results by week only. To get results by day, use getTimelinesForHealth instead and add the parameter timelineResolution = 'day', as in:

```<code>response = service.getTimelinesForHealth(
    terms = 'apple',
    time_startDate = 'YYYY-MM-DD',
    time_endDate = 'YYYY-MM-DD',
    timelineResolution = 'day'
).execute()
</code>```

Note that restrictions_startDate and restrictions_endDate should be
changed to time_startDate and time_endDate respectively, and the time
is indicated in the format 'YYYY-MM-DD'.

ContentLicense: CC BY-SA 4.0

Title: Google Trends API - data frequency

Body:
I have gained access to the Google Trends API and tried downloading some trends data using the getting started guide's code:

start_date = '2010-01'
end_date = '2018-01'
response = service.getGraph(terms='apple',restrictions_startDate=start_date,restrictions_endDate=end_date).execute()
pprint.pprint(response)

This returns monthly data. Is there a way to get the data in daily frequency?

Body:
getGraph returns results by week only. To get results by day, use getTimelinesForHealth instead and add the parameter timelineResolution = 'day', as in:

response = service.getTimelinesForHealth(
    terms = 'apple',
    time_startDate = 'YYYY-MM-DD',
    time_endDate = 'YYYY-MM-DD',
    timelineResolution = 'day'
).execute()

Note that restrictions_startDate and restrictions_endDate should be
changed to time_startDate and time_endDate respectively, and the time
is indicated in the format 'YYYY-MM-DD'.


问:
Detect white background on images using python
Is there a way to tell whether an image as a white background using python and what could be a good strategy to get a "percentage of confidence" about this question? Seems like the literature on internet doesn't cover exactly this case and I can't find anything strictly related.

The images I want to analyze are typical e-commerce website product pictures, so they should have a single focused object in the middle and white background only at the borders.

Another information that could be available is the max percentage of image space the object should occupy.

答:
This question may be years ago but I just had a similar task recently. Sharing my answer here might help others that will encounter the same task too and I might also improve my answer by having the community look at it.

```<code>import cv2 as cv
import numpy as np

THRESHOLD_INTENSITY = 230

def has_white_background(img):
    # Read image into org_img variable
    org_img = cv.imread(img, cv.IMREAD_GRAYSCALE)
    # cv.imshow('Original Image', org_img)

    # Create a black blank image for the mask
    mask = np.zeros_like(org_img)

    # Create a thresholded image, I set my threshold to 200 as this is the value
    # I found most effective in identifying light colored object
    _, thres_img = cv.threshold(org_img, 200, 255, cv.THRESH_BINARY_INV)

    # Find the most significant contours
    contours, hierarchy = cv.findContours(thres_img, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
    # Get the outermost contours
    outer_contours_img = max(contours, key=cv.contourArea)

    # Get the bounding rectangle of the contours
    x,y,w,h = cv.boundingRect(outer_contours_img)
    # Draw a rectangle base on the bounding rectangle of the contours to our mask
    cv.rectangle(mask,(x,y),(x+w,y+h),(255,255,255),-1)
    # Invert the mask so that we create a hole for the detected object in our mask
    mask = cv.bitwise_not(mask)

    # Apply mask to the original image to subtract it and retain only the bg
    img_bg = cv.bitwise_and(org_img, org_img, mask=mask)

    # If the size of the mask is similar to the size of the image then the bg is not white
    if h == org_img.shape[0] and w == org_img.shape[1]:
        return False

    # Create a np array of the
    np_array = np.array(img_bg)

    # Remove the zeroes from the "remaining bg image" so that we dont consider the black part,
    # and find the average intensity of the remaining pixels
    ave_intensity = np_array[np.nonzero(np_array)].mean()

    if ave_intensity > THRESHOLD_INTENSITY:
        return True
    else:
        return False
</code>```

These are the images of the steps from the code above:

Here is the Original Image. No copyright infringement intended.
(Cant find the url of the actual imagem from unsplash)

First step is to convert the image to grayscale.

Apply thresholding to the image.

Get the contours of the "thresholded" image and get the contours. Drawing the contours is optional only.

From the contours, get the values of the outer contour and find its bounding rectangle. Optionally draw the rectangle to the image so that you'll see if your assumed thresholding value fits the object in the rectangle.

Create a mask out of the bounding rectangle.

Lastly, subtract the mask to the greyscale image. What will remain is the background image minus the mask.

To Finally identify if the background is white, find the average intensity values of the background image excluding the 0 values of the image array. And base on a certain threshold value, categorize it if its white or not.

Hope this helps. If you think it can still be improve, or if there are flaws with my solution pls comment below.

ContentLicense: CC BY-SA 3.0

Body:
This question may be years ago but I just had a similar task recently. Sharing my answer here might help others that will encounter the same task too and I might also improve my answer by having the community look at it.

import cv2 as cv
import numpy as np

THRESHOLD_INTENSITY = 230

def has_white_background(img):
    # Read image into org_img variable
    org_img = cv.imread(img, cv.IMREAD_GRAYSCALE)
    # cv.imshow('Original Image', org_img)

    # Create a black blank image for the mask
    mask = np.zeros_like(org_img)

    # Create a thresholded image, I set my threshold to 200 as this is the value
    # I found most effective in identifying light colored object
    _, thres_img = cv.threshold(org_img, 200, 255, cv.THRESH_BINARY_INV)

    # Find the most significant contours
    contours, hierarchy = cv.findContours(thres_img, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
    # Get the outermost contours
    outer_contours_img = max(contours, key=cv.contourArea)

    # Get the bounding rectangle of the contours
    x,y,w,h = cv.boundingRect(outer_contours_img)
    # Draw a rectangle base on the bounding rectangle of the contours to our mask
    cv.rectangle(mask,(x,y),(x+w,y+h),(255,255,255),-1)
    # Invert the mask so that we create a hole for the detected object in our mask
    mask = cv.bitwise_not(mask)

    # Apply mask to the original image to subtract it and retain only the bg
    img_bg = cv.bitwise_and(org_img, org_img, mask=mask)

    # If the size of the mask is similar to the size of the image then the bg is not white
    if h == org_img.shape[0] and w == org_img.shape[1]:
        return False

    # Create a np array of the
    np_array = np.array(img_bg)

    # Remove the zeroes from the "remaining bg image" so that we dont consider the black part,
    # and find the average intensity of the remaining pixels
    ave_intensity = np_array[np.nonzero(np_array)].mean()

    if ave_intensity > THRESHOLD_INTENSITY:
        return True
    else:
        return False

These are the images of the steps from the code above:

Here is the Original Image. No copyright infringement intended.
(Cant find the url of the actual imagem from unsplash)

First step is to convert the image to grayscale.

Apply thresholding to the image.

Get the contours of the "thresholded" image and get the contours. Drawing the contours is optional only.

From the contours, get the values of the outer contour and find its bounding rectangle. Optionally draw the rectangle to the image so that you'll see if your assumed thresholding value fits the object in the rectangle.

Create a mask out of the bounding rectangle.

Lastly, subtract the mask to the greyscale image. What will remain is the background image minus the mask.

To Finally identify if the background is white, find the average intensity values of the background image excluding the 0 values of the image array. And base on a certain threshold value, categorize it if its white or not.

Hope this helps. If you think it can still be improve, or if there are flaws with my solution pls comment below.


问:
Converting epoch timestamp into a readable date
I'm retrieving a value which is supposed to be a epoch timestamp from a database and trying to convert it back to a date format to display it into a screen.

I can see that I'm retrieving the correct value i.e. 1644537600 which should represent  Friday, 11 February 2022 00:00:00.

When I do the following var date = new Date(parseInt(timestamp));  I get Tue Jan 20 1970 01:48:57

I tried to divide timestamp / 1000 or 1000000 but I get the same result.

It could be with date formatting but struggling to make it work.

答: That epoch is in seconds, you need to multiply it by 1000.</p>


问:
Use `Microsoft.NETCore.UniversalWindowsPlatform` from NuGet on build agent
I build a UWP app on Azure DevOps hosted build agent (Windows-2022, version 20220131.1).
Of course, I use Microsoft.NETCore.UniversalWindowsPlatform NuGet package.
As long as My app has F# code I have to hack a GateKeeper.xml and enable F# in it.
So I use PowerShell to do that

```<code>foreach ($file in gci -Recurse 'C:\Users\*\.nuget\packages\*.net.native.compiler\**\GatekeeperConfig.xml')
{
    (gc $file.FullName) -replace '<FSharpRule on="true">','<FSharpRule on="false">' | sc $file.FullName
}
</code>```

But for version 6.2.12 the content of Microsoft.NETCore.UniversalWindowsPlatform is present in C:\Program Files (x86)\Microsoft SDKs\UWPNuGetPackages\microsoft.netcore.universalwindowsplatform\6.2.12\ where I have no admin rights to change anything on a build agent.

So I wonder if it is possible to force MSBuild to always use NuGet directly never using packages cached in Program Files?

答:
If the agent and UWP adhere to 'normal' NuGet standards, you could try a nuget.config as follows:

<config>
  <packageSources>
    <clear />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />

  </packageSources>
  <fallbackPackageFolders>
    <clear />
  </fallbackPackageFolders>
</config>
```

Keep in mind though, that this might break caching facilities on agents.

Body:
I build a UWP app on Azure DevOps hosted build agent (Windows-2022, version 20220131.1).
Of course, I use Microsoft.NETCore.UniversalWindowsPlatform NuGet package.
As long as My app has F# code I have to hack a GateKeeper.xml and enable F# in it.
So I use PowerShell to do that

foreach ($file in gci -Recurse 'C:\Users\*\.nuget\packages\*.net.native.compiler\**\GatekeeperConfig.xml')
{
    (gc $file.FullName) -replace '<FSharpRule on="true">','<FSharpRule on="false">' | sc $file.FullName
}

But for version 6.2.12 the content of Microsoft.NETCore.UniversalWindowsPlatform is present in C:\Program Files (x86)\Microsoft SDKs\UWPNuGetPackages\microsoft.netcore.universalwindowsplatform\6.2.12\ where I have no admin rights to change anything on a build agent.

So I wonder if it is possible to force MSBuild to always use NuGet directly never using packages cached in Program Files?

Body:
If the agent and UWP adhere to 'normal' NuGet standards, you could try a nuget.config as follows:

<config>
  <packageSources>
    <clear />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
    <!-- any additional sources you need-->
  </packageSources>
  <fallbackPackageFolders>
    <clear />
  </fallbackPackageFolders>
</config>

Keep in mind though, that this might break caching facilities on agents.


问:
useSelector updates twice when createAsyncThunk dispatches event fulfilled
I'm new to redux toolkit and react. But I'm trying to follow the redux toolkit slicer methodology.

My slice:

```<code>import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
const axios = require("axios");
export const fetchR = createAsyncThunk(
  "fetchR",
  async (teamId) => {
    console.log(teamId);
    var data = await axios.get(url);

    return data.data;
  }
);
export const rSlice = createSlice({
  name: "slice",
  initialState: {
    data: { count: 0, data: [] },
    loading: "",
  },
  reducers: {
    setR: (state, action) => {},
    getR: (state, action) => {},
  },
  extraReducers: (builder) => {
    builder.addCase(fetchR.pending, (state, action) => {
      state.loading = "loading";
    });
    builder.addCase(fetchR.fulfilled, (state, action) => {
      state.data = action.payload;
      state.loading = "loaded";
    });
  },
});

// Action creators are generated for each case reducer function
export const { setR, getR } = rSlice.actions;

export default rSlice.reducer;
</code>```

My component that calls fetchR the createAsyncThunk.

```<code>  <IconButton
    onClick={() => {
      dispatch(fetchR("FU"));
    }}
    type="submit"
    sx={{ p: "10px" }}
    aria-label="search"
  >
    <SearchIcon />
  </IconButton>
</code>```

My component that listens to state change for rSlice.

```<code>const MainSub = () => {
  const rList = useSelector((state) => {
    console.log(state.res);
    return state.res;
  }, shallowEqual);
  return (
    <div>
    </div>
  );
};
export default MainSub;
</code>```

My console.log:

```<code>FU
MainSub.js:6
{res: {…}}
res: {data: {…}, loading: 'loading'}
[[Prototype]]: Object
MainSub.js:6
{res: {…}}
res: {data: {…}, loading: 'loaded'}
[[Prototype]]: Object
MainSub.js:6
{res: {…}}
res: {data: {…}, loading: 'loaded'}
[[Prototype]]: Object
</code>```

Notice that the console log in MainSub runs twice when createAysncThunk dispatches fulfilled. I'm not sure what could cause this to run twice. Looking at my network traffic, there is only ONE get request made. So I know that I'm not making multiple requests. Our thunk dispatches an event to pending and fulfilled once. But useSelector thinks the state was changed twice when Thunk dispatches to fulfilled. Again this console log is happening in our MainSub component. Any help would be appreciated Thank you!

答:
Yes, the selector will get run twice - once in the Redux subscription callback after the action itself is dispatched (so it runs outside of React), but then potentially again inside the component itself during render.  This is due to an implementation detail of useSelector.

As a side note, you should never write useSelector(state => state) - that will always cause the component to re-render any time the root state changes!  Instead, you should always select the smallest piece of state this component needs.

Body:
I'm new to redux toolkit and react. But I'm trying to follow the redux toolkit slicer methodology.

My slice:

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
const axios = require("axios");
export const fetchR = createAsyncThunk(
  "fetchR",
  async (teamId) => {
    console.log(teamId);
    var data = await axios.get(url);

    return data.data;
  }
);
export const rSlice = createSlice({
  name: "slice",
  initialState: {
    data: { count: 0, data: [] },
    loading: "",
  },
  reducers: {
    setR: (state, action) => {},
    getR: (state, action) => {},
  },
  extraReducers: (builder) => {
    builder.addCase(fetchR.pending, (state, action) => {
      state.loading = "loading";
    });
    builder.addCase(fetchR.fulfilled, (state, action) => {
      state.data = action.payload;
      state.loading = "loaded";
    });
  },
});

// Action creators are generated for each case reducer function
export const { setR, getR } = rSlice.actions;

export default rSlice.reducer;

My component that calls fetchR the createAsyncThunk.

  <IconButton
    onClick={() => {
      dispatch(fetchR("FU"));
    }}
    type="submit"
    sx={{ p: "10px" }}
    aria-label="search"
  >
    <SearchIcon />
  </IconButton>

My component that listens to state change for rSlice.

const MainSub = () => {
  const rList = useSelector((state) => {
    console.log(state.res);
    return state.res;
  }, shallowEqual);
  return (

  );
};
export default MainSub;

My console.log:

FU
MainSub.js:6
{res: {…}}
res: {data: {…}, loading: 'loading'}
[[Prototype]]: Object
MainSub.js:6
{res: {…}}
res: {data: {…}, loading: 'loaded'}
[[Prototype]]: Object
MainSub.js:6
{res: {…}}
res: {data: {…}, loading: 'loaded'}
[[Prototype]]: Object

Notice that the console log in MainSub runs twice when createAysncThunk dispatches fulfilled. I'm not sure what could cause this to run twice. Looking at my network traffic, there is only ONE get request made. So I know that I'm not making multiple requests. Our thunk dispatches an event to pending and fulfilled once. But useSelector thinks the state was changed twice when Thunk dispatches to fulfilled. Again this console log is happening in our MainSub component. Any help would be appreciated Thank you!


问:
Tweaking asp.net mvc
I really love the "one model in - one model out" idea of Fubu MVC. A controller would look something like this

```<code>public class MyController
    {
        public OutputModel MyAction(InputModel inputModel)
        {
            //..
        }
    }
</code>```

and the service locator would automagically fill in all the required dependencies in the constructor.

This makes the controller very easy  to test.

So my question is: How would you go about tweaking asp.net mvc to allow this simplicity in the controllers ?

答:
What you're looking for the is the ControllerActionInvoker. You'll have to implement your own and override/take over handling a lot of the pipeline work that ASP.NET MVC.

For reference, check out Jonathon Carter's 2-part post on doing ControllerActionInvokers:
http://lostintangent.com/2008/07/03/aspnet-mvc-controlleractioninvoker-part-1/

and

http://lostintangent.com/2008/07/07/aspnet-mvc-controlleractioninvoker-part-2/

Also, the Oxite team did this in the 2nd release of Oxite, you can check out their source here:

http://oxite.codeplex.com/SourceControl/changeset/view/30544

Here's a link directly to their ControllerActionInvoker implementation:
http://oxite.codeplex.com/SourceControl/changeset/view/30544#442766

OwnerDisplayName: BjartN

ContentLicense: CC BY-SA 2.5

Title: Tweaking asp.net mvc

Body:
I really love the "one model in - one model out" idea of Fubu MVC. A controller would look something like this

public class MyController
    {
        public OutputModel MyAction(InputModel inputModel)
        {
            //..
        }
    }

and the service locator would automagically fill in all the required dependencies in the constructor.

This makes the controller very easy  to test.

So my question is: How would you go about tweaking asp.net mvc to allow this simplicity in the controllers ?

OwnerDisplayName: chadmyers


问:
Shannon-Fano Encoding with Images
I have been assigned to encode and decode images using the Shannon-Fano technique. I'll be writing in Matlab.

I am able to access the data array of the image in Matlab, so I can see the value of each pixel. I understand the basics of using the Shannon-Fano technique for text, but not images.

Would I need to loop through each pixel and count the number of occurrences for each pixel value?

Thanks for pointing me in the right direction.

答: Yes, since you want the frequencies of each possible pixel value. You could also try taking a smaller sample and estimating the frequencies if you need to be quick. The simplest method here would be to just make an array of ints that has the same size as the number of possible values. Whereas for text the symbols would be words or letters, for the image the symbols are the values of each pixel.</p>

Title: Shannon-Fano Encoding with Images


问:
How to redirect 404 error to 404.php page?
I need help in php. I am making one portal website in Core Php. I had created 404 page and .htaccess file.

404.php:

```<code><html>
  <head>
    <title>404 Error - Page Not Found</title>
  </head>
  <body>404 Error - Page Not Found!</body>
</html>
</code>```

.htaccess:

```<code>Redirect 404 /404.php
</code>```

But this is not working. If I use this code:

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /404.html [L]
</IfModule>
</code>```

It shows internal server error.

Here is my website: http://jobguide.australianenglishcenter.com/

答:
Open Your htaccess and insert this</p>
```<code>RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.html
</code>```

Body:
I need help in php. I am making one portal website in Core Php. I had created 404 page and .htaccess file.

404.php:

    <title>404 Error - Page Not Found</title>

  404 Error - Page Not Found!

.htaccess:

Redirect 404 /404.php

But this is not working. If I use this code:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /404.html [L]
</IfModule>

It shows internal server error.

Here is my website: http://jobguide.australianenglishcenter.com/

Body:
Open Your htaccess and insert this

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.html


问:
Function variable with dynamic function parameters
Some libraries such as Bevy or Actix Web have functions which accept user defined functions with any amount of parameters.

Examples:

Actix Web:

```<code>async fn fn1(path: web::Path<String>) -> impl Responder {
    // not important
}
async fn fn2(_req: HttpRequest) -> impl Responder {
    // not important
}
let app = App::new()
    .route("/", web::get().to(fn2))
    .route("/{name}", web::get().to(fn1));

</code>```

Bevy:

```<code>fn fn1(mut commands: Commands) {}
fn fn2(mut commands: Commands, time: Res<Time>) {}

App::new().add_system(fn1).add_system(fn2);
</code>```

As you can see in both cases the functions web::get().to(), add_system() accept functions with dynamic number and types of parameters as their parameter. They're not macros. How can I achieve this? Is there a name for this? Thanks

答:
Since functions can implement traits, the solution is to define a trait that represents "can serve as callback function" and then manually implement it for every function arity up to some large number of arguments. In actix, this is done by having .to(f) take something implementing the Handler trait:

pub fn to<F, Args>(mut self, handler: F) -> Self
where
    F: Handler<Args>,
    Args: FromRequest + 'static,
    F::Output: Responder + 'static,
```
<p>Where <code>Handler</code> is defined by:</p>
<pre class="lang-rust prettyprint-override"><code>pub trait Handler<Args>: Clone + 'static {
    type Output;
    type Future: Future<Output = Self::Output>;

    fn call(&self, args: Args) -> Self::Future;
}
</code>```

And implementations for function arities are created as follows:

/// Generates a [`Handler`] trait impl for N-ary functions where N is specified with a sequence of
/// space separated type parameters.
///
/// # Examples
/// ```ignore
/// factory_tuple! {}         // implements Handler for types: fn() -> R
/// factory_tuple! { A B C }  // implements Handler for types: fn(A, B, C) -> R
/// ```
macro_rules! factory_tuple ({ $($param:ident)* } => {
    impl<Func, Fut, $($param,)*> Handler<($($param,)*)> for Func
    where
        Func: Fn($($param),*) -> Fut + Clone + 'static,
        Fut: Future,
    {
        type Output = Fut::Output;
        type Future = Fut;

        #[inline]
        #[allow(non_snake_case)]
        fn call(&self, ($($param,)*): ($($param,)*)) -> Self::Future {
            (self)($($param,)*)
        }
    }
});

factory_tuple! {}
factory_tuple! { A }
factory_tuple! { A B }
factory_tuple! { A B C }
factory_tuple! { A B C D }
factory_tuple! { A B C D E }
factory_tuple! { A B C D E F }
factory_tuple! { A B C D E F G }
factory_tuple! { A B C D E F G H }
factory_tuple! { A B C D E F G H I }
factory_tuple! { A B C D E F G H I J }
factory_tuple! { A B C D E F G H I J K }
factory_tuple! { A B C D E F G H I J K L }
```

Body:
Some libraries such as Bevy or Actix Web have functions which accept user defined functions with any amount of parameters.

Examples:

Actix Web:

async fn fn1(path: web::Path<String>) -> impl Responder {
    // not important
}
async fn fn2(_req: HttpRequest) -> impl Responder {
    // not important
}
let app = App::new()
    .route("/", web::get().to(fn2))
    .route("/{name}", web::get().to(fn1));

Bevy:

fn fn1(mut commands: Commands) {}
fn fn2(mut commands: Commands, time: Res<Time>) {}

App::new().add_system(fn1).add_system(fn2);

As you can see in both cases the functions web::get().to(), add_system() accept functions with dynamic number and types of parameters as their parameter. They're not macros. How can I achieve this? Is there a name for this? Thanks

Body:
Since functions can implement traits, the solution is to define a trait that represents "can serve as callback function" and then manually implement it for every function arity up to some large number of arguments. In actix, this is done by having .to(f) take something implementing the Handler trait:

pub fn to<F, Args>(mut self, handler: F) -> Self
where
    F: Handler<Args>,
    Args: FromRequest + 'static,
    F::Output: Responder + 'static,

Where Handler is defined by:

pub trait Handler<Args>: Clone + 'static {
    type Output;
    type Future: Future<Output = Self::Output>;

    fn call(&self, args: Args) -> Self::Future;
}

And implementations for function arities are created as follows:

/// Generates a [`Handler`] trait impl for N-ary functions where N is specified with a sequence of
/// space separated type parameters.
///
/// # Examples
/// ```ignore
/// factory_tuple! {}         // implements Handler for types: fn() -> R
/// factory_tuple! { A B C }  // implements Handler for types: fn(A, B, C) -> R
/// ```
macro_rules! factory_tuple ({ $($param:ident)* } => {
    impl<Func, Fut, $($param,)*> Handler<($($param,)*)> for Func
    where
        Func: Fn($($param),*) -> Fut + Clone + 'static,
        Fut: Future,
    {
        type Output = Fut::Output;
        type Future = Fut;

        #[inline]
        #[allow(non_snake_case)]
        fn call(&self, ($($param,)*): ($($param,)*)) -> Self::Future {
            (self)($($param,)*)
        }
    }
});

factory_tuple! {}
factory_tuple! { A }
factory_tuple! { A B }
factory_tuple! { A B C }
factory_tuple! { A B C D }
factory_tuple! { A B C D E }
factory_tuple! { A B C D E F }
factory_tuple! { A B C D E F G }
factory_tuple! { A B C D E F G H }
factory_tuple! { A B C D E F G H I }
factory_tuple! { A B C D E F G H I J }
factory_tuple! { A B C D E F G H I J K }
factory_tuple! { A B C D E F G H I J K L }


问:
What is the different between using "IN" vs using "=" inside a query?
I'd like to understand the best way to restrict items in a query. For example Query1 returns a list of ID's based of specific detail filters. I would like Query2 to return only items where Query2.ID is the same as Query1.ID.

Which Query2 Detail Filter is better? And why?

Query2.ID IN ( Query1.ID )

Query2.ID = Query1.ID

Note: Using an "=" filter requires Query2's "Cross product allowed" property to be set to "Allow".

答:
SQL efficiency - [=] vs [in] vs [like] vs [matches]

it depends on the underlying SQL engine. In MS-SQL, for example (according to the query planner output), IN clauses are converted to =, so there would be no difference

Which is better for you will depend on the specific report request.  = is for single values and IN is for multiple values.  It's all about the prompts.  If you are hard-coding (so, not using a parameter) a filter that looks for a single value, use =.

But that's not really what you're asking...

Query2.ID = Query1.ID

You need a join, not a filter.


问:
How could I extract two numbers from a df column?
I have a dataframe, and there are columns (Height, Width and Life Span) with minimal and maximal values. What I want is to create another column with average values (27 for Height etc.), but to do it I need to extract two values - 26 and 28. And I didn't manage to succeed in this task - for example, with regex (df['Height'].replace('\D', '', regex=True)) I could only extract all numbers together, which isn't right. Or I could use re.findall(r'\d+', df['Height'][0]) which gives me what I need, but it applies only for the first row and not for any others (there are 400 rows in original dataset, I pasted only the first one). So, if you could help me I'll be very glad.

Code for df below.

```<code>import pandas as pd

pd.DataFrame({'Dog Breed Group': 'Working Dogs',
 'Height': '26 to 28 inches at the shoulder',
 'Weight': '80 to 140 pounds',
 'Life Span': '10 to 11 years'}, index=[0])
</code>```

答:
Extract digits from strings then convert them as int and finally apply the mean to get a unique number:</p>
```<code>COLS = ['Height', 'Weight', 'Life Span']
get_mean = lambda x: x.str.extractall('(\d+)').astype(int).mean()

df[COLS] = df[COLS].apply(get_mean)
print(df)

# Output:
  Dog Breed Group  Height  Weight  Life Span
0    Working Dogs    27.0   110.0       10.5
</code>```

Body:
I have a dataframe, and there are columns (Height, Width and Life Span) with minimal and maximal values. What I want is to create another column with average values (27 for Height etc.), but to do it I need to extract two values - 26 and 28. And I didn't manage to succeed in this task - for example, with regex (df['Height'].replace('\D', '', regex=True)) I could only extract all numbers together, which isn't right. Or I could use re.findall(r'\d+', df['Height'][0]) which gives me what I need, but it applies only for the first row and not for any others (there are 400 rows in original dataset, I pasted only the first one). So, if you could help me I'll be very glad.

Code for df below.

import pandas as pd

pd.DataFrame({'Dog Breed Group': 'Working Dogs',
 'Height': '26 to 28 inches at the shoulder',
 'Weight': '80 to 140 pounds',
 'Life Span': '10 to 11 years'}, index=[0])

Body:
Extract digits from strings then convert them as int and finally apply the mean to get a unique number:

COLS = ['Height', 'Weight', 'Life Span']
get_mean = lambda x: x.str.extractall('(\d+)').astype(int).mean()

df[COLS] = df[COLS].apply(get_mean)
print(df)

# Output:
  Dog Breed Group  Height  Weight  Life Span
0    Working Dogs    27.0   110.0       10.5


问:
Using Poetry with PyEnv and having Python version issues
I'm working on WSL2 Ubuntu. I've been taking a course in backend API development using Fastapi. My Ubuntu default python is 3.8 I believe. I'm trying to use python 3.10.0 for my development. I've done the following:

pyenv install 3.10.0

cd to my project folder and pyenv local 3.10.0 (creates .python-version file containing 3.10.0)

poetry shell (this creates a .venv folder and all dependencies are added there during development). Bash Prompt has (.venv) in it.

python --version shows 3.10.0 as current version

My problem is that when I look into the .venv/bin file, all of the symbolic links show python 3.8.

```<code>drwxr-xr-x 2 mryan mryan 4096 Feb  1 23:12 .
drwxr-xr-x 4 mryan mryan 4096 Feb  1 23:12 ..
-rw-r--r-- 1 mryan mryan 2152 Feb  1 23:12 activate
-rw-r--r-- 1 mryan mryan 1444 Feb  1 23:12 activate.csh
-rw-r--r-- 1 mryan mryan 3033 Feb  1 23:12 activate.fish
-rw-r--r-- 1 mryan mryan 1303 Feb  1 23:12 activate.nu
-rw-r--r-- 1 mryan mryan 1754 Feb  1 23:12 activate.ps1
-rw-r--r-- 1 mryan mryan 1199 Feb  1 23:12 activate_this.py
-rw-r--r-- 1 mryan mryan  333 Feb  1 23:12 deactivate.nu
-rwxr-xr-x 1 mryan mryan  249 Feb  1 23:12 pip
-rwxr-xr-x 1 mryan mryan  249 Feb  1 23:12 pip-3.8
-rwxr-xr-x 1 mryan mryan  249 Feb  1 23:12 pip3
-rwxr-xr-x 1 mryan mryan  249 Feb  1 23:12 pip3.8
lrwxrwxrwx 1 mryan mryan   18 Feb  1 23:12 python -> /usr/bin/python3.8
lrwxrwxrwx 1 mryan mryan    6 Feb  1 23:12 python3 -> python
lrwxrwxrwx 1 mryan mryan    6 Feb  1 23:12 python3.8 -> python
-rwxr-xr-x 1 mryan mryan  236 Feb  1 23:12 wheel
-rwxr-xr-x 1 mryan mryan  236 Feb  1 23:12 wheel-3.8
-rwxr-xr-x 1 mryan mryan  236 Feb  1 23:12 wheel3
-rwxr-xr-x 1 mryan mryan  236 Feb  1 23:12 wheel3.8
</code>```

When I try using the command poetry env use 3.10.0 I get the following:

```<code>(.venv) mryan ~/python/fastapi1/.venv/bin $poetry env use 3.10.0
/bin/sh: 1: python3.10: not found

  EnvCommandError

  Command python3.10 -c "import sys; print('.'.join([str(s) for s in sys.version_info[:3]]))" errored with the following return code 127, and output:

  at ~/.local/share/pypoetry/venv/lib/python3.8/site-packages/poetry/utils/env.py:378 in activate
       374│                     shell=True,
       375│                 )
       376│             )
       377│         except CalledProcessError as e:
    →  378│             raise EnvCommandError(e)
       379│
       380│         python_version = Version.parse(python_version.strip())
       381│         minor = "{}.{}".format(python_version.major, python_version.minor)
       382│         patch = python_version.text
(.venv) mryan ~/python/fastapi1/.venv/bin $python3.10
python3.10: command not found
</code>```

What am I doing wrong here? I feel I'm missing something significant here. I've been through a zillion web pages on poetry and virtual environments.

答:
I am surprised that poetry shell creates .venv. Are you certain about that? Or did you maybe create it with virtualenv?

I just kind of replicated what you probably did and did not get the error. I would recommend you to create a minimal, reproducible example. Then you will probably catch what is wrong. For this I case I recommend creating a bash script. A start could be:

```<code>mkdir ~/python/test_error
cd ~/python/test_error
cp ~/python/fastapi1/pyproject.toml .
pyenv local 3.10.0
poetry env use 3.10.0
</code>```

This script works for me (when I change the folders).

Body:
I'm working on WSL2 Ubuntu. I've been taking a course in backend API development using Fastapi. My Ubuntu default python is 3.8 I believe. I'm trying to use python 3.10.0 for my development. I've done the following:

pyenv install 3.10.0

cd to my project folder and pyenv local 3.10.0 (creates .python-version file containing 3.10.0)

poetry shell (this creates a .venv folder and all dependencies are added there during development). Bash Prompt has (.venv) in it.

python --version shows 3.10.0 as current version

My problem is that when I look into the .venv/bin file, all of the symbolic links show python 3.8.

drwxr-xr-x 2 mryan mryan 4096 Feb  1 23:12 .
drwxr-xr-x 4 mryan mryan 4096 Feb  1 23:12 ..
-rw-r--r-- 1 mryan mryan 2152 Feb  1 23:12 activate
-rw-r--r-- 1 mryan mryan 1444 Feb  1 23:12 activate.csh
-rw-r--r-- 1 mryan mryan 3033 Feb  1 23:12 activate.fish
-rw-r--r-- 1 mryan mryan 1303 Feb  1 23:12 activate.nu
-rw-r--r-- 1 mryan mryan 1754 Feb  1 23:12 activate.ps1
-rw-r--r-- 1 mryan mryan 1199 Feb  1 23:12 activate_this.py
-rw-r--r-- 1 mryan mryan  333 Feb  1 23:12 deactivate.nu
-rwxr-xr-x 1 mryan mryan  249 Feb  1 23:12 pip
-rwxr-xr-x 1 mryan mryan  249 Feb  1 23:12 pip-3.8
-rwxr-xr-x 1 mryan mryan  249 Feb  1 23:12 pip3
-rwxr-xr-x 1 mryan mryan  249 Feb  1 23:12 pip3.8
lrwxrwxrwx 1 mryan mryan   18 Feb  1 23:12 python -> /usr/bin/python3.8
lrwxrwxrwx 1 mryan mryan    6 Feb  1 23:12 python3 -> python
lrwxrwxrwx 1 mryan mryan    6 Feb  1 23:12 python3.8 -> python
-rwxr-xr-x 1 mryan mryan  236 Feb  1 23:12 wheel
-rwxr-xr-x 1 mryan mryan  236 Feb  1 23:12 wheel-3.8
-rwxr-xr-x 1 mryan mryan  236 Feb  1 23:12 wheel3
-rwxr-xr-x 1 mryan mryan  236 Feb  1 23:12 wheel3.8

When I try using the command poetry env use 3.10.0 I get the following:

(.venv) mryan ~/python/fastapi1/.venv/bin $poetry env use 3.10.0
/bin/sh: 1: python3.10: not found

  EnvCommandError

  Command python3.10 -c "import sys; print('.'.join([str(s) for s in sys.version_info[:3]]))" errored with the following return code 127, and output:

  at ~/.local/share/pypoetry/venv/lib/python3.8/site-packages/poetry/utils/env.py:378 in activate
       374│                     shell=True,
       375│                 )
       376│             )
       377│         except CalledProcessError as e:
    →  378│             raise EnvCommandError(e)
       379│
       380│         python_version = Version.parse(python_version.strip())
       381│         minor = "{}.{}".format(python_version.major, python_version.minor)
       382│         patch = python_version.text
(.venv) mryan ~/python/fastapi1/.venv/bin $python3.10
python3.10: command not found

What am I doing wrong here? I feel I'm missing something significant here. I've been through a zillion web pages on poetry and virtual environments.

Body:
I am surprised that poetry shell creates .venv. Are you certain about that? Or did you maybe create it with virtualenv?

I just kind of replicated what you probably did and did not get the error. I would recommend you to create a minimal, reproducible example. Then you will probably catch what is wrong. For this I case I recommend creating a bash script. A start could be:

mkdir ~/python/test_error
cd ~/python/test_error
cp ~/python/fastapi1/pyproject.toml .
pyenv local 3.10.0
poetry env use 3.10.0

This script works for me (when I change the folders).


问:
Simple question about Entity Framework
I have this very simple example:

This generates these straightforward classes:

However, when I access the property Cities of any of my User objects read from the database it is always set to null. I thought that the Entity Framework would fill that property. Am I right? What I'm doing wrong?

Thanks.

EDIT: Just as a note I'm using 3.5, not 4 (looks like there are some key differences)

答:
I think you are looking for the Include method</p>

```<code>context.Users.Include("Cities")
</code>```

Title: Simple question about Entity Framework

Body:
I think you are looking for the Include method

context.Users.Include("Cities")


问:
Python DataFrame: Remove/Replace part of a string for all values in a column
In a Dataframe "df" I have a column called "Company". In there I have a list of companies that end with "- CP" the problem is that the spaces are not always in the same place and in some of the entries the dash "-" is missing. I want to remove the "-CP" from all entries.

Input

Company

Intest Apple - CP

Intest Apple -CP

Intest Apple-CP

Intest Apple - CP

Intest Apple CP

Howard P Delta - CP

Output

Company

Intest Apple

Intest Apple

Intest Apple

Intest Apple

Intest Apple

Howard P Delta

This is the code that I have, but when I run it nothing changes

```<code>df['Company'] = df['Company'].str.replace("-CP'","")
df['Company'] = df['Company'].str.replace("- CP'","")
df['Company'] = df['Company'].str.replace(" - CP'","")
</code>```

答:
```<code>df['Company']=df['Company'].str.replace("-CP","")
df['Company'] = df['Company'].str.replace("- CP","")
df['Company'] = df['Company'].str.replace(" - CP","")
</code>```

Body:
In a Dataframe "df" I have a column called "Company". In there I have a list of companies that end with "- CP" the problem is that the spaces are not always in the same place and in some of the entries the dash "-" is missing. I want to remove the "-CP" from all entries.

Input

Company

Intest Apple - CP

Intest Apple -CP

Intest Apple-CP

Intest Apple - CP

Intest Apple CP

Howard P Delta - CP

Output

Company

Intest Apple

Intest Apple

Intest Apple

Intest Apple

Intest Apple

Howard P Delta

This is the code that I have, but when I run it nothing changes

df['Company'] = df['Company'].str.replace("-CP'","")
df['Company'] = df['Company'].str.replace("- CP'","")
df['Company'] = df['Company'].str.replace(" - CP'","")


问:
Split Regex matches into Groups
I have markdown content with multiple images where each image is:

```<code>![Image Description](/image-path.png)
</code>```

I am selecting all images in the markdown content using Regex:

```<code>var matches = new Regex(@"!\[.*?\]\((.*?)\)").Matches(content);
</code>```

I am getting 2 groups:

```<code>Groups[0] = ![Image Description](/image-path.png);  > (Everything)

Groups[1] = /image-path.png                         > (Image Path)
</code>```

Wouldn't be possible to get instead?

```<code>Groups[0] = Image Description.                      > (Image Description)

Groups[1] = /image-path.png                         > (Image Path)
</code>```

答:
Currently the group 1 value is part of the matched string.

You could get the match for Image Description and only /image-path.png) in group 1 using a lookbehind and a lookahead with a capture group:

```<code>(?<=!\[)[^][]*(?=]\(([^()]*)\))
</code>```

The pattern in parts matches:

(?<=![) Assert ![ to the left

[^][]*] Match any char except [ and ]

(?= Positive lookahead to assert to the right

]\(([^()]*)\) Match ] and capture in group 1 what is between (...)

) Close lookahead

.NET regex demo

```<code>string pattern = @"(?<=!\[)[^][]*(?=]\(([^()]*)\))";
string input = @"![Image Description](/image-path.png)";

Match m = Regex.Match(input, pattern);
Console.WriteLine(m.Groups[0]);
Console.WriteLine(m.Groups[1]);
</code>```

Output

```<code>Image Description
/image-path.png
</code>```

Title: Split Regex matches into Groups

Body:
I have markdown content with multiple images where each image is:

![Image Description](/image-path.png)

I am selecting all images in the markdown content using Regex:

var matches = new Regex(@"!\[.*?\]\((.*?)\)").Matches(content);

I am getting 2 groups:

Groups[0] = ![Image Description](/image-path.png);  > (Everything)

Groups[1] = /image-path.png                         > (Image Path)

Wouldn't be possible to get instead?

Groups[0] = Image Description.                      > (Image Description)

Groups[1] = /image-path.png                         > (Image Path)

Body:
Currently the group 1 value is part of the matched string.

You could get the match for Image Description and only /image-path.png) in group 1 using a lookbehind and a lookahead with a capture group:

(?<=!\[)[^][]*(?=]\(([^()]*)\))

The pattern in parts matches:

(?<=![) Assert ![ to the left

[^][]*] Match any char except [ and ]

(?= Positive lookahead to assert to the right

]\(([^()]*)\) Match ] and capture in group 1 what is between (...)

) Close lookahead

.NET regex demo

string pattern = @"(?<=!\[)[^][]*(?=]\(([^()]*)\))";
string input = @"![Image Description](/image-path.png)";

Match m = Regex.Match(input, pattern);
Console.WriteLine(m.Groups[0]);
Console.WriteLine(m.Groups[1]);

Output

Image Description
/image-path.png


问:
Python list: Extract integers from list of strings
I have a list with the following values, which in fact are strings inside the list:

```<code>mylist = ['4, 1, 2', '1, 2', '120, 13', '223, 10']
</code>```

How can I extract each value and create a new list with every value inside the list above?

I need a result like:

```<code>mylist = [4, 1, 2, 1, 2, 120, 13, 223, 10]
</code>```

Thank you in advance

答:
Just use a list comprehension like so:

```<code>mylist = ['4, 1, 2', '1, 2', '120, 13', '223, 10']
output = [int(c) for c in ",".join(mylist).split(",")]
print(output)
</code>```

Output:

```<code>[4, 1, 2, 1, 2, 120, 13, 223, 10]
</code>```

This makes a single string of the values and the separates all of the values into individual strings. It then can turn them into ints with int() and add it to a new list.

Body:
I have a list with the following values, which in fact are strings inside the list:

mylist = ['4, 1, 2', '1, 2', '120, 13', '223, 10']

How can I extract each value and create a new list with every value inside the list above?

I need a result like:

mylist = [4, 1, 2, 1, 2, 120, 13, 223, 10]

Thank you in advance

Body:
Just use a list comprehension like so:

mylist = ['4, 1, 2', '1, 2', '120, 13', '223, 10']
output = [int(c) for c in ",".join(mylist).split(",")]
print(output)

Output:

[4, 1, 2, 1, 2, 120, 13, 223, 10]

This makes a single string of the values and the separates all of the values into individual strings. It then can turn them into ints with int() and add it to a new list.


问:
Sorting columns in iReport
I am using java-jasper report and iReport to build the report. I want to make my report sortable by column.</p>

答:
Coming from definitive guide to iReport book:

Sort and filter options can be set from the Report query dialog box by clicking the buttons labeled Sort options and Filter Expressions.

OwnerDisplayName: Gaurang

Title: Sorting columns in iReport


问:
SQLite_check constraint, which checks that the entered year is at least this year
```<code>P_Year int default 2022 Check (P_Year >= select strftime('%Y','now'))
</code>```

I want to check constraint on p_year, which checks that the entered year is at least the current year. Can somebody help me?

答:
The problem with your code is the SELECT keyword which is invalid inside the check constraint.

If P_Year's data type is TEXT use this:

```<code>CHECK (P_Year >= strftime('%Y','now'))
</code>```

If its data type is INTEGER (as it should be) you must convert the result of strftime() to an integer because it returns a string:

```<code>CHECK (P_Year >= strftime('%Y','now') + 0)
</code>```

See a simplified demo.

Body:
P_Year int default 2022 Check (P_Year >= select strftime('%Y','now'))

I want to check constraint on p_year, which checks that the entered year is at least the current year. Can somebody help me?

Body:
The problem with your code is the SELECT keyword which is invalid inside the check constraint.

If P_Year's data type is TEXT use this:

CHECK (P_Year >= strftime('%Y','now'))

If its data type is INTEGER (as it should be) you must convert the result of strftime() to an integer because it returns a string:

CHECK (P_Year >= strftime('%Y','now') + 0)

See a simplified demo.


问:
'>' not supported between instances of 'str' and 'float'
I am if using if statement with or condition
but this is showing error
first I was wrong with none and or condiotns

```<code>print(farm_acerage)
print(batch_acerage)
print(current_acerage)

if farm_acerage in (None, 0):
   return Response({"error": True, "message": "Add farm first"},
                   status = status.HTTP_200_OK)

if farm_acerage is not None and batch_acerage in (None, 0):
   if current_acerage > farm_acerage:
      return Response({"error": True, "message": "Ckkannot add batch more than farm capacity"},
                      status = status.HTTP_200_OK)

if farm_acerage is not None and batch_acerage is not None:
   batch_acerage = float(batch_acerage) + float(current_acerage)
   if batch_acerage > farm_acerage:
      return Response({"error": True, "message": "Cannot add batch more than farm capacity"},
                      status=status.HTTP_200_OK)

</code>```

The error is

```<code>2.0
None
1.0
'>' not supported between instances of 'str' and 'float'

</code>```

答:
None or 0 will return 0. Indeed, x or y returns x if the truthiness of x is True and y otherwise.

You can work with:

```<code>if batch <strong>== None</strong> or batch <strong>== 0</strong>:
   # …</code>```

or shorter:

```<code>if batch <strong>in</strong> (None, 0):
    # …</code>```

Furthermore your current_acerage is a string, not a float, so you can make a comparison with:

```<code>if batch_acerage in (None, 0) and <strong>float(</strong>current_acerage<strong>)</strong> > farm_acerage:
    return Response(
        {"error": True, "message": "Ckkannot add batch more than farm capacity"},
        status = status.HTTP_200_OK
    )</code>```

Body:
I am if using if statement with or condition
but this is showing error
first I was wrong with none and or condiotns

print(farm_acerage)
print(batch_acerage)
print(current_acerage)

if farm_acerage in (None, 0):
   return Response({"error": True, "message": "Add farm first"},
                   status = status.HTTP_200_OK)

if farm_acerage is not None and batch_acerage in (None, 0):
   if current_acerage > farm_acerage:
      return Response({"error": True, "message": "Ckkannot add batch more than farm capacity"},
                      status = status.HTTP_200_OK)

if farm_acerage is not None and batch_acerage is not None:
   batch_acerage = float(batch_acerage) + float(current_acerage)
   if batch_acerage > farm_acerage:
      return Response({"error": True, "message": "Cannot add batch more than farm capacity"},
                      status=status.HTTP_200_OK)

The error is

2.0
None
1.0
'>' not supported between instances of 'str' and 'float'

Body:
None or 0 will return 0. Indeed, x or y returns x if the truthiness of x is True and y otherwise.

You can work with:

if batch == None or batch == 0:
   # …

or shorter:

if batch in (None, 0):
    # …

Furthermore your current_acerage is a string, not a float, so you can make a comparison with:

if batch_acerage in (None, 0) and float(current_acerage) > farm_acerage:
    return Response(
        {"error": True, "message": "Ckkannot add batch more than farm capacity"},
        status = status.HTTP_200_OK
    )


问:
How to deploy dockerised react + django web app to google app engine?
I have created a web app which uses react as frontend and django as backend. I have also added nginx proxy to my both backend and frontend. I use docker compose to build and start all of my containers and everything works perfectly.

Now i want to deploy it to google app engine and I have no idea how to do that. I found this well written article, but it uses aws. I want to use app engine because its free (for now).

It would be really helpful if someone could guide me through this.

答:
App Engine Standard does not support containers but App Engine Flex does using Custom Runtimes.

Anyway, App Engine Flex does not support docker compose so you need to decouple your app into individual services (react, django, nginx (not necessary at all since GAE already has an NGINX proxy)) by using your own container for each element or use the already available runtimes when applies.

Then you can connect each other by using the App Engine URLs. This article can help you understand this approach (it is for NodeJS but the idea is the same).


问:
Show the content of the function in the div
How do I show myFunction content in myDiv div? So show "Example"?

function myFunction() {
  document.getElementById("demo").innerHTML = "Example!";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.myDiv {
  border: 5px outset red;
  background-color: lightblue;
  text-align: center;
}</code>```

```

答: I think you are not clear about the concept of html,CSS and js.myDiv is a CSS class.You can beatify the class in it.Whatever html tag uses that class will integrate the proper of .myDiv class. myFunction() is a js function if you use the demo id in your html tag and it will act according to your function defination.</p>

Body:
How do I show myFunction content in myDiv div? So show "Example"?

function myFunction() {
  document.getElementById("demo").innerHTML = "Example!";
}

.myDiv {
  border: 5px outset red;
  background-color: lightblue;
  text-align: center;
}


问:
Shape of a numpy array when being passed as an input to Input in Keras
I am reading a book about Deep Learning and I am currently learning about Keras functional API in it. In the context:

"The input layer takes a shape argument that is a tuple that indicates the
dimensionality of the input data. When input data is one-dimensional, such as for a Multilayer
Perceptron, the shape must explicitly leave room for the shape of the minibatch size used when
splitting the data when training the network. Therefore, the shape tuple is always defined
with a hanging last dimension (2,), this is the way you must define a one-dimensional tuple in
Python, for example:"

I did not quite understand the shape part - why is the second parameter left empty? What does keeping it empty mean? None means that it could take any shape but what is happening here? Also, about the mini batch size - isn't only one data processed at a time in a NN and with mini batch - we update the learning rate (if using sgd) after every batch of data gets evaluated with our model. Then why do we need to change the dimension of our input shape to accommodate this? - shouldn't only one data instance go at a time?

答:
If your data was two-dimensional (e.g. a greyscale image) then the numpy array would be of shape (height, width), for example. With a one-dimensional input though, you might be tempted to say its shape is just length. When you say (length,) instead, the difference is that you have not an integer, but a tuple with one element.

The idea about batches is that multiple are processed at once to speed training up. How exactly that works internally, I am not sure of, but oftentimes you actually have more than one instance in a batch. I believe the gradient descent simply does not update the weights between each instance and instead it is only updated after each batch - which means that every instance in a batch can be computed in parallel.

My guess why they point out that the shape being a tuple is relevant is that there is no special case handling for when the shape is just an integer. E.g. you can loop over a tuple's entries, but not over an integer.

Notice also that the shape of a numpy array is also a tuple:

>>> import numpy as np
>>> np.array([1,2,3]).shape
(3,)
```

so you can use array.shape directly if you wish to do so.

Technically, you could use batches but set the batch size to 1. That can be confusing though, because if you use squeeze somewhere, it will get rid of the batch dimension as well.

Body:
If your data was two-dimensional (e.g. a greyscale image) then the numpy array would be of shape (height, width), for example. With a one-dimensional input though, you might be tempted to say its shape is just length. When you say (length,) instead, the difference is that you have not an integer, but a tuple with one element.

The idea about batches is that multiple are processed at once to speed training up. How exactly that works internally, I am not sure of, but oftentimes you actually have more than one instance in a batch. I believe the gradient descent simply does not update the weights between each instance and instead it is only updated after each batch - which means that every instance in a batch can be computed in parallel.

My guess why they point out that the shape being a tuple is relevant is that there is no special case handling for when the shape is just an integer. E.g. you can loop over a tuple's entries, but not over an integer.

Notice also that the shape of a numpy array is also a tuple:

>>> import numpy as np
>>> np.array([1,2,3]).shape
(3,)

so you can use array.shape directly if you wish to do so.

Technically, you could use batches but set the batch size to 1. That can be confusing though, because if you use squeeze somewhere, it will get rid of the batch dimension as well.


问:
Outer overflow div does not adjust size with scale
I have an outer div with a fixed size that uses a scroll for overflow. In it there is an inner div which is larger than the outer div. Therefore the overflow can be accessed by scrolling. This works without scaling as one would expect.

With a scaling on the inner div enabled, e. g. 0.7. The inner div is scaled down as expected. However, the scroll does not decrease in size as I would expect. There is space around the div which I can see by scrolling.

How can I fix this? Thank you very much.

.outer {
  overflow: scroll;
  width: 300px;
  height: 300px;
}

.inner {
  width: 1000px;
  height: 1000px;
  background-color: brown;
}

.inner-scaled {
  transform: scale(0.7);
  transform-origin: 0 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
  When I do not scale, the whole outer div is filled with the inner div. Scrolling works as expected and the red element fills all the space in the scroll.
</p>

<div class="outer">
  <div class="inner"></div>
</div>

<p>
  When I scale down, I see that the inner red element is smaller, as I would expect. However, I would also expect, that the outer div scaling range adjusts to the new size. This does not seem to be the case, as a white space around the element within the
  scroll exists.
</p>

<b>How can I fix this to adjust the size?</b>

<div class="outer">
  <div class="inner inner-scaled"></div>
</div></code>```

答:
I'm not entirely sure what your expected outcome is but why don't you put the scale on the outer?

I have also set the width of the inner div to 100% so it scales with the outer since you did not seem to allow horizontal scrolling.

.outer {
  overflow: scroll;
  width: 300px;
  height: 300px;
}

.inner {
  width: 100%;
  height: 1000px;
  background-color: brown;
}

.outer-scaled {
  transform: scale(0.7);
  transform-origin: 0 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
  When I do not scale, the whole outer div is filled with the inner div. Scrolling works as expected and the red element fills all the space in the scroll.
</p>

<div class="outer">
  <div class="inner"></div>
</div>

<p>
  When I scale down, I see that the inner red element is smaller, as I would expect. However, I would also expect, that the outer div scaling range adjusts to the new size. This does not seem to be the case, as a white space around the element within the
  scroll exists.
</p>

<b>How can I fix this to adjust the size?</b>

<div class="outer outer-scaled">
  <div class="inner"></div>
</div></code>```

Body:
I have an outer div with a fixed size that uses a scroll for overflow. In it there is an inner div which is larger than the outer div. Therefore the overflow can be accessed by scrolling. This works without scaling as one would expect.

With a scaling on the inner div enabled, e. g. 0.7. The inner div is scaled down as expected. However, the scroll does not decrease in size as I would expect. There is space around the div which I can see by scrolling.

How can I fix this? Thank you very much.

.outer {
  overflow: scroll;
  width: 300px;
  height: 300px;
}

.inner {
  width: 1000px;
  height: 1000px;
  background-color: brown;
}

.inner-scaled {
  transform: scale(0.7);
  transform-origin: 0 0;
}

  When I do not scale, the whole outer div is filled with the inner div. Scrolling works as expected and the red element fills all the space in the scroll.

  When I scale down, I see that the inner red element is smaller, as I would expect. However, I would also expect, that the outer div scaling range adjusts to the new size. This does not seem to be the case, as a white space around the element within the
  scroll exists.

How can I fix this to adjust the size?

Body:
I'm not entirely sure what your expected outcome is but why don't you put the scale on the outer?

I have also set the width of the inner div to 100% so it scales with the outer since you did not seem to allow horizontal scrolling.

.outer {
  overflow: scroll;
  width: 300px;
  height: 300px;
}

.inner {
  width: 100%;
  height: 1000px;
  background-color: brown;
}

.outer-scaled {
  transform: scale(0.7);
  transform-origin: 0 0;
}

<p>
  When I do not scale, the whole outer div is filled with the inner div. Scrolling works as expected and the red element fills all the space in the scroll.
</p>

<div class="outer">
  <div class="inner"></div>
</div>

<p>
  When I scale down, I see that the inner red element is smaller, as I would expect. However, I would also expect, that the outer div scaling range adjusts to the new size. This does not seem to be the case, as a white space around the element within the
  scroll exists.
</p>

<b>How can I fix this to adjust the size?</b>

<div class="outer outer-scaled">
  <div class="inner"></div>
</div>


问:
How to add lfs support to this git setup?
I've set up my git repos like this: a bare repo on my HDD and a clone of it on my SSD. The bare repo is acting as a backup. Now I want to add lfs support to it and can't figure out how. I tried doing this in the clone repo:

```<code>git lfs install
git lfs track '*.png'
</code>```

Now I create test.png in that directory.

```<code>git add .
git commit -m "added png file"
git push origin master
</code>```

After running the last line I get this error:

```<code>Remote "origin" does not support the LFS locking API. Consider disabling it with:
$ git config lfs.D:/Git/test.git/info/lfs.locksverify false
batch request: missing protocol: "D:/Git/test.git/info/lfs"
error: failed to push some refs to 'D:/Git/test.git'
</code>```

Doing git config lfs.D:/Git/test.git/info/lfs.locksverify false doesn't help.
I think I'm misunderstanding how lfs sould be set up, but I couldn't find any tutorials on how to do it locally. I'm also not sure if it can even work without a server for lfs cache. Any help on how to set this up would be appreciated!

答: @alierdogan7: On Bitbucket, the LFS support is enabled in the repository settings (toothed wheel, lower left side)</p>

Body:
I've set up my git repos like this: a bare repo on my HDD and a clone of it on my SSD. The bare repo is acting as a backup. Now I want to add lfs support to it and can't figure out how. I tried doing this in the clone repo:

git lfs install
git lfs track '*.png'

Now I create test.png in that directory.

git add .
git commit -m "added png file"
git push origin master

After running the last line I get this error:

Remote "origin" does not support the LFS locking API. Consider disabling it with:
$ git config lfs.D:/Git/test.git/info/lfs.locksverify false
batch request: missing protocol: "D:/Git/test.git/info/lfs"
error: failed to push some refs to 'D:/Git/test.git'

Doing git config lfs.D:/Git/test.git/info/lfs.locksverify false doesn't help.
I think I'm misunderstanding how lfs sould be set up, but I couldn't find any tutorials on how to do it locally. I'm also not sure if it can even work without a server for lfs cache. Any help on how to set this up would be appreciated!


答:
This code:

```<code><div class="myDiv">
<p> id="demo"</p>
</div>
</code>```

Should be this:

```<code><div class="myDiv">
<p id="demo"></p>
</div>
</code>```

With the id tag inside

And this:

```<code>function myFunction() {
  document.getElementById("demo").innerHTML = "Example!";
}
</code>```

Should also get called since it is a function and not just the document.getElementById("demo").innerHTML = "Example!";

Example 1:

```<code>function myFunction() {
      document.getElementById("demo").innerHTML = "Example!";
    }
myFunction();
</code>```

function myFunction() {
      document.getElementById("demo").innerHTML = "Example!";
    }

myFunction();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.myDiv {
  border: 5px outset red;
  background-color: lightblue;
  text-align: center;
}</code>```

```
</div>
</div>
</p>
<p>Example 2:</p>
```document.getElementById("demo").innerHTML = "Example!";
```
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.getElementById("demo").innerHTML = "Example!";</code>```

.myDiv {
  border: 5px outset red;
  background-color: lightblue;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="myDiv">
<p id="demo"></p>
</div></code>```

Title: Show the content of the function in the div

Body:
This code:

<div class="myDiv">
<p> id="demo"</p>
</div>

Should be this:

<div class="myDiv">
<p id="demo"></p>
</div>

With the id tag inside <p>

And this:

function myFunction() {
  document.getElementById("demo").innerHTML = "Example!";
}

Should also get called since it is a function and not just the document.getElementById("demo").innerHTML = "Example!";

Example 1:

function myFunction() {
      document.getElementById("demo").innerHTML = "Example!";
    }
myFunction();

function myFunction() {
      document.getElementById("demo").innerHTML = "Example!";
    }

myFunction();

.myDiv {
  border: 5px outset red;
  background-color: lightblue;
  text-align: center;
}

<div class="myDiv">
<p id="demo"></p>
</div>

Example 2:

document.getElementById("demo").innerHTML = "Example!";

document.getElementById("demo").innerHTML = "Example!";

.myDiv {
  border: 5px outset red;
  background-color: lightblue;
  text-align: center;
}

<div class="myDiv">
<p id="demo"></p>
</div>


问:
Need JS equivalent
Python Code:

```<code>signature = hmac.new(bytearray.fromhex(key), data.encode('utf-8'), hashlib.sha256).hexdigest()
</code>```

Solutions That I have tried

```<code>var compute_hmac = crypto.createHmac('sha256', key).update(data).digest('hex');

var compute_hmac = crypto.createHmac('sha256', Buffer.from(key, 'hex').toString()).update(data).digest('hex');
</code>```

const hmac = crypto.createHmac('sha256',   Buffer.from(key, 'hex'))

Trying to validate webhook signatures of the following API

https://developer.close.com/topics/webhooks/

data is the payload received, the same thing is passed to python and JS code. But somehow, hex digest of python code is validated and hex code of JS code is entirely different.

Please refer to API link mentioned above (webhook signatures) to understand what I'm trying to achieve

答:
Pass directly the keybuffer instead of adding .toString() to it

```<code>var compute_hmac = crypto.createHmac('sha256', Buffer.from(key, 'hex')).update(data).digest('hex');
</code>```

py code

```<code>import hashlib
import hmac

key ="A1FF92";
data = "hello"

signature = hmac.new(bytearray.fromhex(key), data.encode('utf-8'), hashlib.sha256).hexdigest()
//78a1151ddd4f298a134e4625362af2ab8ef4bd49719e17053ec1eadd4cbf1bab
</code>```

node code

```<code>var crypto = require("crypto")
var key = "A1FF92"
var data="hello";
var compute_hmac = crypto.createHmac('sha256', Buffer.from(key, 'hex')).update(data).digest('hex');

// 78a1151ddd4f298a134e4625362af2ab8ef4bd49719e17053ec1eadd4cbf1bab
</code>```

Title: Need JS equivalent

Body:
Python Code:

signature = hmac.new(bytearray.fromhex(key), data.encode('utf-8'), hashlib.sha256).hexdigest()

Solutions That I have tried

var compute_hmac = crypto.createHmac('sha256', key).update(data).digest('hex');

var compute_hmac = crypto.createHmac('sha256', Buffer.from(key, 'hex').toString()).update(data).digest('hex');

const hmac = crypto.createHmac('sha256',   Buffer.from(key, 'hex'))

Trying to validate webhook signatures of the following API

https://developer.close.com/topics/webhooks/

data is the payload received, the same thing is passed to python and JS code. But somehow, hex digest of python code is validated and hex code of JS code is entirely different.

Please refer to API link mentioned above (webhook signatures) to understand what I'm trying to achieve

Body:
Pass directly the keybuffer instead of adding .toString() to it

var compute_hmac = crypto.createHmac('sha256', Buffer.from(key, 'hex')).update(data).digest('hex');

py code

import hashlib
import hmac

key ="A1FF92";
data = "hello"

signature = hmac.new(bytearray.fromhex(key), data.encode('utf-8'), hashlib.sha256).hexdigest()
//78a1151ddd4f298a134e4625362af2ab8ef4bd49719e17053ec1eadd4cbf1bab

node code

var crypto = require("crypto")
var key = "A1FF92"
var data="hello";
var compute_hmac = crypto.createHmac('sha256', Buffer.from(key, 'hex')).update(data).digest('hex');

// 78a1151ddd4f298a134e4625362af2ab8ef4bd49719e17053ec1eadd4cbf1bab


问:
Alignment of flex items
I have a wrapper which is display:flex and equally spaces the items horizontally. Those items have display:flex also but are flex-direction:column these are basically an image and a span wrapped in a button. What is happening is when the span the breaks onto 2 lines it misaligning the top of the images so they look out of line, is there a way around this?

You can see the problem here

答:
You've got align-items: center on your main .bottle-refill-options container, which is vertically centering everything.

Change this to align-items: flex-start; and all your items will vertically center along the top, giving the look (i think) you want

Title: Alignment of flex items


问:
Generic Data Access Layer in an Multi-Layer Arcitechture
I need to create an generic data access layer to use in my final assignment in Software Engineering, but my data access layer that I have currently created can automatically generate CRUD(Create, Read, Update and Delete) SQL Statement. I still need to define every table in my database and every time I change my database I need to define the changes in my data access layer.

Please look at the sample of my code and tell me how to change my code to improve my access layer:

```<code>class sqlConn
{
    //Local
    private String strConn = @"Data Source=.\SQLEXPRESS;" +
        @"AttachDbFilename='D:\JP Stuff\BELGIUM CAMPUS\3de Jaar\SOFTWARE ENGINEERING\ASSIGNMENT\Premier Service Solutions\Premier Service Solutions\DB\db_PSS_1.0.mdf';" +
        @"Integrated Security=True;" +
        @"User Instance=True";
    private SqlConnection conn;

    //Properties
    public SqlConnection Conn
    {
        get { return this.conn = new SqlConnection(this.strConn); }
    }

    //Constructor
    public sqlConn()
    {

    }
}

class sqlFactory : sqlConn
{
    //Constructor
    public sqlFactory()
        : base()
    {

    }

    //Insert Record into database
    public void Create(String[] dbData, List<String> strRow)
    {
        using (SqlConnection sqlCon = this.Conn)
        using (SqlCommand com = new SqlCommand("SELECT * FROM " + dbData[0], sqlCon))
        {
            SqlDataAdapter da = new SqlDataAdapter(com);
            SqlCommandBuilder sqlbuilder = new SqlCommandBuilder(da);

            DataSet ds = new DataSet();
            da.Fill(ds, dbData[0]);

            DataRow dr = ds.Tables[dbData[0]].NewRow();

            for (int i = 0; i < dbData.Count() - 2; i++)
            {
                dr[i + 1] = strRow[i];
            }

            ds.Tables[dbData[0]].Rows.Add(dr);
            da.Update(ds, dbData[0]);
        }
    }
}

 class dbDefinitions : sqlFactory
 {
    public static Dictionary<String, String[]> columns;

    static dbDefinitions()
    {
        columns = new Dictionary<String,String[]>();

        //tblCall Definition
        #region call
        String[] data = new String[]
        {
            "tblCall", "call_ID_PK", "call_emp_ID_FK",
            "call_Description", "call_Notes", "call_Start_Time",
            "call_End_Time", "call_Job_FK"
        };
        columns.Add("call", data);
        #endregion
    }
}
</code>```

答: Try defining the database schema information in an xml file and read it to create the CRUD operations.</p>

Body:
I need to create an generic data access layer to use in my final assignment in Software Engineering, but my data access layer that I have currently created can automatically generate CRUD(Create, Read, Update and Delete) SQL Statement. I still need to define every table in my database and every time I change my database I need to define the changes in my data access layer.

Please look at the sample of my code and tell me how to change my code to improve my access layer:

class sqlConn
{
    //Local
    private String strConn = @"Data Source=.\SQLEXPRESS;" +
        @"AttachDbFilename='D:\JP Stuff\BELGIUM CAMPUS\3de Jaar\SOFTWARE ENGINEERING\ASSIGNMENT\Premier Service Solutions\Premier Service Solutions\DB\db_PSS_1.0.mdf';" +
        @"Integrated Security=True;" +
        @"User Instance=True";
    private SqlConnection conn;

    //Properties
    public SqlConnection Conn
    {
        get { return this.conn = new SqlConnection(this.strConn); }
    }

    //Constructor
    public sqlConn()
    {

    }
}

class sqlFactory : sqlConn
{
    //Constructor
    public sqlFactory()
        : base()
    {

    }

    //Insert Record into database
    public void Create(String[] dbData, List<String> strRow)
    {
        using (SqlConnection sqlCon = this.Conn)
        using (SqlCommand com = new SqlCommand("SELECT * FROM " + dbData[0], sqlCon))
        {
            SqlDataAdapter da = new SqlDataAdapter(com);
            SqlCommandBuilder sqlbuilder = new SqlCommandBuilder(da);

            DataSet ds = new DataSet();
            da.Fill(ds, dbData[0]);

            DataRow dr = ds.Tables[dbData[0]].NewRow();

            for (int i = 0; i < dbData.Count() - 2; i++)
            {
                dr[i + 1] = strRow[i];
            }

            ds.Tables[dbData[0]].Rows.Add(dr);
            da.Update(ds, dbData[0]);
        }
    }
}

 class dbDefinitions : sqlFactory
 {
    public static Dictionary<String, String[]> columns;

    static dbDefinitions()
    {
        columns = new Dictionary<String,String[]>();

        //tblCall Definition
        #region call
        String[] data = new String[]
        {
            "tblCall", "call_ID_PK", "call_emp_ID_FK",
            "call_Description", "call_Notes", "call_Start_Time",
            "call_End_Time", "call_Job_FK"
        };
        columns.Add("call", data);
        #endregion
    }
}


问:
Converting this table of rgb values to hex color values?
how would i convert this:

```<code>import json

import cv2 as cv2

import numpy as np

class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
                            np.int16, np.int32, np.int64, np.uint8,
                            np.uint16, np.uint32, np.uint64)):
            return int(obj)
        elif isinstance(obj, (np.float_, np.float16, np.float32,
                              np.float64)):
            return float(obj)
        elif isinstance(obj, (np.ndarray,)):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

jsonReturn = json.dumps(cv2.resize(Frame, self.Resolution, interpolation=cv2.INTER_NEAREST), cls=NumpyEncoder)

</code>```

to all hex color values?

 (Note: There is ]] and [[ at some points)]

答:
my attempt:

input, 'test.png':

code :

```<code>import json

import cv2 as cv2

import numpy as np

Frame = cv2.imread('test.png')

print((Frame.shape[0],(Frame.shape[1])))

Resolution = (Frame.shape[0],Frame.shape[1])

def rgb_to_hex(i):
    """Return color as #rrggbb for the given color values."""
    return '#%02x' % (i)

class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):

        if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
                            np.int16, np.int32, np.int64, np.uint8,
                            np.uint16, np.uint32, np.uint64)):
            return int(obj)
        elif isinstance(obj, (np.float_, np.float16, np.float32,
                              np.float64)):
            return float(obj)
        elif isinstance(obj, (np.ndarray,)):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

pippo = cv2.resize(Frame, Resolution, interpolation=cv2.INTER_NEAREST).astype('int')

# print(pippo, type(pippo))

rgb_to_hex_vectorized = np.vectorize(rgb_to_hex)

pippo = rgb_to_hex_vectorized(pippo)

# print(pippo, type(pippo))

jsonReturn = json.dumps(pippo, cls=NumpyEncoder)

with open('saved.json', 'w') as fil:
     fil.write(jsonReturn)
</code>```

output:

Body:
how would i convert this:

import json

import cv2 as cv2

import numpy as np

class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
                            np.int16, np.int32, np.int64, np.uint8,
                            np.uint16, np.uint32, np.uint64)):
            return int(obj)
        elif isinstance(obj, (np.float_, np.float16, np.float32,
                              np.float64)):
            return float(obj)
        elif isinstance(obj, (np.ndarray,)):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

jsonReturn = json.dumps(cv2.resize(Frame, self.Resolution, interpolation=cv2.INTER_NEAREST), cls=NumpyEncoder)

to all hex color values?

 (Note: There is ]] and [[ at some points)]

Body:
my attempt:

input, 'test.png':

code :

import json

import cv2 as cv2

import numpy as np

Frame = cv2.imread('test.png')

print((Frame.shape[0],(Frame.shape[1])))

Resolution = (Frame.shape[0],Frame.shape[1])

def rgb_to_hex(i):
    """Return color as #rrggbb for the given color values."""
    return '#%02x' % (i)

class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):

        if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
                            np.int16, np.int32, np.int64, np.uint8,
                            np.uint16, np.uint32, np.uint64)):
            return int(obj)
        elif isinstance(obj, (np.float_, np.float16, np.float32,
                              np.float64)):
            return float(obj)
        elif isinstance(obj, (np.ndarray,)):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

pippo = cv2.resize(Frame, Resolution, interpolation=cv2.INTER_NEAREST).astype('int')

# print(pippo, type(pippo))

rgb_to_hex_vectorized = np.vectorize(rgb_to_hex)

pippo = rgb_to_hex_vectorized(pippo)

# print(pippo, type(pippo))

jsonReturn = json.dumps(pippo, cls=NumpyEncoder)

with open('saved.json', 'w') as fil:
     fil.write(jsonReturn)

output:


问:
JsonConvert.SerializeObject() not serializing a List(of T) where T is a custom Class of mine
I am trying to format Quote items data into a JSON Object to later save to MySQL. the following code produces JSONObject, which is returning an empty JSON object, like this: [{}], even though Quote_Items_Info_Data IS NOT empty. No errors are being triggered!
Why on earth is JsonConvert is not serializing?

```<code>Friend Class JSON_Quote_Item
    Friend Property ItemNumber As String
    Friend Property ItemDescription As String
    Friend Property ItemQty As String
    Friend Property ItemPrice As String
    Public Sub New()
    End Sub
    Public Sub New(ByVal _ItemNumber As String, ByVal _ItemDescription As String, ByVal _itemQty As String, ByVal _itemPrice As String)
        ItemNumber = _ItemNumber.Trim.Replace(vbCrLf, "\r\n").Replace(Chr(34), "\" & Chr(34)).Replace("'", "\'")
        ItemDescription = _ItemDescription.Trim.Replace(vbCrLf, "\r\n").Replace(Chr(34), "\" & Chr(34)).Replace("'", "\'")
        ItemQty = _itemQty.Trim
        ItemPrice = _itemPrice.Trim
    End Sub
End Class
'
'
''' <summary>
''' Convert all Quote items to a JSON object on the form and save it to the server DB.
''' senderFRM is the Quote Creator/Editor. Following an example from: https://www.newtonsoft.com/json/help/html/SerializingCollections.htm
''' and https://www.newtonsoft.com/json
''' </summary>
''' <param name="senderFRM"></param>
''' <returns></returns>
Friend Function SaveAllQuoteItems(senderFRM As frmQuotesCreatorEditor) As Boolean
    Try
        'make sure I will not run into an exception!
        If senderFRM IsNot Nothing AndAlso String.IsNullOrEmpty(senderFRM.txtQuoteNumber.Text.Trim) = False Then
            Dim QuoteNumber As String = senderFRM.txtQuoteNumber.Text.Trim
            'Holds a list of the custom class JSON_Quote_Item as T and contain all the form quote items data.
            Dim Quote_Items_Info_Data As List(Of JSON_Quote_Item) = New List(Of JSON_Quote_Item)
            '

            '
            'Go thru all FlowLayout controls in the form with the finality of finding the Quote items data and put this into a JSON (serialized) string.
            For Each myPanel As Panel In senderFRM.flpQuoteItems.Controls.OfType(Of Panel)
                Dim myElementHost As ElementHost = myPanel.Controls.OfType(Of ElementHost).FirstOrDefault
                Dim MyUserControl_QuoteItem As UserControl_QuoteItem = TryCast(myElementHost.Child, UserControl_QuoteItem)
                '
                Dim myQuoteItemNumber As String = MyUserControl_QuoteItem.txtItemNumber.Text
                Dim myQuoteItemDescription As String = MyUserControl_QuoteItem.txtItemDescription.Text
                Dim myQuoteItemQty As String = MyUserControl_QuoteItem.txtItemQty.Text
                Dim MyQuoteItemPrice As String = MyUserControl_QuoteItem.txtItemListedCustomerPrice.Text
                '
                'Perhaps not necessary but here to check that all parameters contain data.
                If String.IsNullOrEmpty(myQuoteItemNumber) = False And String.IsNullOrEmpty(myQuoteItemDescription) = False And
                    String.IsNullOrEmpty(myQuoteItemQty) = False And String.IsNullOrEmpty(MyQuoteItemPrice) = False Then
                    'add the data to the list of UserControl_QuoteItem
                    Quote_Items_Info_Data.Add(New JSON_Quote_Item(myQuoteItemNumber, myQuoteItemDescription, MyQuoteItemPrice, myQuoteItemQty))
                End If
            Next
            '
            Dim JSONObject As Object = DBNull.Value
            If Quote_Items_Info_Data IsNot Nothing AndAlso Quote_Items_Info_Data.Count > 0 Then
                '
                'NuGet - Newtonsoft.Json.JsonConvert
                'Return as string, but will keep as an object to be able to use it on the parameterization of the SQL query later!
                JSONObject = JsonConvert.SerializeObject(Quote_Items_Info_Data)
            End If
            '
            Console.WriteLine(JSONObject.ToString)
            'JSONObject is returning an empty JSON Object returning this: [{}] ,  even though Quote_Items_Info_Data was not empty.
            'Why on earth is JsonConvert is not serializing?
            '
            'Code to save to the quote column in the database code goes here if the above ever Works!
        End If
        Return True
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try
    Return False
End Function
</code>```

答:
The problem was indeed the Declaration Access Level being FRIEND.So:
this:

```<code>    Public Property ItemNumber As String
    Public Property ItemDescription As String
    Public Property ItemQty As String
    Public Property ItemPrice As String
</code>```

Do work Too and is much cleaner!
Thanks, @Jimi, sometimes one gets blinded!

Body:
I am trying to format Quote items data into a JSON Object to later save to MySQL. the following code produces JSONObject, which is returning an empty JSON object, like this: [{}], even though Quote_Items_Info_Data IS NOT empty. No errors are being triggered!
Why on earth is JsonConvert is not serializing?

Friend Class JSON_Quote_Item
    Friend Property ItemNumber As String
    Friend Property ItemDescription As String
    Friend Property ItemQty As String
    Friend Property ItemPrice As String
    Public Sub New()
    End Sub
    Public Sub New(ByVal _ItemNumber As String, ByVal _ItemDescription As String, ByVal _itemQty As String, ByVal _itemPrice As String)
        ItemNumber = _ItemNumber.Trim.Replace(vbCrLf, "\r\n").Replace(Chr(34), "\" & Chr(34)).Replace("'", "\'")
        ItemDescription = _ItemDescription.Trim.Replace(vbCrLf, "\r\n").Replace(Chr(34), "\" & Chr(34)).Replace("'", "\'")
        ItemQty = _itemQty.Trim
        ItemPrice = _itemPrice.Trim
    End Sub
End Class
'
'
'''
''' Convert all Quote items to a JSON object on the form and save it to the server DB.
''' senderFRM is the Quote Creator/Editor. Following an example from: https://www.newtonsoft.com/json/help/html/SerializingCollections.htm
''' and https://www.newtonsoft.com/json
'''
''' <param name="senderFRM"></param>
''' <returns></returns>
Friend Function SaveAllQuoteItems(senderFRM As frmQuotesCreatorEditor) As Boolean
    Try
        'make sure I will not run into an exception!
        If senderFRM IsNot Nothing AndAlso String.IsNullOrEmpty(senderFRM.txtQuoteNumber.Text.Trim) = False Then
            Dim QuoteNumber As String = senderFRM.txtQuoteNumber.Text.Trim
            'Holds a list of the custom class JSON_Quote_Item as T and contain all the form quote items data.
            Dim Quote_Items_Info_Data As List(Of JSON_Quote_Item) = New List(Of JSON_Quote_Item)
            '

            '
            'Go thru all FlowLayout controls in the form with the finality of finding the Quote items data and put this into a JSON (serialized) string.
            For Each myPanel As Panel In senderFRM.flpQuoteItems.Controls.OfType(Of Panel)
                Dim myElementHost As ElementHost = myPanel.Controls.OfType(Of ElementHost).FirstOrDefault
                Dim MyUserControl_QuoteItem As UserControl_QuoteItem = TryCast(myElementHost.Child, UserControl_QuoteItem)
                '
                Dim myQuoteItemNumber As String = MyUserControl_QuoteItem.txtItemNumber.Text
                Dim myQuoteItemDescription As String = MyUserControl_QuoteItem.txtItemDescription.Text
                Dim myQuoteItemQty As String = MyUserControl_QuoteItem.txtItemQty.Text
                Dim MyQuoteItemPrice As String = MyUserControl_QuoteItem.txtItemListedCustomerPrice.Text
                '
                'Perhaps not necessary but here to check that all parameters contain data.
                If String.IsNullOrEmpty(myQuoteItemNumber) = False And String.IsNullOrEmpty(myQuoteItemDescription) = False And
                    String.IsNullOrEmpty(myQuoteItemQty) = False And String.IsNullOrEmpty(MyQuoteItemPrice) = False Then
                    'add the data to the list of UserControl_QuoteItem
                    Quote_Items_Info_Data.Add(New JSON_Quote_Item(myQuoteItemNumber, myQuoteItemDescription, MyQuoteItemPrice, myQuoteItemQty))
                End If
            Next
            '
            Dim JSONObject As Object = DBNull.Value
            If Quote_Items_Info_Data IsNot Nothing AndAlso Quote_Items_Info_Data.Count > 0 Then
                '
                'NuGet - Newtonsoft.Json.JsonConvert
                'Return as string, but will keep as an object to be able to use it on the parameterization of the SQL query later!
                JSONObject = JsonConvert.SerializeObject(Quote_Items_Info_Data)
            End If
            '
            Console.WriteLine(JSONObject.ToString)
            'JSONObject is returning an empty JSON Object returning this: [{}] ,  even though Quote_Items_Info_Data was not empty.
            'Why on earth is JsonConvert is not serializing?
            '
            'Code to save to the quote column in the database code goes here if the above ever Works!
        End If
        Return True
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try
    Return False
End Function

Body:
The problem was indeed the Declaration Access Level being FRIEND.So:
this:

    Public Property ItemNumber As String
    Public Property ItemDescription As String
    Public Property ItemQty As String
    Public Property ItemPrice As String

Do work Too and is much cleaner!
Thanks, @Jimi, sometimes one gets blinded!


问:
How to get all selected indices in a datagrid
I have a datagrid with the option SelectionMode = DataGridSelectionMode.Extended.

With that I can select various row.

I would like to know the indices of the selected rows.
I am aware that I can get dtg_ExecutionTimes_PpDescriptions.SelectedItems but I am not able to retrieve the indices from that list.
For example in the picture it is 1 and 3 (or 0 and 2)

Thanx

答:
There are different ways, if you don't have reference duplicates in your items source (what is usually the case), then you can iterate through the items and get the indexes:</p>
```<code>var selIndexes = new List<int>();
foreach (var selItem in dtg_ExecutionTimes_PpDescriptions.SelectedItems)
{
    selIndexes.Add(dtg_ExecutionTimes_PpDescriptions.Items.IndexOf(selItem));
}
</code>```

Body:
There are different ways, if you don't have reference duplicates in your items source (what is usually the case), then you can iterate through the items and get the indexes:

var selIndexes = new List<int>();
foreach (var selItem in dtg_ExecutionTimes_PpDescriptions.SelectedItems)
{
    selIndexes.Add(dtg_ExecutionTimes_PpDescriptions.Items.IndexOf(selItem));
}


答:
This may not answer your question fully, but you can improve this code in several ways.

Composition versus Inheritance

First, understand and apply composition over inheritance. Composition is a "has a" relationship, whereas inheritance is a "is a" relationship.

For example, if a Person class has a property of the Phone class type, it's composition.

```<code>public class Person
{
    public Phone Phone {get; set;}
}
</code>```

If a Person class descends from the Phone class it's inheritance.

```<code>public class Person : Phone
{
}
</code>```

In your code, sqlFactory should contain a sqlConn instead of inheriting from it.

Composition gives more flexibility, especially since C# doesn't allow for multiple inheritance. Read here for more: Prefer composition over inheritance?

SQL Injection

You should never build sql statements using string concatenation like this.

```<code>"SELECT * FROM " + dbData[0]
</code>```

This creates a potential security hole that allows for SQL Injection attacks. You should always use parameterized queries to prevent against this.

Read Tip/Trick: Guard Against SQL Injection Attacks to understand SQL Injection attacks and how to prevent them.

Coding Convention

The nearly universally accepted convention for class naming amongst C# developers is to use PascalCase, where the first letter of every word in your class name is capitalized. Your classes would be SqlFactory, SqlConn, and DbDefinition.

This guide gives fairly commonly used conventions: C# Coding Standards document

Title: Generic Data Access Layer in an Multi-Layer Arcitechture

Body:
This may not answer your question fully, but you can improve this code in several ways.

Composition versus Inheritance

First, understand and apply composition over inheritance. Composition is a "has a" relationship, whereas inheritance is a "is a" relationship.

For example, if a Person class has a property of the Phone class type, it's composition.

public class Person
{
    public Phone Phone {get; set;}
}

If a Person class descends from the Phone class it's inheritance.

public class Person : Phone
{
}

In your code, sqlFactory should contain a sqlConn instead of inheriting from it.

Composition gives more flexibility, especially since C# doesn't allow for multiple inheritance. Read here for more: Prefer composition over inheritance?

SQL Injection

You should never build sql statements using string concatenation like this.

"SELECT * FROM " + dbData[0]

This creates a potential security hole that allows for SQL Injection attacks. You should always use parameterized queries to prevent against this.

Read Tip/Trick: Guard Against SQL Injection Attacks to understand SQL Injection attacks and how to prevent them.

Coding Convention

The nearly universally accepted convention for class naming amongst C# developers is to use PascalCase, where the first letter of every word in your class name is capitalized. Your classes would be SqlFactory, SqlConn, and DbDefinition.

This guide gives fairly commonly used conventions: C# Coding Standards document