问:
collecting elevation data - extract geolocations from a geotiff file
I am trying to add elevation data to a plot using the rayshader package. I can plot the area in which I want to find elevation data using the leaflet package.

```<code>library(whitebox)
library(leaflet)
library(rayshader)
library(rayrender)
library(raster)

# define bounding box with longitude/latitude coordinates
bbox <- list(
  p1 = list(long = -3.6525599, lat = 40.4065001),
  p2 = list(long = -3.7525599, lat = 40.4965001)
)

leaflet() %>%
  addTiles() %>%
  addRectangles(
    lng1 = bbox$p1$long, lat1 = bbox$p1$lat,
    lng2 = bbox$p2$long, lat2 = bbox$p2$lat,
    fillColor = "transparent"
  ) %>%
  fitBounds(
    lng1 = bbox$p1$long, lat1 = bbox$p1$lat,
    lng2 = bbox$p2$long, lat2 = bbox$p2$lat,
  )
</code>```

I am following this blog: https://wcmbishop.github.io/rayshader-demo/ and currently at the part:

"Downloading Elevation Data"

The author uses the USGS data collected from this link:

```<code>https://elevation.nationalmap.gov/arcgis/rest/services/3DEPElevation/ImageServer/exportImage?bbox=-122.522%2C37.707%2C-122.354%2C37.84&bboxSR=4326&size=600%2C480&imageSR=4326&time=&format=jpgpng&pixelType=F32&noData=&noDataInterpretation=esriNoDataMatchAny&interpolation=+RSP_BilinearInterpolation&compression=&compressionQuality=&bandIds=&mosaicRule=&renderingRule=&f=html
</code>```

I replaced the lat, long coordinates in the link with mine:

```<code>https://elevation.nationalmap.gov/arcgis/rest/services/3DEPElevation/ImageServer/exportImage?bbox=-3.6525599%2C40.4065001%2C-3.7525599%2C40.4965001&bboxSR=4326&size=600%2C480&imageSR=4326&time=&format=jpgpng&pixelType=F32&noData=&noDataInterpretation=esriNoDataMatchAny&interpolation=+RSP_BilinearInterpolation&compression=&compressionQuality=&bandIds=&mosaicRule=&renderingRule=&f=html
</code>```

Which returned an empty image - which is no surprise since the USGS is a U.S. data provider. So I download the following file:

The DTM Spain Mainland 20m http://data.opendataportal.at/dataset/dtm-spain/resource/38816df0-9d50-476f-832e-0f7f5fa21771

The file is 2.4 GB in size and is a file for the whole of Spain but I only want the elevation data for the bounds of my lat & long points.

```<code>rgdal::GDALinfo("DTM Spain_Mainland (2019) 20m.tif")
rows        48394
columns     58187
bands       1
lower left origin.x        -23380
lower left origin.y        3901190
res.x       20
res.y       20
ysign       -1
oblique.x   0
oblique.y   0
driver      GTiff
projection  +proj=utm +zone=30 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m
+no_defs
file        DTM Spain_Mainland (2019) 20m.tif
apparent band summary:
   GDType hasNoDataValue NoDataValue blockSize1 blockSize2
1 Float32           TRUE      -32767          1      58187
apparent band statistics:
         Bmin       Bmax Bmean Bsd
1 -4294967295 4294967295    NA  NA
Metadata:
AREA_OR_POINT=Point
</code>```

My question is, how can I either get the geotiff for the long and lat positions in bbox or filter the current DTM Spain_Mainland (2019) 20m.tif file down to just the long, lat coordinates?

答:
You could have a look at the elevatr package, which will give you the raster you want:

```<code>library(elevatr)
library(raster)

bbox2 <- data.frame(x = c(-3.6525599, -3.7525599), y = c(40.4065001, 40.4965001))

elev <- get_elev_raster(bbox2, z = 13, clip = "bbox",
                        prj = "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
</code>```

Body:
I am trying to add elevation data to a plot using the rayshader package. I can plot the area in which I want to find elevation data using the leaflet package.

library(whitebox)
library(leaflet)
library(rayshader)
library(rayrender)
library(raster)

# define bounding box with longitude/latitude coordinates
bbox <- list(
  p1 = list(long = -3.6525599, lat = 40.4065001),
  p2 = list(long = -3.7525599, lat = 40.4965001)
)

leaflet() %>%
  addTiles() %>%
  addRectangles(
    lng1 = bbox$p1$long, lat1 = bbox$p1$lat,
    lng2 = bbox$p2$long, lat2 = bbox$p2$lat,
    fillColor = "transparent"
  ) %>%
  fitBounds(
    lng1 = bbox$p1$long, lat1 = bbox$p1$lat,
    lng2 = bbox$p2$long, lat2 = bbox$p2$lat,
  )

I am following this blog: https://wcmbishop.github.io/rayshader-demo/ and currently at the part:

"Downloading Elevation Data"

The author uses the USGS data collected from this link:

https://elevation.nationalmap.gov/arcgis/rest/services/3DEPElevation/ImageServer/exportImage?bbox=-122.522%2C37.707%2C-122.354%2C37.84&bboxSR=4326&size=600%2C480&imageSR=4326&time=&format=jpgpng&pixelType=F32&noData=&noDataInterpretation=esriNoDataMatchAny&interpolation=+RSP_BilinearInterpolation&compression=&compressionQuality=&bandIds=&mosaicRule=&renderingRule=&f=html

I replaced the lat, long coordinates in the link with mine:

https://elevation.nationalmap.gov/arcgis/rest/services/3DEPElevation/ImageServer/exportImage?bbox=-3.6525599%2C40.4065001%2C-3.7525599%2C40.4965001&bboxSR=4326&size=600%2C480&imageSR=4326&time=&format=jpgpng&pixelType=F32&noData=&noDataInterpretation=esriNoDataMatchAny&interpolation=+RSP_BilinearInterpolation&compression=&compressionQuality=&bandIds=&mosaicRule=&renderingRule=&f=html

Which returned an empty image - which is no surprise since the USGS is a U.S. data provider. So I download the following file:

The DTM Spain Mainland 20m http://data.opendataportal.at/dataset/dtm-spain/resource/38816df0-9d50-476f-832e-0f7f5fa21771

The file is 2.4 GB in size and is a file for the whole of Spain but I only want the elevation data for the bounds of my lat & long points.

rgdal::GDALinfo("DTM Spain_Mainland (2019) 20m.tif")
rows        48394
columns     58187
bands       1
lower left origin.x        -23380
lower left origin.y        3901190
res.x       20
res.y       20
ysign       -1
oblique.x   0
oblique.y   0
driver      GTiff
projection  +proj=utm +zone=30 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m
+no_defs
file        DTM Spain_Mainland (2019) 20m.tif
apparent band summary:
   GDType hasNoDataValue NoDataValue blockSize1 blockSize2
1 Float32           TRUE      -32767          1      58187
apparent band statistics:
         Bmin       Bmax Bmean Bsd
1 -4294967295 4294967295    NA  NA
Metadata:
AREA_OR_POINT=Point

My question is, how can I either get the geotiff for the long and lat positions in bbox or filter the current DTM Spain_Mainland (2019) 20m.tif file down to just the long, lat coordinates?

Body:
You could have a look at the elevatr package, which will give you the raster you want:

library(elevatr)
library(raster)

bbox2 <- data.frame(x = c(-3.6525599, -3.7525599), y = c(40.4065001, 40.4965001))

elev <- get_elev_raster(bbox2, z = 13, clip = "bbox",
                        prj = "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")


来源: stackexchange

问:
Using split on an input string
I'm a beginner to Python 3 and when I try this code it works:

```<code>a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i) for i in b]
print(mylist)
</code>```

Output:

Enter three digits separated by space:2 3 4
[2, 3, 4]
```

<p>However I get errors when I try this:</p>

```a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i**2) for i in b]
print(mylist)
```

<blockquote>
  <p>Error: TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'</p>
</blockquote>

<p>In fact this works as well:</p>

```list1 = [2,3,4]
mylist = [int(i**2) for i in list1]
print(mylist)
```

What am I doing wrong?

答:
you have to give condition for split like " "
suppose the input is 2 3 4 and you want to split it as 2,3,4. and also the input return value as str so you have to change it to int as follows then you can use **

```<code> a = input('Enter three digits separated by space:')
 b = map(int,a.split(" "))
 mylist = [i**2 for i in b]
</code>```

this will work for you..

ContentLicense: CC BY-SA 4.0

Title: Using split on an input string

Body:
I'm a beginner to Python 3 and when I try this code it works:

a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i) for i in b]
print(mylist)

Output:

Enter three digits separated by space:2 3 4
[2, 3, 4]

However I get errors when I try this:

a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i**2) for i in b]
print(mylist)

Error: TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

In fact this works as well:

list1 = [2,3,4]
mylist = [int(i**2) for i in list1]
print(mylist)

What am I doing wrong?

Body:
you have to give condition for split like " "
suppose the input is 2 3 4 and you want to split it as 2,3,4. and also the input return value as str so you have to change it to int as follows then you can use **

 a = input('Enter three digits separated by space:')
 b = map(int,a.split(" "))
 mylist = [i**2 for i in b]

this will work for you..


问:
Removing partial duplicate rows (duplicate data in only two columns) from Microsoft SQL Server 2012 table
I have a table of around 7000 rows, a small sample of which is below:

```<code>ORG_ID     Entity_CLASS_ID     Entity_ID     ORGANISATION_ID     ORGANISATION_ROLE_ID    COLUMN_X
-------------------------------------------------------------------------------------------------
781        3                   998           896                 4                       1
2098       3                   998           3191                4                       66
3808       4                   998           3191                4                       6555
780        3                   997           2402                4                       34234
3807       4                   997           2061                4                       234
2097       3                   997           2061                4                       6756
</code>```

You will notice that for each Entity_ID, there are multiple rows. For each Entity_ID, there are two or more different Entity_CLASS_IDs.

You can see that in some circumstances two of the rows for each Entity_ID match on ORGANISATION_ID too, but have different Entity_Class_IDs:

```<code>ORG_ID     Entity_CLASS_ID     Entity_ID     ORGANISATION_ID     ORGANISATION_ROLE_ID    COLUMN_X
-------------------------------------------------------------------------------------------------
2098       3                   998           3191                4                       66
3808       4                   998           3191                4                       6555
</code>```

Where this is the case i would like to delete the row with the entity class ID = 3.

The resulting tidied up table should be:

```<code>ORG_ID     Entity_CLASS_ID     Entity_ID     ORGANISATION_ID     ORGANISATION_ROLE_ID    COLUMN_X
-------------------------------------------------------------------------------------------------
781        3                   998           896                 4                       1
3808       4                   998           3191                4                       6555
780        3                   997           2402                4                       34234
3807       4                   997           2061                4                       234
</code>```

Hopefully I've explained that clearly!?

I've tried to work this out in code myself, but the mix of partial matches is stopping me from getting anywhere near a solution!

Thanks in advance for any help with this.

答:
We can try using a CTE for this purpose:

```<code>WITH cte AS (
    SELECT *, COUNT(*) OVER (PARTITION BY Entity_ID, ORGANISATION_ID) cnt,
        MAX(Entity_CLASS_ID) OVER (PARTITION BY Entity_ID, ORGANISATION_ID) max_ecid
    FROM yourTable
)

DELETE
FROM cte
WHERE
    Entity_CLASS_ID = 3 AND   -- identifies the duplicate
    cnt = 2 AND               -- must occur in a pair
    max_ecid = 4;             -- the other record must be 4
</code>```

Here is a running demo showing that the correct records are being identified for deletion:

Demo

Body:
I have a table of around 7000 rows, a small sample of which is below:

ORG_ID     Entity_CLASS_ID     Entity_ID     ORGANISATION_ID     ORGANISATION_ROLE_ID    COLUMN_X
-------------------------------------------------------------------------------------------------
781        3                   998           896                 4                       1
2098       3                   998           3191                4                       66
3808       4                   998           3191                4                       6555
780        3                   997           2402                4                       34234
3807       4                   997           2061                4                       234
2097       3                   997           2061                4                       6756

You will notice that for each Entity_ID, there are multiple rows. For each Entity_ID, there are two or more different Entity_CLASS_IDs.

You can see that in some circumstances two of the rows for each Entity_ID match on ORGANISATION_ID too, but have different Entity_Class_IDs:

ORG_ID     Entity_CLASS_ID     Entity_ID     ORGANISATION_ID     ORGANISATION_ROLE_ID    COLUMN_X
-------------------------------------------------------------------------------------------------
2098       3                   998           3191                4                       66
3808       4                   998           3191                4                       6555

Where this is the case i would like to delete the row with the entity class ID = 3.

The resulting tidied up table should be:

ORG_ID     Entity_CLASS_ID     Entity_ID     ORGANISATION_ID     ORGANISATION_ROLE_ID    COLUMN_X
-------------------------------------------------------------------------------------------------
781        3                   998           896                 4                       1
3808       4                   998           3191                4                       6555
780        3                   997           2402                4                       34234
3807       4                   997           2061                4                       234

Hopefully I've explained that clearly!?

I've tried to work this out in code myself, but the mix of partial matches is stopping me from getting anywhere near a solution!

Thanks in advance for any help with this.

Body:
We can try using a CTE for this purpose:

WITH cte AS (
    SELECT *, COUNT(*) OVER (PARTITION BY Entity_ID, ORGANISATION_ID) cnt,
        MAX(Entity_CLASS_ID) OVER (PARTITION BY Entity_ID, ORGANISATION_ID) max_ecid
    FROM yourTable
)

DELETE
FROM cte
WHERE
    Entity_CLASS_ID = 3 AND   -- identifies the duplicate
    cnt = 2 AND               -- must occur in a pair
    max_ecid = 4;             -- the other record must be 4

Here is a running demo showing that the correct records are being identified for deletion:

Demo


问:
Find length of a string in SQL using LIKE operator
Example:

Suppose there are following rows:

1- Animal is innocent
 2- Dog is Animal

select length(columnname like %animal%) from tablename

```<code>o/p - 1-17
      2-13
</code>```

答:
You can use case when function</p>

```<code>case when columnname like %animal% then length(columname) else 0 end as lengthNum
</code>```

Body:
Example:

Suppose there are following rows:

1- Animal is innocent
 2- Dog is Animal

select length(columnname like %animal%) from tablename

o/p - 1-17
      2-13

Body:
You can use case when function

case when columnname like %animal% then length(columname) else 0 end as lengthNum


问:
Setting Variable Synchronously in Asynchronous Function

function foo()
{
 let a = 5;
 setTimeout(function(){a = 6;}, 1000);
 return a;
}```

How can I return 6 for foo? The asynchronous function I am using is actually from a framework, not setTimeout.

答:
As it stands you cannot make foo return the value of a as set within the callback given to setTimeout because when the return statement is executed the timeout callback function has not been invoked.

What you can do is make your function async and wrap the call to setTimeout in a Promise, then await that promise to allow the setTimeout callback to be invoked, and then finally return a.

async function foo() {
  let a = 5;
  await new Promise(resolve => {
    setTimeout(function() {
      a = 6;
      resolve();
    }, 1000);
  });
  return a;
}

(async () => {
  console.log("running...")
  console.log(await foo());
})()```

Body:
function foo()
{
 let a = 5;
 setTimeout(function(){a = 6;}, 1000);
 return a;
}

How can I return 6 for foo? The asynchronous function I am using is actually from a framework, not setTimeout.


问:
Use Powershell to download attached excel file from Servicenow ticket
I'm currently working on a powershell script that should be able to download an attached excel file from a service now ticket, before I explain more please see the basic flow of the automation below.

The user will be asked to enter the ticket number.

The system will then find that incident ticket to accurately get the excel file needed(I saw online that I need to use sys_id).

It will then be downloaded to a specific path on the user's machine. ex: "C:\downloads\Demo\".

Following all this, I found a sample script online that I'm trying to configure to match my needs; however, I'm not sure where to get the values on that sample script. You can check the bullets below the script for the questions I have in mind.

```<code>$IncidentNumber = Read-Host -Prompt 'Enter Incident Request #'
#$admin = "admin"
#$password = "admin" | ConvertTo-SecureString -AsPlainText -Force
#$Credential = New-Object pscredential -ArgumentList ($admin,$password)
$Uri = "https://dev42835.service-now.com/api/now/table/incident?sysparm_query=number=$($IncidentNumber)&sysparm_fields=sys_id&sysparm_limit=1"
$IncidentResult = Invoke-RestMethod -Uri $Uri #-Method Get -Credential $Credential
if($IncidentResult.result.sys_id -ne $null) {
    $IncidentAttachments = Invoke-RestMethod -Uri "https://dev42835.service-now.com/api/now/attachment?sysparm_query=table_sys_id=$($IncidentResult.result.sys_id)" #-Method Get -Credential $Credential
    $IncidentAttachments.result | Select file_name , download_link
}
else{
    "Incident Not Found!"
}
</code>```

Do I really need the credentials to run the script? If yes, is there a way to
remove the need of the credentials?

Where can I get the URL that is assigned to the $URI variable?

I'm new to powershell automation so I would appreciate it if you can recommend better approach if there are any.

答:
Yes you need credentials.

Your URI is the URL of your servicenow instance. Change the dev42835 portion to match. If you're unsure of your instance, contact servicenow support.
https://dev42835.service-now.com

If you use the REST API explorer, you can view API endpoints and versions which will help with forming your requests. You do need to have the rest_api_explorer role to access the REST API Explorer. If you do not have this role, contact your service-now admin requesting it.

https://docs.servicenow.com/bundle/geneva-servicenow-platform/page/integrate/inbound_rest/task/t_GetStartedAccessExplorer.html

Body:
I'm currently working on a powershell script that should be able to download an attached excel file from a service now ticket, before I explain more please see the basic flow of the automation below.

The user will be asked to enter the ticket number.

The system will then find that incident ticket to accurately get the excel file needed(I saw online that I need to use sys_id).

It will then be downloaded to a specific path on the user's machine. ex: "C:\downloads\Demo\".

Following all this, I found a sample script online that I'm trying to configure to match my needs; however, I'm not sure where to get the values on that sample script. You can check the bullets below the script for the questions I have in mind.

$IncidentNumber = Read-Host -Prompt 'Enter Incident Request #'
#$admin = "admin"
#$password = "admin" | ConvertTo-SecureString -AsPlainText -Force
#$Credential = New-Object pscredential -ArgumentList ($admin,$password)
$Uri = "https://dev42835.service-now.com/api/now/table/incident?sysparm_query=number=$($IncidentNumber)&sysparm_fields=sys_id&sysparm_limit=1"
$IncidentResult = Invoke-RestMethod -Uri $Uri #-Method Get -Credential $Credential
if($IncidentResult.result.sys_id -ne $null) {
    $IncidentAttachments = Invoke-RestMethod -Uri "https://dev42835.service-now.com/api/now/attachment?sysparm_query=table_sys_id=$($IncidentResult.result.sys_id)" #-Method Get -Credential $Credential
    $IncidentAttachments.result | Select file_name , download_link
}
else{
    "Incident Not Found!"
}

Do I really need the credentials to run the script? If yes, is there a way to
remove the need of the credentials?

Where can I get the URL that is assigned to the $URI variable?

I'm new to powershell automation so I would appreciate it if you can recommend better approach if there are any.


问:
Populate MatBlazor MatAutocompleteList with values from an object list
I am working on an application using .Net Core 3.1 and client side Blazor. I am using MatBlazor components but I am unable to get the MatAutocompleteList to load. The data is retrieved from an API and converted to an object list when the page loads:

```<code>    List<CountryDto> countries = new List<CountryDto>();

    protected override async Task OnInitializedAsync()
    {
        await ReadCountries();
    }

    ...

    async Task ReadCountries()
    {
        ApiResponseDto apiResponse = await Http.GetJsonAsync<ApiResponseDto>( "api/country" );

        if ( apiResponse.StatusCode == 200 )
        {
            countries = Newtonsoft.Json.JsonConvert.DeserializeObject<CountryDto []>( apiResponse.Result.ToString() ).ToList<CountryDto>();
        }
    }
</code>```

Then I am referencing the data in the autocomplete list like this (similar to the example):

```<code><MatAutocompleteList @bind-Value="@church.Country" Items="@countries" Label="Select Country" TItem="CountryDto" CustomStringSelector="@(i => i.Name)" />
</code>```

No matter how I configure the autocomplete box, the page fails to load and Chrome Dev tools shows a string of unhandled errors rendering the component.

I have tried configuring it different ways using the examples but I always get the same errors. What am I doing wrong?

答: This is a known issue.  A workaround was explained here. A new version of the control is in the works so hopefully this new component will solve the issue.</p>

Body:
I am working on an application using .Net Core 3.1 and client side Blazor. I am using MatBlazor components but I am unable to get the MatAutocompleteList to load. The data is retrieved from an API and converted to an object list when the page loads:

    List<CountryDto> countries = new List<CountryDto>();

    protected override async Task OnInitializedAsync()
    {
        await ReadCountries();
    }

    ...

    async Task ReadCountries()
    {
        ApiResponseDto apiResponse = await Http.GetJsonAsync<ApiResponseDto>( "api/country" );

        if ( apiResponse.StatusCode == 200 )
        {
            countries = Newtonsoft.Json.JsonConvert.DeserializeObject<CountryDto []>( apiResponse.Result.ToString() ).ToList<CountryDto>();
        }
    }

Then I am referencing the data in the autocomplete list like this (similar to the example):

<MatAutocompleteList @bind-Value="@church.Country" Items="@countries" Label="Select Country" TItem="CountryDto" CustomStringSelector="@(i => i.Name)" />

No matter how I configure the autocomplete box, the page fails to load and Chrome Dev tools shows a string of unhandled errors rendering the component.

I have tried configuring it different ways using the examples but I always get the same errors. What am I doing wrong?


问:
nodejs how to replace ; with ',' to make an sql query
I have a query that looks like this:

```<code>INSERT INTO table VALUES ('47677;2019;2019;10T-1001-10010AS;A05;International;TieLineKoman-KosovoB;L_KOM-KOSB;2018;NULL;NULL;;NULL;Tieline;NULL;10XAL-KESH-----J;0;3')
</code>```

that is produced by parsing a csv file.

The query is not in a valid form, I have to replace all semicolons with the string ',' (comma inside single quotes). What I want to get is:

```<code>('47677','2019','2019','10T-1001-10010AS','A05','International','TieLineKoman-KosovoB','L_KOM-KOSB','2018','NULL','NULL','','NULL','Tieline','NULL','10XAL-KESH-----J','0','3')
</code>```

I have tried to do this in many different ways, but I end up with backshlashes added in my string. This is what I get:

```<code>"INSERT INTO AllocatedEICDetail VALUES ('47677\\',\\'2019\\',\\'2019\\',\\'10T-1001-10010AS\\',\\'A05\\',\\'International\\',\\'TieLineKoman-KosovoB\\',\\'L_KOM-KOSB\\',\\'2018\\',\\'NULL\\',\\'NULL\\',\\'\\',\\'NULL\\',\\'Tieline\\',\\'NULL\\',\\'10XAL-KESH-----J\\',\\'0\\',\\'3')"
</code>```

Any ideas how to do this properly without having the backslashes added?

Thank you!

答:
```<code>//the string you have
const string = '47677;2019;2019;10T-1001-10010AS;A05;International;TieLineKoman-KosovoB;L_KOM-KOSB;2018;NULL;NULL;;NULL;Tieline;NULL;10XAL-KESH-----J;0;3';
//the string you need:
const targetString = string.replace(/\;/g,',');</code>```

You specify a small regex between the forward slashes in replace which is a simple ';', give it a 'g' flag for global which will replace all instances, and in the second argument supply what you need it replaced with.

Body:
I have a query that looks like this:

INSERT INTO table VALUES ('47677;2019;2019;10T-1001-10010AS;A05;International;TieLineKoman-KosovoB;L_KOM-KOSB;2018;NULL;NULL;;NULL;Tieline;NULL;10XAL-KESH-----J;0;3')

that is produced by parsing a csv file.

The query is not in a valid form, I have to replace all semicolons with the string ',' (comma inside single quotes). What I want to get is:

('47677','2019','2019','10T-1001-10010AS','A05','International','TieLineKoman-KosovoB','L_KOM-KOSB','2018','NULL','NULL','','NULL','Tieline','NULL','10XAL-KESH-----J','0','3')

I have tried to do this in many different ways, but I end up with backshlashes added in my string. This is what I get:

"INSERT INTO AllocatedEICDetail VALUES ('47677\\',\\'2019\\',\\'2019\\',\\'10T-1001-10010AS\\',\\'A05\\',\\'International\\',\\'TieLineKoman-KosovoB\\',\\'L_KOM-KOSB\\',\\'2018\\',\\'NULL\\',\\'NULL\\',\\'\\',\\'NULL\\',\\'Tieline\\',\\'NULL\\',\\'10XAL-KESH-----J\\',\\'0\\',\\'3')"

Any ideas how to do this properly without having the backslashes added?

Thank you!

Body:
//the string you have
const string = '47677;2019;2019;10T-1001-10010AS;A05;International;TieLineKoman-KosovoB;L_KOM-KOSB;2018;NULL;NULL;;NULL;Tieline;NULL;10XAL-KESH-----J;0;3';
//the string you need:
const targetString = string.replace(/\;/g,',');

You specify a small regex between the forward slashes in replace which is a simple ';', give it a 'g' flag for global which will replace all instances, and in the second argument supply what you need it replaced with.


问:
Injection Token Not Resetting on Component Change
I'm not sure of the small details here, so maybe this isn't even supposed to work—but it seems like there should be some solution to this. I have a parent component that uses two child components in tabs, like so:

```<code><div class="container" *ngIf="page === 'tab1'">
    <refresher-component></refresher-component>
    <child-component1></child-component1>
</div>
<div class="container" *ngIf="page === 'tab2'">
    <refresher-component></refresher-component>
    <child-component2></child-component2>
</div>
</code>```

The parent also has a refresher component, that is responsible for refreshing the data in both of the tabs. Each of the child components injects a service that implements the Refreshable interface:

Child component 1: constructor(private service1: Service1)

Child component 2: constructor(private service2: Service2)

Each service looks like this (replace 1 with 2 for 2nd service):

```<code>@Injectable()
export class Service1 implements Refreshable<Type1[]>
</code>```

The refersher-component looks like this:

```<code>public constructor(@Inject(RefresherServiceToken) public refreshableService: Refreshable<any>) {
    console.log('refreshable', this.refreshableService);
}
</code>```

What happens is that when I load the page (1st tab is default), the console.log outputs Service1. However, when changing to Tab 2, the constructor is called again, but it also outputs Service1. Therefore the refresh is also done on Service1's data, and does not affect Service2.

Is this normal behavior, because the route doesn't change, and do I need to add something to reset the service? Is there a simple way to troubleshoot this behavior in general? (Angular 8)

答:
It looks like what was missing from my troubleshooting was the provider of the RefresherServiceToken. This must exist somewhere. In my case the provided was given in an "empty" module that was the parent of the parent component, and since the refresher-component is outside of the children, it also can't be overridden at the child-component level.

There are three solutions for this that I can think of:

Simplest:

Move the refresher-component inside each child-component. In my actual code it was a bit difficult, but in the above example it's trivial. After that, add the necessary provider on the child component level, for example:

```<code>providers: [
    {provide: RefresherServiceToken, useExisting: Service2}
]
</code>```

In this case, even if there was a provider on the parent level, it is overridden.

Simple to implement, difficult to read/follow later

Configure the provider dynamically at the parent-component level. There are a few ways to do it, as described here:
How to add providers to Injector dynamically?

Potentially the most difficult to implement, but simplest to grasp

Change the way these pages are built, in that the two child components should be in two completely separate pages/routes, whereas the shared template parts (say, header/footer) are in shared components. This completely works around the problem, because there is no one parent for both child components, and therefore they cannot have the same provider. Naturally separate providers need to be defined for each of them, as outlined in the first example.

Body:
I'm not sure of the small details here, so maybe this isn't even supposed to work—but it seems like there should be some solution to this. I have a parent component that uses two child components in tabs, like so:

    <refresher-component></refresher-component>
    <child-component1></child-component1>

    <refresher-component></refresher-component>
    <child-component2></child-component2>

The parent also has a refresher component, that is responsible for refreshing the data in both of the tabs. Each of the child components injects a service that implements the Refreshable interface:

Child component 1: constructor(private service1: Service1)

Child component 2: constructor(private service2: Service2)

Each service looks like this (replace 1 with 2 for 2nd service):

@Injectable()
export class Service1 implements Refreshable<Type1[]>

The refersher-component looks like this:

public constructor(@Inject(RefresherServiceToken) public refreshableService: Refreshable<any>) {
    console.log('refreshable', this.refreshableService);
}

What happens is that when I load the page (1st tab is default), the console.log outputs Service1. However, when changing to Tab 2, the constructor is called again, but it also outputs Service1. Therefore the refresh is also done on Service1's data, and does not affect Service2.

Is this normal behavior, because the route doesn't change, and do I need to add something to reset the service? Is there a simple way to troubleshoot this behavior in general? (Angular 8)

Body:
It looks like what was missing from my troubleshooting was the provider of the RefresherServiceToken. This must exist somewhere. In my case the provided was given in an "empty" module that was the parent of the parent component, and since the refresher-component is outside of the children, it also can't be overridden at the child-component level.

There are three solutions for this that I can think of:

Simplest:

Move the refresher-component inside each child-component. In my actual code it was a bit difficult, but in the above example it's trivial. After that, add the necessary provider on the child component level, for example:

providers: [
    {provide: RefresherServiceToken, useExisting: Service2}
]

In this case, even if there was a provider on the parent level, it is overridden.

Simple to implement, difficult to read/follow later

Configure the provider dynamically at the parent-component level. There are a few ways to do it, as described here:
How to add providers to Injector dynamically?

Potentially the most difficult to implement, but simplest to grasp

Change the way these pages are built, in that the two child components should be in two completely separate pages/routes, whereas the shared template parts (say, header/footer) are in shared components. This completely works around the problem, because there is no one parent for both child components, and therefore they cannot have the same provider. Naturally separate providers need to be defined for each of them, as outlined in the first example.


问:
Making the configuration available to all classes
I'm writing a small web server, and it takes a configuration file with all sorts of different options: how many threads to run, which class deals which each file extension, which file to display by default and so on and so forth. To represent this, I'm parsing the config file into a Configuration object which contains all these settings, and the main class holds this object.

However, the config data is required on almost every level of the server - classes within classes within classes...

My question is, what is the best practice to use here? Should I give the config as a parameter for many many classes and pass it back and forth? Should I make it a singleton? Is there another solution I don't see?

答:
Use Guice!  Guice is a dependency-injection framework which effectively replaces your use of the new keyword.  You define your object bindings in a Module like this:

```<code>bind(Configuration.class).to(MySpecificConfiguration.class);
bind(WebServer.class).to(MySpecificWebServerImplementation.class);
</code>```

And then, instead of newing up WebServer directly, you just ask Guice to do it for you:

```<code>WebServer ws = Guice.createInjector(yourModule).getInstance(WebServer.class);
</code>```

Which will magically create MySpecificWebServerImplementation for you.  If MySpecificWebServerImplementation is defined as follows:

```<code>public class MySpecificWebServerImplementation {
    @Inject
    public MySpecificWebServerImplementation(Configuration configuration) {
    }
}
</code>```

Then MySpecificWebServerImplementation will automatically get given the configuration and you don't have to worry about passing it around.

ContentLicense: CC BY-SA 3.0

Body:
Use Guice!  Guice is a dependency-injection framework which effectively replaces your use of the new keyword.  You define your object bindings in a Module like this:

bind(Configuration.class).to(MySpecificConfiguration.class);
bind(WebServer.class).to(MySpecificWebServerImplementation.class);

And then, instead of newing up WebServer directly, you just ask Guice to do it for you:

WebServer ws = Guice.createInjector(yourModule).getInstance(WebServer.class);

Which will magically create MySpecificWebServerImplementation for you.  If MySpecificWebServerImplementation is defined as follows:

public class MySpecificWebServerImplementation {
    @Inject
    public MySpecificWebServerImplementation(Configuration configuration) {
    }
}

Then MySpecificWebServerImplementation will automatically get given the configuration and you don't have to worry about passing it around.


问:
LoginRequiredMiddleware not working for Unauthenticated User
I am trying to automate the links access for authenticated and unauthenticated users using LoginRequiredMiddleware. The code is not working as unauthenticated users can still open other urls which they are not supposed to. Please see my code below and advise. Thanks.

urls.py

```<code>from django.urls import path
from . import views
from django.contrib.auth.views import (
    LoginView, LogoutView,
    PasswordResetView, PasswordResetDoneView,
    PasswordResetConfirmView,
    PasswordResetCompleteView
)

urlpatterns = [

    path('', views.home, name = 'home'),
    path('column/', views.column),
    path('login/', LoginView.as_view(template_name='accounts/login.html'), name = 'login'),
    path('logout/', LogoutView.as_view(template_name='accounts/logout.html'), name = 'logout'),
    path('register/', views.register, name = 'register'),
    path('profile/', views.view_profile, name = 'view_profile'),
    path('profile/edit/', views.edit_profile, name = 'edit_profile'),
    path('change_password/', views.change_password, name = 'change_password'),
    path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'), name = 'password_reset'),
    path('reset-password/done', PasswordResetDoneView.as_view(), name = 'password_reset_done'),
    path('reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', PasswordResetConfirmView.as_view(), name = 'password_reset_confirm'),
    path('reset-password/complete/$', PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]
</code>```

settings.py

```<code>STATIC_URL = '/static/'

LOGIN_REDIRECT_URL = 'home'

LOGIN_URL = 'login'

LOGIN_EXEMPT_URLS = (
    'logout',
    'register',
)
</code>```

LoginRequiredMiddleware.py

```<code>import re

from django.conf import settings
from django.urls import reverse
from django.shortcuts import redirect
from django.contrib.auth import logout

EXEMPT_URLS = [settings.LOGIN_URL.lstrip('/')]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
    EXEMPT_URLS += [url for url in settings.LOGIN_EXEMPT_URLS]

class LoginRequiredMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        assert hasattr(request, 'user')

        if request.user.is_authenticated is False:
            if view_func.__name__ in EXEMPT_URLS is False:
                return redirect(settings.LOGIN_URL)

        else:
            return None
</code>```

答:
Have you added this middleware to your MIDDLEWARE setting in settings.py?

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'myproject.middleware.LoginRequiredMiddleware',
]
```

Body:
I am trying to automate the links access for authenticated and unauthenticated users using LoginRequiredMiddleware. The code is not working as unauthenticated users can still open other urls which they are not supposed to. Please see my code below and advise. Thanks.

urls.py

from django.urls import path
from . import views
from django.contrib.auth.views import (
    LoginView, LogoutView,
    PasswordResetView, PasswordResetDoneView,
    PasswordResetConfirmView,
    PasswordResetCompleteView
)

urlpatterns = [

    path('', views.home, name = 'home'),
    path('column/', views.column),
    path('login/', LoginView.as_view(template_name='accounts/login.html'), name = 'login'),
    path('logout/', LogoutView.as_view(template_name='accounts/logout.html'), name = 'logout'),
    path('register/', views.register, name = 'register'),
    path('profile/', views.view_profile, name = 'view_profile'),
    path('profile/edit/', views.edit_profile, name = 'edit_profile'),
    path('change_password/', views.change_password, name = 'change_password'),
    path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'), name = 'password_reset'),
    path('reset-password/done', PasswordResetDoneView.as_view(), name = 'password_reset_done'),
    path('reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', PasswordResetConfirmView.as_view(), name = 'password_reset_confirm'),
    path('reset-password/complete/$', PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]

settings.py

STATIC_URL = '/static/'

LOGIN_REDIRECT_URL = 'home'

LOGIN_URL = 'login'

LOGIN_EXEMPT_URLS = (
    'logout',
    'register',
)

LoginRequiredMiddleware.py

import re

from django.conf import settings
from django.urls import reverse
from django.shortcuts import redirect
from django.contrib.auth import logout

EXEMPT_URLS = [settings.LOGIN_URL.lstrip('/')]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
    EXEMPT_URLS += [url for url in settings.LOGIN_EXEMPT_URLS]

class LoginRequiredMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        assert hasattr(request, 'user')

        if request.user.is_authenticated is False:
            if view_func.__name__ in EXEMPT_URLS is False:
                return redirect(settings.LOGIN_URL)

        else:
            return None


问:
React best practice for passing props to children - pass all props, or explicitly pass selected props?
Which approach is better practice when passing props to child components:

Approach 1. Pass all props using {...props}, e.g.

```<code>ParentComponent = (props) => {
    return <ChildComponent {...props}>
}

</code>```

Approach 2. Explicitly pass only required props, e.g

```<code>ParentComponent = ({prop1, prop2}) => {
    return <ChildComponent prop1={prop1}, prop2={prop2}>
}
</code>```

Approach 1: causes warnings when illegal props are inadvertently passed to children, as described here

Approach 2: makes it a pain to propagate CSS styles down to child components, in cases where you want to style all instances of a reused component, since each CSS style property needs to be explicitly added to the set of props being passed down.

答: I would never use prop drilling it is very tricky and can make your app very slow. Use approach 2! :)</p>

Body:
Which approach is better practice when passing props to child components:

Approach 1. Pass all props using {...props}, e.g.

ParentComponent = (props) => {
    return <ChildComponent {...props}>
}

Approach 2. Explicitly pass only required props, e.g

ParentComponent = ({prop1, prop2}) => {
    return <ChildComponent prop1={prop1}, prop2={prop2}>
}

Approach 1: causes warnings when illegal props are inadvertently passed to children, as described here

Approach 2: makes it a pain to propagate CSS styles down to child components, in cases where you want to style all instances of a reused component, since each CSS style property needs to be explicitly added to the set of props being passed down.


问:
Passing props in React Typescript using custom hooks
I have made a custom useToggler hook, and i am trying to pass toggle props from it to button child in Header. When i try toggle={toggle} i get error:

Type '{toggle: () => void;}' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.

How can i achieve that with typescript?

```<code>import './style/app.css';
import Header from './components/Header';
import SideDrawer from './components/SideDrawer'
import Backdrop from'./components/Backdrop'
import useToggler from "./components/UseToggler";

const App = () => {
    const [show, toggle]=useToggler()

    return (
        <div className="App">
            <Header toggle={toggle} />
            <SideDrawer/>
            <Backdrop/>
            <main style={{marginTop:'56px'}}>
                <p>Page content</p>
            </main>
        </div>
    );
}

export default App;
</code>```

答:
You'll get a similar error, since you're violating the interface typecheck. The Component should have a mandatory prop. You can avoid this error by spreading the props you want to pass as:</p>

```<code><Header {...toggler} />
</code>```

Body:
I have made a custom useToggler hook, and i am trying to pass toggle props from it to button child in Header. When i try toggle={toggle} i get error:

Type '{toggle: () => void;}' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.

How can i achieve that with typescript?

import './style/app.css';
import Header from './components/Header';
import SideDrawer from './components/SideDrawer'
import Backdrop from'./components/Backdrop'
import useToggler from "./components/UseToggler";

const App = () => {
    const [show, toggle]=useToggler()

    return (

            <SideDrawer/>
            <Backdrop/>

Page content

    );
}

export default App;

Body:
You'll get a similar error, since you're violating the interface typecheck. The Component should have a mandatory prop. You can avoid this error by spreading the props you want to pass as:

<Header {...toggler} />


问:
Why base64 string has been saved as Object in mongoDB?
I want to save a product detail on the mongoDB database. And when I do this mongoBD store a property imageSrc as object. But I need to store this as string

my database

my angular service

my express server request

I think it is connected with http-headers, but I cannot solve this problem

答: I think what's happening here is that you assign the Promise to imageSrc and not the actual result. You should resolve the promise of getBase64 before calling http.post.


问:
How to extract original prices using BeautifulSoup?
I am trying to learn BeatifulSoup but currently having trouble with extracting prices (especially if there's a discount / strike through). I am only interested when there's a discount (itemprop = "offers") and for this exercise, I just want to extract the original price.

Full HTML can be obtain by inspecting this page:
https://www.patagonia.ca/shop/mens-hard-shell-jackets-vests

Highlighted desired target in the HTML below:

I have tried

```<code>from bs4 import BeautifulSoup
import requests
import pandas as pd
import json

page = requests.get("https://www.patagonia.ca/shop/mens-hard-shell-jackets-vests", verify = False)
soup = BeautifulSoup(page.content, 'html.parser')

div_price = []

for section_tag in soup.find_all('div', class_='product-tile__meta-primary'):
    for div_prices in section_tag.find_all('div', class_='price'):
        if div_prices.get('itemprop') == 'offers':
            for x in div_prices.find_all('span', {'class':'strike-through list'}):
                for y in x.find_all('span', class_='value'):
                    div_price.append(y.get('content'))
        else:
            continue
</code>```

The above code gives me the desired prices - I only want the original price ($499) and not the discounted price ($349.30) - however it gets repeated multiple times :(

['499.00',  '435.00',  '879.00',  '999.00',  '799.00',  '499.00',
  '435.00',  '879.00',  '999.00',  '799.00',  '499.00',  '435.00',
  '879.00',  '999.00',  '799.00',  '499.00',  '435.00',  '879.00',
  '999.00', . . .

Also I'm not proud with the nested loops I'm hoping the community can help to fix these two bugs (feels like I'm missing something simple here but I just can't get my head around it):

If there's a better way without using all the loops I'm all ears

Is there a better way to extract the required info other than keep using find_all (still within BeautifulSoup)?

答:
Code:

```<code>from bs4 import BeautifulSoup
import requests

page = requests.get("https://www.patagonia.ca/shop/mens-hard-shell-jackets-vests", verify = False)
soup = BeautifulSoup(page.content, 'html.parser')

div_price = []
for price in soup.find_all('span', {'class': 'strike-through list'}):
    div_price.append(str(price.text).strip()[3:])

print(div_price)
</code>```

Output:

```<code>['499', '435', '879', '999', '799']
</code>```

Body:
I am trying to learn BeatifulSoup but currently having trouble with extracting prices (especially if there's a discount / strike through). I am only interested when there's a discount (itemprop = "offers") and for this exercise, I just want to extract the original price.

Full HTML can be obtain by inspecting this page:
https://www.patagonia.ca/shop/mens-hard-shell-jackets-vests

Highlighted desired target in the HTML below:

I have tried

from bs4 import BeautifulSoup
import requests
import pandas as pd
import json

page = requests.get("https://www.patagonia.ca/shop/mens-hard-shell-jackets-vests", verify = False)
soup = BeautifulSoup(page.content, 'html.parser')

div_price = []

for section_tag in soup.find_all('div', class_='product-tile__meta-primary'):
    for div_prices in section_tag.find_all('div', class_='price'):
        if div_prices.get('itemprop') == 'offers':
            for x in div_prices.find_all('span', {'class':'strike-through list'}):
                for y in x.find_all('span', class_='value'):
                    div_price.append(y.get('content'))
        else:
            continue

The above code gives me the desired prices - I only want the original price ($499) and not the discounted price ($349.30) - however it gets repeated multiple times :(

['499.00',  '435.00',  '879.00',  '999.00',  '799.00',  '499.00',
  '435.00',  '879.00',  '999.00',  '799.00',  '499.00',  '435.00',
  '879.00',  '999.00',  '799.00',  '499.00',  '435.00',  '879.00',
  '999.00', . . .

Also I'm not proud with the nested loops I'm hoping the community can help to fix these two bugs (feels like I'm missing something simple here but I just can't get my head around it):

If there's a better way without using all the loops I'm all ears

Is there a better way to extract the required info other than keep using find_all (still within BeautifulSoup)?

Body:
Code:

from bs4 import BeautifulSoup
import requests

page = requests.get("https://www.patagonia.ca/shop/mens-hard-shell-jackets-vests", verify = False)
soup = BeautifulSoup(page.content, 'html.parser')

div_price = []
for price in soup.find_all('span', {'class': 'strike-through list'}):
    div_price.append(str(price.text).strip()[3:])

print(div_price)

Output:

['499', '435', '879', '999', '799']


问:
form not display on html, django
I tried to make a blog that allows user posts, store the posts in the db along with the posted date time and the person who posted it.

My problem is that I somehow cannot load the {{form}} to my UI, which makes my form invalid and I just don't know why it doesn't show up the input text box.

I'm not sure if I need a get_post function, but I'll just put it in views.py. (I havnt write the html of that part yet. Just need to see the form first.)
I'm pretty new to Django, can somebody pls help me with this!!!  Thanks!

Below are my files.

blog.html file:

```<code>{% block posts %}
<div>
<span>New Post: </span>
<form method="post" action="{% url 'posts' %}" enctype="multipart/form-data">
            {% csrf_token %}
            <table>
                {{form}}
                <!--not showing in UI-->
            </table>
            <input id="id_post_button" type="submit" value="Submit" /><br>
</form>
<div>
{% endblock %}
</code>```

urls.py

```<code>urlpatterns = [
    path('posts', views.post_action, name='posts'),
    path('post/<int:id>', views.get_post, name='post'),
]
</code>```

Models.py

```<code>class PostModel(models.Model):
    user_id = models.IntegerField()
    post_input_text = models.CharField(max_length=100)
    post_profile = models.CharField(max_length=30)
    post_date_time = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return 'id=' + str(self.user_id) + ", post_date_time=" + self.post_date_time + ", post_input_text=" + self.post_input_text + ", post_profile=" + self.post_profile

</code>```

Views.py:

```<code>@login_required
def post_action(request):
    print("----post action---")
    context = {}
    if request.method == "GET":
        context['form'] = CreatePost()
        context['posts']= PostModel.objects.get(user_id = request.user.id)
        return render(request, "socialnetwork/blog.html", context)

    form = CreatePost(request.POST, request.FILES)
    if not form.is_valid():
        print("not valid ~~~~~~~~")
        context['form'] = form
        context['posts'] = PostModel.objects.get(user_id = request.user.id)
        return render(request, "socialnetwork/blog.html", context)

    post_input_text = form.cleaned_data.get("post_input_text")
    post_date_time = form.cleaned_data.get("post_date_time")
    post_profile = form.cleaned_data.get("post_profile")
    obj = PostModel.objects.get(
        user_id = request.user.id,
    )
    obj.post_input_text = form.cleaned_data.get("post_input_text")
    obj.post_date_time = form.cleaned_data.get("post_date_time")
    obj.post_profile = form.cleaned_data.get("post_profile")
    obj.save()
    form = CreatePost() #refresh the form to original state

    context['form'] = form
    context['posts'] = obj
    return render(request, "socialnetwork/blog.html", context)

def get_post(request, id):
    item = get_object_or_404(PostModel, id=id)
    print('Picture #{} fetched from db: {} (type={})'.format(id, item.post_input_text, item.post_profile, item.post_date_time))
    if not item.post_input_text:
        raise Http404
    return HttpResponse(item.post_input_text)

</code>```

forms.py

```<code>class CreatePost(forms.Form):
    post_input_text = forms.CharField(max_length=100)
    post_profile = forms.CharField(max_length=30)
    post_date_time = forms.DateTimeField()
</code>```

答: Update the template with {{ form.as_table }}, instead of {{form}}

Title: form not display on html, django

Body:
I tried to make a blog that allows user posts, store the posts in the db along with the posted date time and the person who posted it.

My problem is that I somehow cannot load the {{form}} to my UI, which makes my form invalid and I just don't know why it doesn't show up the input text box.

I'm not sure if I need a get_post function, but I'll just put it in views.py. (I havnt write the html of that part yet. Just need to see the form first.)
I'm pretty new to Django, can somebody pls help me with this!!!  Thanks!

Below are my files.

blog.html file:

{% block posts %}

New Post:
<form method="post" action="{% url 'posts' %}" enctype="multipart/form-data">
            {% csrf_token %}

                {{form}}

            <input id="id_post_button" type="submit" value="Submit" />

</form>

{% endblock %}

urls.py

urlpatterns = [
    path('posts', views.post_action, name='posts'),
    path('post/<int:id>', views.get_post, name='post'),
]

Models.py

class PostModel(models.Model):
    user_id = models.IntegerField()
    post_input_text = models.CharField(max_length=100)
    post_profile = models.CharField(max_length=30)
    post_date_time = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return 'id=' + str(self.user_id) + ", post_date_time=" + self.post_date_time + ", post_input_text=" + self.post_input_text + ", post_profile=" + self.post_profile

Views.py:

@login_required
def post_action(request):
    print("----post action---")
    context = {}
    if request.method == "GET":
        context['form'] = CreatePost()
        context['posts']= PostModel.objects.get(user_id = request.user.id)
        return render(request, "socialnetwork/blog.html", context)

    form = CreatePost(request.POST, request.FILES)
    if not form.is_valid():
        print("not valid ~~~~~~~~")
        context['form'] = form
        context['posts'] = PostModel.objects.get(user_id = request.user.id)
        return render(request, "socialnetwork/blog.html", context)

    post_input_text = form.cleaned_data.get("post_input_text")
    post_date_time = form.cleaned_data.get("post_date_time")
    post_profile = form.cleaned_data.get("post_profile")
    obj = PostModel.objects.get(
        user_id = request.user.id,
    )
    obj.post_input_text = form.cleaned_data.get("post_input_text")
    obj.post_date_time = form.cleaned_data.get("post_date_time")
    obj.post_profile = form.cleaned_data.get("post_profile")
    obj.save()
    form = CreatePost() #refresh the form to original state

    context['form'] = form
    context['posts'] = obj
    return render(request, "socialnetwork/blog.html", context)

def get_post(request, id):
    item = get_object_or_404(PostModel, id=id)
    print('Picture #{} fetched from db: {} (type={})'.format(id, item.post_input_text, item.post_profile, item.post_date_time))
    if not item.post_input_text:
        raise Http404
    return HttpResponse(item.post_input_text)

forms.py

class CreatePost(forms.Form):
    post_input_text = forms.CharField(max_length=100)
    post_profile = forms.CharField(max_length=30)
    post_date_time = forms.DateTimeField()


问:
Get exit code of SFTP command run by system()
my program created a script that executes sftp command using expect. The script should download a file from SFTP server. When the script is generated, my program call system command to run the script. The script should exit when an error is encountered. For example, if the password is wrong. How am I be able to get the error returned by sftp command?

Below is the code that generates and run the script:

```<code>downloadFileFromServer()
{
    ofstream downloadScript;
    string  result, command;

    downloadScript.open("/temp/download.sh");

    downloadScript << "#!/usr/bin/expect -f \n";
    downloadScript << "spawn sftp -P " + <port number> +
                      " " + <user name> +
                      "@" + <IP> + "\n";
    downloadScript << "expect { \ntimeout {\nsend_user \"Permission denied\\n\"\nexit\n}\n}\n";

    downloadScript << "send \"" + <password> + "\\n\"\n";
    downloadScript << "expect \"sftp>\"""\n";
    downloadScript << "send \"cd " + <source directory> + "\\n\"\n";
    downloadScript << "expect \"sftp>\"""\n";
    downloadScript << "send \"lcd " + <destination directory> + "\\n\"\n";
    downloadScript << "expect \"sftp>\"""\n";
    downloadScript << "send \"get " + <file name> + "\\n\"\n";
    downloadScript << "expect \"sftp>\"""\n";
    downloadScript << "send \"exit\\n\"\n";
    downloadScript << "expect -exact \"$\"""\n";

    downloadScript.close();

    command = "chmod +x /temp/download.sh && /temp/download.sh";
    system(command.c_str());

}
</code>```

Below is the script created:

```<code>#!/usr/bin/expect -f
spawn sftp -P <port numner> <user name>@<IP>
expect "<user name>@<IP>'s password:"
expect {
timeout {
send_user "Permission denied\n"
exit
}
}
send "<password>\n"
expect "sftp>"
send "cd <source directory>\n"
expect "sftp>"
send "lcd <destination directory>\n"
expect "sftp>"
send "get <file name>\n"
expect "sftp>"
send "exit\n"
expect -exact "$"
</code>```

I want my program to catch the "Permission denied" error.

答:
You need to send the password before checking for timeouts

```<code>expect "<user name>@<IP>'s password:"
send "<password>\n"
expect {
    timeout {
        send_user "Permission denied\n"
        exit 1
    }
    "sftp>"
}
send "cd ..."
</code>```

I have expect looking for either the timeout or the prompt, whichever one comes first.

Body:
my program created a script that executes sftp command using expect. The script should download a file from SFTP server. When the script is generated, my program call system command to run the script. The script should exit when an error is encountered. For example, if the password is wrong. How am I be able to get the error returned by sftp command?

Below is the code that generates and run the script:

downloadFileFromServer()
{
    ofstream downloadScript;
    string  result, command;

    downloadScript.open("/temp/download.sh");

    downloadScript << "#!/usr/bin/expect -f \n";
    downloadScript << "spawn sftp -P " + <port number> +
                      " " + <user name> +
                      "@" + <IP> + "\n";
    downloadScript << "expect { \ntimeout {\nsend_user \"Permission denied\\n\"\nexit\n}\n}\n";

    downloadScript << "send \"" + <password> + "\\n\"\n";
    downloadScript << "expect \"sftp>\"""\n";
    downloadScript << "send \"cd " + <source directory> + "\\n\"\n";
    downloadScript << "expect \"sftp>\"""\n";
    downloadScript << "send \"lcd " + <destination directory> + "\\n\"\n";
    downloadScript << "expect \"sftp>\"""\n";
    downloadScript << "send \"get " + <file name> + "\\n\"\n";
    downloadScript << "expect \"sftp>\"""\n";
    downloadScript << "send \"exit\\n\"\n";
    downloadScript << "expect -exact \"$\"""\n";

    downloadScript.close();

    command = "chmod +x /temp/download.sh && /temp/download.sh";
    system(command.c_str());

}

Below is the script created:

#!/usr/bin/expect -f
spawn sftp -P <port numner> <user name>@<IP>
expect "<user name>@<IP>'s password:"
expect {
timeout {
send_user "Permission denied\n"
exit
}
}
send "<password>\n"
expect "sftp>"
send "cd <source directory>\n"
expect "sftp>"
send "lcd <destination directory>\n"
expect "sftp>"
send "get <file name>\n"
expect "sftp>"
send "exit\n"
expect -exact "$"

I want my program to catch the "Permission denied" error.

Body:
You need to send the password before checking for timeouts

expect "<user name>@<IP>'s password:"
send "<password>\n"
expect {
    timeout {
        send_user "Permission denied\n"
        exit 1
    }
    "sftp>"
}
send "cd ..."

I have expect looking for either the timeout or the prompt, whichever one comes first.


问:
Can't get input value with Twig
Hello I was trying to pass some arguments but I don't know how to get value of input using twig here is my code :
okey first of all im displaying the blog details using this detailsaction which also rendering a form to add comments to the blog ;

```<code>public function detailsAction(Request $request,Blog $blog){

        $user=$this->getUser();
        if($user==null)
            return $this->redirectToRoute('fos_user_security_login');
        $add_comment = new CommentaireBlog();
        $em = $this->getDoctrine()->getManager();

        $comments = $em->getRepository(CommentaireBlog::class)->findByBlog($blog);
        $add_comment->setBlog($blog);
        $add_comment->setUser($user);
        $add_comment->setDate( new \DateTime());

        $form = $this->createFormBuilder($add_comment)

            ->add('contenu', TextareaType::class)

            ->getForm();

        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $add_comment = $form->getData();
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($add_comment);
                $em->flush();

                return $this->redirectToRoute('blog_details', array('id' => $blog->getId()));
            }
        }

        return $this->render('blog/details.html.twig', array(
            'form' => $form->createView(),
            'comment' => $add_comment,
            'blog' => $blog,
            'comments'=>$comments,
        ));

    }

</code>```

twig page:

```<code>   {{ form_start(form) }}
                                <div class="row form-group">

                                    <div class="col col-md-3"><label class=" form-control-label">Votre Commentaire  </label></div>
                                    <div class="col-12 col-md-9"> {{ form_widget(form.contenu, { 'attr': {'class': 'form-control'} }) }}<small class="form-text text-muted"></small></div>
                                    <button type="submit" class="btn btn-default">Envoyer</button>
                                    <div class="col-12 col-md-9">
                                    </div>
                                </div>
                                    {{ form_end(form) }}

</code>```

now what i want to do is that after someone add a comment and its(racist/verbual abuse..) an other user can report the comment and a mail will be sent so i used reportAction which take three arguments the reason the message and comment id

```<code>public function reportAction($msg,$type,$id)
    {

    }
</code>```

i still didnt write inside it cause first of all i need to the value of inputs so i went to the twig page and i made this little form to get inputs but idk how to get the value
here is the form :

```<code><div class="modal-body">
  <form id="lala" method="GET">
    <label for="cars">Reason:</label>
            <select id="reportreason">
                <option value="Inappropriate Content">Inappropriate Content</option>
                 <option value="Spam">Spam</option>
                <option value="Racism">Racism</option>
                <option value="Nudity">Nudity</option>
                 <option value="Other">Other</option>
      </select>
    <div class="form-group">
        <label for="message-text" class="col-form-label">Message:</label>
        <textarea id="reportmessage" class="form-control" id="message-text"></textarea>
    </div>
  </form>
</div>
 <div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    <a id="reportlink" href="{{ path('comment_report', { 'msg': form.vars.data.reportmessage ,'type': form.vars.data.reportreason, 'id': comment.id  }) }}" type="button" class="btn btn-primary">Send message</a>
</div>
</code>```

this is yml file :

```<code>blog_details:
    path:      /{id}/details
    defaults: { _controller: "BlogBundle:Blog:details" }
    methods:  [GET, POST]
comment_report:
    path:     /{msg}/{type}/{id}/report
    defaults: { _controller: "BlogBundle:Blog:report" }
    methods:  [GET, POST]
</code>```

but im getting this error now :
Neither the property "reportmessage" nor one of the methods "reportmessage()", "getreportmessage()"/"isreportmessage()" or "__call()" exist and have public access in class "BlogBundle\Entity\CommentaireBlog".

so how can i get get the value of the inputs using twig ?

答:
I don't know why you wrote your path call like that, but there should not be any round brackets about the variables you want to use in your route. The following code should work:

```<code><a
  href="{{ path('comment_report', { 'msg': form.reportmessage.value ,'type': form.reportreason.value, 'id': comment.id  }) }}"
  type="button"
  class="btn btn-primary">
     Send message
</a>
</code>```

Title: Can't get input value with Twig

Body:
Hello I was trying to pass some arguments but I don't know how to get value of input using twig here is my code :
okey first of all im displaying the blog details using this detailsaction which also rendering a form to add comments to the blog ;

public function detailsAction(Request $request,Blog $blog){

        $user=$this->getUser();
        if($user==null)
            return $this->redirectToRoute('fos_user_security_login');
        $add_comment = new CommentaireBlog();
        $em = $this->getDoctrine()->getManager();

        $comments = $em->getRepository(CommentaireBlog::class)->findByBlog($blog);
        $add_comment->setBlog($blog);
        $add_comment->setUser($user);
        $add_comment->setDate( new \DateTime());

        $form = $this->createFormBuilder($add_comment)

            ->add('contenu', TextareaType::class)

            ->getForm();

        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $add_comment = $form->getData();
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($add_comment);
                $em->flush();

                return $this->redirectToRoute('blog_details', array('id' => $blog->getId()));
            }
        }

        return $this->render('blog/details.html.twig', array(
            'form' => $form->createView(),
            'comment' => $add_comment,
            'blog' => $blog,
            'comments'=>$comments,
        ));

    }

twig page:

   {{ form_start(form) }}

Votre Commentaire

 {{ form_widget(form.contenu, { 'attr': {'class': 'form-control'} }) }}

                                    <button type="submit" class="btn btn-default">Envoyer</button>

                                    {{ form_end(form) }}

now what i want to do is that after someone add a comment and its(racist/verbual abuse..) an other user can report the comment and a mail will be sent so i used reportAction which take three arguments the reason the message and comment id

public function reportAction($msg,$type,$id)
    {

    }

i still didnt write inside it cause first of all i need to the value of inputs so i went to the twig page and i made this little form to get inputs but idk how to get the value
here is the form :

  <form id="lala" method="GET">
    Reason:
            <select id="reportreason">
                <option value="Inappropriate Content">Inappropriate Content</option>
                 <option value="Spam">Spam</option>
                <option value="Racism">Racism</option>
                <option value="Nudity">Nudity</option>
                 <option value="Other">Other</option>
      </select>

        Message:
        <textarea id="reportmessage" class="form-control" id="message-text"></textarea>

  </form>

    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    Send message

this is yml file :

blog_details:
    path:      /{id}/details
    defaults: { _controller: "BlogBundle:Blog:details" }
    methods:  [GET, POST]
comment_report:
    path:     /{msg}/{type}/{id}/report
    defaults: { _controller: "BlogBundle:Blog:report" }
    methods:  [GET, POST]

but im getting this error now :
Neither the property "reportmessage" nor one of the methods "reportmessage()", "getreportmessage()"/"isreportmessage()" or "__call()" exist and have public access in class "BlogBundle\Entity\CommentaireBlog".

so how can i get get the value of the inputs using twig ?

Body:
I don't know why you wrote your path call like that, but there should not be any round brackets about the variables you want to use in your route. The following code should work:

<a
  href="{{ path('comment_report', { 'msg': form.reportmessage.value ,'type': form.reportreason.value, 'id': comment.id  }) }}"
  type="button"
  class="btn btn-primary">
     Send message
</a>


问:
In PHP Remove several characters from the beginning of a String?
I need to find a specic line of text, from a text-file,
and then copy it to a new text-file:

1: I have a text file with several lines of text, eg:

```<code>JOHN
MIKE
BEN
*BJAMES
PETE
</code>```

2: So, I read that text-files contents into an array,
with each line of text, placed into a seperate element of the array.

3: Then I tested each element of the array,
to find the line that starts with, say: *B  ie:

```<code>if ( preg_match( "/^\*(B)/",$contents[$a] ) )
</code>```

Which works ok...

4: Then I copy (WRITE) that line of text, to a new text-file.

Q: So how can I remove the '*B' from that line of text,
BEFORE I WRITE it to the new text-file ?

答:
If you already use preg_match, you can modify your regex to get what you want in another variable.

```<code>if (preg_match('/^\*B(.*)$/', $contens[$a], $matches)
{
    fwrite($targetPointer, $matches[1]);
}
</code>```

After using preg_matchthe variable $matches holds the single matches of subparts of the regex enclosed in brackets. So the relevant part of your line ist matched by (.*) and saved into $matches[1].

Body:
I need to find a specic line of text, from a text-file,
and then copy it to a new text-file:

1: I have a text file with several lines of text, eg:

JOHN
MIKE
BEN
*BJAMES
PETE

2: So, I read that text-files contents into an array,
with each line of text, placed into a seperate element of the array.

3: Then I tested each element of the array,
to find the line that starts with, say: *B  ie:

if ( preg_match( "/^\*(B)/",$contents[$a] ) )

Which works ok...

4: Then I copy (WRITE) that line of text, to a new text-file.

Q: So how can I remove the '*B' from that line of text,
BEFORE I WRITE it to the new text-file ?

Body:
If you already use preg_match, you can modify your regex to get what you want in another variable.

if (preg_match('/^\*B(.*)$/', $contens[$a], $matches)
{
    fwrite($targetPointer, $matches[1]);
}

After using preg_matchthe variable $matches holds the single matches of subparts of the regex enclosed in brackets. So the relevant part of your line ist matched by (.*) and saved into $matches[1].


问:
Excel: Ensembl continue, how to save to CSV file after change R
Related to
Unable to use biomaRt package to get Gene Symbols from Entrez IDs

The code is working like a charm, but I would like to save it to my current CSV file and not only "viewing" it (adding an additional column will do the work as well, I got over 65k ids)

```<code>library(biomaRt)
marts <- listMarts()
ensembl <- useMart("ensembl")
datasets <- listDatasets(ensembl)
ensembl=useDataset("hsapiens_gene_ensembl",mart=ensembl)
attributes <- listAttributes(ensembl)
my_ids <- read.csv("LUADhtseq.csv")
ensembl = useEnsembl(biomart="ensembl", dataset="hsapiens_gene_ensembl")
results_end_1 <- getBM(attributes = c("ensembl_gene_id","external_gene_name"), values = my_ids, mart = ensembl )
View(results_end_1)
</code>```

答:
You are getting back all the entries in ensembl, and you need to merge:

```<code>my_ids = data.frame(ids=c("ENSG00000130203","ENSG00000136717","ENSG00000186868"))

df = merge(my_ids,results_end_1,by.x="ids",by.y="ensembl_gene_id")
df
              ids external_gene_name
1 ENSG00000130203               APOE
2 ENSG00000136717               BIN1
3 ENSG00000186868               MAPT
</code>```

Or you need to set the "filters" option to get the entries in my_ids, :

```<code>out <- getBM(attributes = c("ensembl_gene_id","external_gene_name"),
values = my_ids, mart = ensembl,filters="ensembl_gene_id")

  ensembl_gene_id external_gene_name
1 ENSG00000130203               APOE
2 ENSG00000136717               BIN1
3 ENSG00000186868               MAPT
</code>```

And you can write:

```<code>write.csv(out,"out.csv",row.names=FALSE,quote=FALSE)
</code>```

Body:
Related to
Unable to use biomaRt package to get Gene Symbols from Entrez IDs

The code is working like a charm, but I would like to save it to my current CSV file and not only "viewing" it (adding an additional column will do the work as well, I got over 65k ids)

library(biomaRt)
marts <- listMarts()
ensembl <- useMart("ensembl")
datasets <- listDatasets(ensembl)
ensembl=useDataset("hsapiens_gene_ensembl",mart=ensembl)
attributes <- listAttributes(ensembl)
my_ids <- read.csv("LUADhtseq.csv")
ensembl = useEnsembl(biomart="ensembl", dataset="hsapiens_gene_ensembl")
results_end_1 <- getBM(attributes = c("ensembl_gene_id","external_gene_name"), values = my_ids, mart = ensembl )
View(results_end_1)

Body:
You are getting back all the entries in ensembl, and you need to merge:

my_ids = data.frame(ids=c("ENSG00000130203","ENSG00000136717","ENSG00000186868"))

df = merge(my_ids,results_end_1,by.x="ids",by.y="ensembl_gene_id")
df
              ids external_gene_name
1 ENSG00000130203               APOE
2 ENSG00000136717               BIN1
3 ENSG00000186868               MAPT

Or you need to set the "filters" option to get the entries in my_ids, :

out <- getBM(attributes = c("ensembl_gene_id","external_gene_name"),
values = my_ids, mart = ensembl,filters="ensembl_gene_id")

  ensembl_gene_id external_gene_name
1 ENSG00000130203               APOE
2 ENSG00000136717               BIN1
3 ENSG00000186868               MAPT

And you can write:

write.csv(out,"out.csv",row.names=FALSE,quote=FALSE)


问:
How to open dropdown on hover in bootstrap 4
Right now my navigation drop down can open on click.

I want it to open upon hover. How do I do this?

答:
While I appreciate the answers to this question, the answers given are seemingly not the best. This is because these answers are disregarding accessibility.

Notice that, when using only CSS to make the dropdown show on .nav-link hover, the aria-expanded parameter on the .nav-link element does not change to true.

You must use some JS then in order to have the full range of accessibility functionality.

Below is what I have come up with to combat this.

// header_scripts.js

$('body').on('hover', '.nav-item.dropdown', function() {
    $(this).find('.dropdown-toggle').dropdown('toggle');
});

```

<pre class="lang-css prettyprint-override"><code>/* header.css */

.dropdown-menu {
    margin: 0 0 0 0;
}
</code>```

The above code should provide the same functionality that you are seeing in the other answers to this question, but with full accessibility concerns.

The CSS I gave is very general and has pretty low specificity so work with that as you see fit.

Body:
While I appreciate the answers to this question, the answers given are seemingly not the best. This is because these answers are disregarding accessibility.

Notice that, when using only CSS to make the dropdown show on .nav-link hover, the aria-expanded parameter on the .nav-link element does not change to true.

You must use some JS then in order to have the full range of accessibility functionality.

Below is what I have come up with to combat this.

// header_scripts.js

$('body').on('hover', '.nav-item.dropdown', function() {
    $(this).find('.dropdown-toggle').dropdown('toggle');
});

/* header.css */

.dropdown-menu {
    margin: 0 0 0 0;
}

The above code should provide the same functionality that you are seeing in the other answers to this question, but with full accessibility concerns.

The CSS I gave is very general and has pretty low specificity so work with that as you see fit.


问:
Is there a way to initialize a vector by index in c++11?
It is easy to fill the elements of a vector by index after it has been initialized:

```<code>std::vector<int> myVector {0, 0, 0};
int indexOfInterest = 1;
myVector[indexOfInterest] = 999;
// myVector now contains {0, 999, 0}
</code>```

However, is there a way to initialize a vector directly with the index? indexOfInterest may change in my code in the future, and I would like to avoid hard-coding the vector with

```<code>std::vector<int> myVector {0, 999, 0};
</code>```

Is there some syntax like

```<code>int indexOfInterest = 1;
std::vector<int> myVector[3] {indexOfInterest : 999}; // this is made-up syntax!
// desired: myVector contains {0, 999, 0} and is 3 elements large
</code>```

that can be used in C++11 to achieve this effect?

答:
As long as you want everything in the vector to be the same value except for the one value you want different, you can use</p>

```<code>std::vector<int> myVector(size_of_vector, /* some_value_here_if_you_do_not_want_0 */);
myVector[index_you_care_about] = value;
</code>```

Body:
It is easy to fill the elements of a vector by index after it has been initialized:

std::vector<int> myVector {0, 0, 0};
int indexOfInterest = 1;
myVector[indexOfInterest] = 999;
// myVector now contains {0, 999, 0}

However, is there a way to initialize a vector directly with the index? indexOfInterest may change in my code in the future, and I would like to avoid hard-coding the vector with

std::vector<int> myVector {0, 999, 0};

Is there some syntax like

int indexOfInterest = 1;
std::vector<int> myVector[3] {indexOfInterest : 999}; // this is made-up syntax!
// desired: myVector contains {0, 999, 0} and is 3 elements large

that can be used in C++11 to achieve this effect?

Body:
As long as you want everything in the vector to be the same value except for the one value you want different, you can use

std::vector<int> myVector(size_of_vector, /* some_value_here_if_you_do_not_want_0 */);
myVector[index_you_care_about] = value;


问:
How to get pinch effect to an image in iphone
Thanks in advance.

I want to get the pinch effect to an image means i want to change the shape of an image when i perform pinching on an image. I don't know is it possible or not, if it is possible can any one help me to do it using objective c in iphone.

答:
you need to associate a pinch gesture (type of UIPinchGestureRecognizer)with your UIImageView .

Check the below blog tutorial with sample code

Working with UIGesturerecognizer

Sample code from Apple


问:
How to switch UIImages in UIViewController from Array by pressing UIButton
So I have a storyboard with UIImageView and two buttons and I need these buttons to change images in UIImageView. UIImages stored in an Array. I tried for in but it can show only only first image. Help would be appreciated :)

class ViewController: UIViewController {

```<code>var images: [UIImage] = [
UIImage.init(named: "2")!,
UIImage.init(named: "3")!,
UIImage.init(named: "4")!]

override func viewDidLoad() {
    super.viewDidLoad() }

// Do any additional setup after loading the view.

@IBOutlet weak var imageView: UIImageView!

@IBAction func nextButton(_ sender: Any){
    for el in images {
        imageView.image = el }
}}
</code>```

答: Because of for loop in your @IBAction you only see the last image set to your image view. for solution you can define a variable, with button action increase the value and set it to your array index to show in your image view.

Body:
So I have a storyboard with UIImageView and two buttons and I need these buttons to change images in UIImageView. UIImages stored in an Array. I tried for in but it can show only only first image. Help would be appreciated :)

class ViewController: UIViewController {

var images: [UIImage] = [
UIImage.init(named: "2")!,
UIImage.init(named: "3")!,
UIImage.init(named: "4")!]

override func viewDidLoad() {
    super.viewDidLoad() }

// Do any additional setup after loading the view.

@IBOutlet weak var imageView: UIImageView!

@IBAction func nextButton(_ sender: Any){
    for el in images {
        imageView.image = el }
}}


问:
Fast page retrieval in MySQL, index usage?
I would like to speed a MySQL query that basically retrieve a page of data following the pattern below

```<code>select
 my_field_A,
 my_field_B
where
 time_id >= UNIX_TIMESTAMP('1901-01-01  00:00:00') AND
 time_id < UNIX_TIMESTAMP('2009-01-16  00:00:00')
</code>```

The field time_id is an MySQL index, yet, the query behaves as if the entire database was read at each query (retrieving a couple of lines being already quite slow). I not an expert in MySQL. Can someone guess what I am doing wrong?

答:
Make sure you have an index (B-tree) on time_id, this should be efficient for range queries. Also make sure that time_id is in the appropriate time format.

If you really want to understand what mysql is doing you can add the keyword 'explain' infront of the query and run it in your mysql client. This will show some information about what mysql is doing and what kind of scans are performed.

http://dev.mysql.com/doc/refman/5.0/en/using-explain.html

OwnerDisplayName: Joannes Vermorel

ContentLicense: CC BY-SA 2.5

Body:
I would like to speed a MySQL query that basically retrieve a page of data following the pattern below

select
 my_field_A,
 my_field_B
where
 time_id >= UNIX_TIMESTAMP('1901-01-01  00:00:00') AND
 time_id < UNIX_TIMESTAMP('2009-01-16  00:00:00')

The field time_id is an MySQL index, yet, the query behaves as if the entire database was read at each query (retrieving a couple of lines being already quite slow). I not an expert in MySQL. Can someone guess what I am doing wrong?

LastEditorDisplayName: Joannes Vermorel

OwnerDisplayName: Tomh


问:
new tabs opened with the scroll wheel of a mouse do not have a window.opener object
If I use the left mouse button to click on an anchor tag with a target of _blank window.opener is defined. If I use the scroll wheel to click on that same anchor tag, however, window.opener is not defined.

The issue is reproducable in Google Chrome and Firefox, on Windows 10 and Mac OS X and idk what to do about it.

Is there a way, in Javascript, I could disable scroll wheel clicking for select links? Maybe I could hook into a scroll wheel click event and make it behave as a left mouse click instead?

Thanks!

答:
As far as I can tell, you can emulate this behavior by checking event.button

document.addEventListener('click', function (e) {
 // detecting that it was a wheel click on a link
 if (
  e.button === 1 &&
  e.target.tagName === 'A'
 ) {
   window.open(event.target.href);
   e.preventDefault();
 }
});

```

However, this solution won't work if you are opening a link from another domain.

Body:
As far as I can tell, you can emulate this behavior by checking event.button

document.addEventListener('click', function (e) {
 // detecting that it was a wheel click on a link
 if (
  e.button === 1 &&
  e.target.tagName === 'A'
 ) {
   window.open(event.target.href);
   e.preventDefault();
 }
});

However, this solution won't work if you are opening a link from another domain.


问:
TextView with spans , how can I know which one is clicked on?
I am using this library, but from the onClick styles that they have, neither handles my needed case.
https://github.com/splitwise/TokenAutoComplete

So I wanted to do my own. So I have a ContactsCompletionView, which is a TextView. and I override the onTouchEvent like this:

```<code>override fun onTouchEvent(event: MotionEvent): Boolean {
    val action = event.actionMasked
    val text = text
    var handled = super.onTouchEvent(event)
    if (isFocused && text != null && action == MotionEvent.ACTION_UP) {
        val offset = getOffsetForPosition(event.x, event.y)
        if (offset != -1) {
            var offseted = text.substring(offset, text.length)
            var indexLeft = offseted.indexOf("(") + 1
            var indexRight = offseted.indexOf(")")
            if (indexLeft > 0 && indexRight > indexLeft)
                Toast.makeText(context, offseted.substring(indexLeft, indexRight), Toast.LENGTH_SHORT).show()
        }
    }
    return handled
}
</code>```

This is what they had, but I cannot use TokenImageSpan because it is a protected class:

```<code>@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
    int action = event.getActionMasked();
    Editable text = getText();
    boolean handled = false;

    if (tokenClickStyle == TokenClickStyle.None) {
        handled = super.onTouchEvent(event);
    }

    if (isFocused() && text != null && lastLayout != null && action == MotionEvent.ACTION_UP) {

        int offset = getOffsetForPosition(event.getX(), event.getY());

        if (offset != -1) {
            TokenImageSpan[] links = text.getSpans(offset, offset, TokenImageSpan.class);

            if (links.length > 0) {
                links[0].onClick();
                handled = true;
            } else {
                //We didn't click on a token, so if any are selected, we should clear that
                clearSelections();
            }
        }
    }

    if (!handled && tokenClickStyle != TokenClickStyle.None) {
        handled = super.onTouchEvent(event);
    }
    return handled;

}
</code>```

My code works, but my issue is that whenever I press an TAG at the end of it. It gets the next object. I assume that this is because I just use:

```<code> val offset = getOffsetForPosition(event.x, event.y)
 if (offset != -1) {
     var offseted = text.substring(offset, text.length)
 }
</code>```

When they use:

```<code>  if (offset != -1) {
      TokenImageSpan[] links = text.getSpans(offset, offset, TokenImageSpan.class);
  }
</code>```

TokenImageSpan extends ImageSpan, so I can use it like that, But I do not know how to take the text from the ImageSpan. Any ideas how I can fix this please?

答:
You can use clickable span as below:</p>

```<code>SpannableString ss = new SpannableString("your string comes
here");
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View textView) {
    //do your stuff here on click
}
@Override
public void updateDrawState(TextPaint ds) {
    super.updateDrawState(ds);
    ds.setUnderlineText(false);
}
};

//set click range
ss.setSpan(clickableSpan, 8, 15,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

//your text view or edittext
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(Color.TRANSPARENT);
</code>```

Body:
I am using this library, but from the onClick styles that they have, neither handles my needed case.
https://github.com/splitwise/TokenAutoComplete

So I wanted to do my own. So I have a ContactsCompletionView, which is a TextView. and I override the onTouchEvent like this:

override fun onTouchEvent(event: MotionEvent): Boolean {
    val action = event.actionMasked
    val text = text
    var handled = super.onTouchEvent(event)
    if (isFocused && text != null && action == MotionEvent.ACTION_UP) {
        val offset = getOffsetForPosition(event.x, event.y)
        if (offset != -1) {
            var offseted = text.substring(offset, text.length)
            var indexLeft = offseted.indexOf("(") + 1
            var indexRight = offseted.indexOf(")")
            if (indexLeft > 0 && indexRight > indexLeft)
                Toast.makeText(context, offseted.substring(indexLeft, indexRight), Toast.LENGTH_SHORT).show()
        }
    }
    return handled
}

This is what they had, but I cannot use TokenImageSpan because it is a protected class:

@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
    int action = event.getActionMasked();
    Editable text = getText();
    boolean handled = false;

    if (tokenClickStyle == TokenClickStyle.None) {
        handled = super.onTouchEvent(event);
    }

    if (isFocused() && text != null && lastLayout != null && action == MotionEvent.ACTION_UP) {

        int offset = getOffsetForPosition(event.getX(), event.getY());

        if (offset != -1) {
            TokenImageSpan[] links = text.getSpans(offset, offset, TokenImageSpan.class);

            if (links.length > 0) {
                links[0].onClick();
                handled = true;
            } else {
                //We didn't click on a token, so if any are selected, we should clear that
                clearSelections();
            }
        }
    }

    if (!handled && tokenClickStyle != TokenClickStyle.None) {
        handled = super.onTouchEvent(event);
    }
    return handled;

}

My code works, but my issue is that whenever I press an TAG at the end of it. It gets the next object. I assume that this is because I just use:

 val offset = getOffsetForPosition(event.x, event.y)
 if (offset != -1) {
     var offseted = text.substring(offset, text.length)
 }

When they use:

  if (offset != -1) {
      TokenImageSpan[] links = text.getSpans(offset, offset, TokenImageSpan.class);
  }

TokenImageSpan extends ImageSpan, so I can use it like that, But I do not know how to take the text from the ImageSpan. Any ideas how I can fix this please?

Body:
You can use clickable span as below:

SpannableString ss = new SpannableString("your string comes
here");
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View textView) {
    //do your stuff here on click
}
@Override
public void updateDrawState(TextPaint ds) {
    super.updateDrawState(ds);
    ds.setUnderlineText(false);
}
};

//set click range
ss.setSpan(clickableSpan, 8, 15,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

//your text view or edittext
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(Color.TRANSPARENT);


问:
finer-grained control than with LD_PRELOAD?
I have a dynamically linked ELF executable on Linux, and I want to swap a function in a library it is linked against. With LD_PRELOAD I can, of course, supply a small library with a replacement for the function that I compile myself. However, what if in the replacement I want to call the original library function? For example, the function may be srand(), and I want to hijack it with my own seed choice but otherwise let srand() do whatever it normally does.

If I were linking to make said executable, I would use the wrap option of the linker but here I only have the compiled binary.

One trivial solution I see is to cut and paste the source code for the original library function into the replacement - but I want to handle the more general case when the source is unavailable. Or, I could hex edit the needed extra code into the binary but that is specific to the binary and also time consuming. Is something more elegant possible than either of these? Such as some magic with the loader?

(Apologies if I were not using the terminology precisely...)

答:
Here's an example of wrapping malloc:</p>

```<code>// LD_PRELOAD will cause the process to call this instead of malloc(3)
// report malloc(size) calls
void *malloc(size_t size)
    {
    // on first call, get a function pointer for malloc(3)
    static void *(*real_malloc)(size_t) = NULL;
    static int malloc_signal = 0;
    if(!real_malloc)
        {
        // real_malloc = (void *(*)(size_t))dlsym(RTLD_NEXT, "malloc");
        *(void **) (&real_malloc) = dlsym(RTLD_NEXT, "malloc");
        }
    assert(real_malloc);
    if (malloc_signal == 0)
        {
        char *string = getenv("MW_MALLOC_SIGNAL");
        if (string != NULL)
            {
            malloc_signal = 1;
            }
        }

    // call malloc(3)
    void *retval = real_malloc(size);
    fprintf(stderr, "MW! %f malloc size %zu, address %p\n", get_seconds(), size, retval);
    if (malloc_signal == 1)
        {
        send_signal(SIGUSR1);
        }
    return retval;
    }
</code>```

Body:
Here's an example of wrapping malloc:

// LD_PRELOAD will cause the process to call this instead of malloc(3)
// report malloc(size) calls
void *malloc(size_t size)
    {
    // on first call, get a function pointer for malloc(3)
    static void *(*real_malloc)(size_t) = NULL;
    static int malloc_signal = 0;
    if(!real_malloc)
        {
        // real_malloc = (void *(*)(size_t))dlsym(RTLD_NEXT, "malloc");
        *(void **) (&real_malloc) = dlsym(RTLD_NEXT, "malloc");
        }
    assert(real_malloc);
    if (malloc_signal == 0)
        {
        char *string = getenv("MW_MALLOC_SIGNAL");
        if (string != NULL)
            {
            malloc_signal = 1;
            }
        }

    // call malloc(3)
    void *retval = real_malloc(size);
    fprintf(stderr, "MW! %f malloc size %zu, address %p\n", get_seconds(), size, retval);
    if (malloc_signal == 1)
        {
        send_signal(SIGUSR1);
        }
    return retval;
    }