问:
Ionic 3 image pinch and double tap zoom
I want to show a zoomable SVG image inside an ion-tab on an Ionic 3 project. The effect I am looking for is just a regular pinch and double tap zoom, nothing special.

I've tried different combinations, but I can't make it work. This is what I have right now:

HTML:

```<code><ion-content>
  <ion-scroll scrollX="true" scrollY="true" zoom="true" overflow-scroll="false" class="scroll-view" min-zoom="1" maxZoom="10">
    <img src="assets/img/image.svg">
  </ion-scroll>
</ion-content>
</code>```

CSS:

```<code>.scroll-view{
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
</code>```

Any ideas? Thanks!

答:
Zoom, pinch, double tap zoom of Image (tested in Ionic 4).

Use Photo Viewer.

Works with live URL only.

In app.module.ts

import { PhotoViewer } from '@ionic-native/photo-viewer/ngx';

...

providers: [
    PhotoViewer, ...
],
```

<p>In custom.ts</p>

<pre class="lang-js prettyprint-override"><code>import { PhotoViewer } from
'@ionic-native/photo-viewer/ngx';

...

constructor(private photoViewer: PhotoViewer) { }

...

showPhoto()
{
    console.log("showPhoto");
   this.photoViewer.show('https://dummyimage.com/600x400/000/fff');
}
</code>```

In custom.html

```

Title: Ionic 3 image pinch and double tap zoom

Body:
I want to show a zoomable SVG image inside an ion-tab on an Ionic 3 project. The effect I am looking for is just a regular pinch and double tap zoom, nothing special.

I've tried different combinations, but I can't make it work. This is what I have right now:

HTML:

<ion-content>
  <ion-scroll scrollX="true" scrollY="true" zoom="true" overflow-scroll="false" class="scroll-view" min-zoom="1" maxZoom="10">

  </ion-scroll>
</ion-content>

CSS:

.scroll-view{
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

Any ideas? Thanks!

Body:
Zoom, pinch, double tap zoom of Image (tested in Ionic 4).

Use Photo Viewer.

Works with live URL only.

In app.module.ts

import { PhotoViewer } from '@ionic-native/photo-viewer/ngx';

...

providers: [
    PhotoViewer, ...
],

In custom.ts

import { PhotoViewer } from
'@ionic-native/photo-viewer/ngx';

...

constructor(private photoViewer: PhotoViewer) { }

...

showPhoto()
{
    console.log("showPhoto");
   this.photoViewer.show('https://dummyimage.com/600x400/000/fff');
}

In custom.html

<img (click)="showPhoto()" />


来源: stackexchange

问:
Add REST controller/route to SpringBoot test
Is it possible to add a route/endpoint (which I don't want to include in the sources, but rather leave it in the tests) to a SpringBoot test?

```<code>@RestController
class HelloAPI {
    @GetMapping("/hello")
    public String ok() {
        return "world";
    }
}
</code>```

UPDATE:
As it turned out no extra configuration is needed - HelloAPI class should be moved from src/main to src/test. That's it. However, it will be "visible" to all @SpringBoot tests.

So the question is: how can I restrict the creation (registration in the ApplicationContext) of this bean (HelloAPI) to a particular test class?

See link to an example project

答:
You could add a static inner @Configuration class in which the bean is set up:

```<code>@RunWith(SpringRunner.class)
... // Other test annotations
public class YourTestClass {

    @Configuration
    static class ContextConfiguration {
        @Bean
        public HelloAPI helloAPI() {
            return new HelloAPI();
        }
    }

    @Test
    public void someTest_shouldXxx() { ... }
}
</code>```

And be sure to add your HelloAPI class in /src/test instead of /src/main/.

Note however that (test)ApplicationContext will be destroyed after all the tests in the class have been performed, thereby destroying the HelloAPI bean as well.

If you are looking for way to offer test-endpoints to a RestTemplate, bind a MockRestServiceServer to your RestTemplate instead.

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to add a route/endpoint (which I don't want to include in the sources, but rather leave it in the tests) to a SpringBoot test?

@RestController
class HelloAPI {
    @GetMapping("/hello")
    public String ok() {
        return "world";
    }
}

UPDATE:
As it turned out no extra configuration is needed - HelloAPI class should be moved from src/main to src/test. That's it. However, it will be "visible" to all @SpringBoot tests.

So the question is: how can I restrict the creation (registration in the ApplicationContext) of this bean (HelloAPI) to a particular test class?

See link to an example project

Body:
You could add a static inner @Configuration class in which the bean is set up:

@RunWith(SpringRunner.class)
... // Other test annotations
public class YourTestClass {

    @Configuration
    static class ContextConfiguration {
        @Bean
        public HelloAPI helloAPI() {
            return new HelloAPI();
        }
    }

    @Test
    public void someTest_shouldXxx() { ... }
}

And be sure to add your HelloAPI class in /src/test instead of /src/main/.

Note however that (test)ApplicationContext will be destroyed after all the tests in the class have been performed, thereby destroying the HelloAPI bean as well.

If you are looking for way to offer test-endpoints to a RestTemplate, bind a MockRestServiceServer to your RestTemplate instead.


问:
call stack from Docker shows my local paths. Is it nomal?

I created a .NET Core controller returning pdf file which works fine on my local machine. When I wrap it into a Linux image I receive an error:

The type initializer for 'Gdip' threw an exception.

So I created a logging tool which gave me that call stack:

at
  System.Drawing.SafeNativeMethods.Gdip.GdipNewPrivateFontCollection(IntPtr&
  fontCollection)
 at SelectPdf.Lib.ᡜ..ctor()
 at
  SelectPdf.Lib.៞..ctor()
    at SelectPdf.Lib.៞..ctor(ᡏ A_0, ᠝
  A_1)
    at SelectPdf.HtmlToPdf.ᜁ(String A_0, String A_1, String
  A_2, String A_3, Boolean A_4)
    at
  SelectPdf.HtmlToPdf.ConvertHtmlString(String htmlString)
    at
  PdfBuilders.PdfBuilder.Create() in
  C:\Projects\server\intranet.api\Intranet.Api\PDFCreators\PdfBuilder.cs:line
  65
 at
  WorklogAgregators.SingleEmployeePdfReport.CreateReport(PhotoLoginReportWithTotalDto
  reportDto, String& fileName) in
  C:\Projects\server\intranet.api\Intranet.Api\WorklogAgregators\SingleEmployeePdfReport.cs:line
  58
 at
  Login.Api.Controllers.WorklogTimesController.d__10.MoveNext()
  in
  C:\Projects\server\intranet.api\Intranet.Api\Login.API\Controllers\WorklogTimesController.cs:line
  138

And here is the funny part:

Path C:\Projects\server\intranet.api is where I keep the code on my local machine, but docker image has been put onto external server.

Is there some possibility that docker image actually searches for those files and that is the reason why it does not work?
Every other controllers works fine.

答:
TLDR You've built your app on your local PC together with pdb files and these files store your local paths, which are displayed regardless of where the code is being executed.

Error reporting as well as debug info recovers data from so-called pdb files, which are program database. These files store meta information about your program code, including original file names, locations and source code line numbers.
The amount of information stored is controllable and usually depends on your build type (Debug, Release). These files are being distributed together with your binaries and whichever system is used as a host, whenever it needs meta information (like call stack), it takes it from them.


问:
System properties management
Is there any "adequate" way to change system properties in Jenkins? What is the easiest/fastest way change them? For instance, I need to turn off the useless (in my case) pinging thread.</p>

答:
I followed each steps mentioned above but it fails.

So I did change the system time zone using timedatectl set-timezone Europe/London command and then I have restarted jenkins service service jenkins restart it worked.

I was using Rehdat 7.5

Jenkins version 2.168.

Jenkins Installed via yum install jenkins

I hope this will help some one.

ContentLicense: CC BY-SA 3.0

Title: System properties management


问:
Terraform destroying RDS instance and retaining automated backups
I have created and I have been managing a Postgresql RDS instance using Terraform.

Assuming I perform a terraform destroy, will this also delete the associated RDS snapshots that have been taken via the RDS schedule?

答:
When destroying an RDS database you have the option to either create a long lived final snapshot or retain the automated backups which will be deleted as per the schedule they were set for:

Instead of creating a snapshot, you can choose to enable Retain automated backups when you delete a DB instance. These backups are still subject to the retention period of the DB instance and age out the same way systems snapshots do.

Terraform supports keeping a final snapshot by setting the final_snapshot_identifier and making sure that skip_final_snapshot is not set to true.

Unfortunately, Terraform doesn't currently support retaining the automated backups taken from scheduled snapshots but there is an open feature request with a couple of half finished pull requests linked to it.


问:
How to select date and previous date
I have a table of referral records with a start date and end date. If the person has had previous referrals I need to retrieve the start and end date of the referral previous to the current one.

Any ideas would be greatly appreciated!

Example of what I hope to achieve

```<code>Per ID    Ref ID    Refrl_Start_D    Refrl_End_D    Prev_Refrl_S    Prev_Refrl_S
1         5         10/10/2018       Null           01/02/2018      03/03/2018
2         4         05/04/2018       Null           01/01/2017      01/03/2017
1         3         01/02/2018       03/03/2018     02/01/2017      20/01/2017
1         2         02/01/2018       20/01/2018     Null            Null
2         1         01/01/2018       01/03/2018     Null            Null
</code>```

Is have tried adding a Rank calc grouped by person. My plan was to create another table offset it by 1 and join them (i.e. Join referral 5 with 4). However I couldn't figure out how to get the join right.

```<code>SELECT DIM_PERSON_ID,
       FACT_REFERRAL_ID,
       REFRL_START_DTTM,
       REFRL_END_DTTM
FROM FACT_REFERRALS;
</code>```

答:
You should be able to construct this with a CTE to calculate a rank/row number for each record based on the referral dates, then join the CTE to itself to get the previous referral. E.g:</p>

```<code>WITH RANKED_REFERRALS AS (
  SELECT DIM_PERSON_ID,
         FACT_REFERRAL_ID,
         REFRL_START_DTTM,
         REFRL_END_DTTM,
         ROW_NUMBER() OVER(PARTITION BY DIM_PERSON_ID ORDER BY REFRL_START_DATE) AS ROWNUM
  FROM FACT_REFERRALS
)
SELECT A.DIM_PERSON_ID,
       A.ACT_REFERRAL_ID,
       A.REFRL_START_DTTM,
       A.REFRL_END_DTTM,
       B.REFRL_START_DTTM,
       B.REFRL_END_DTTM
FROM RANKED_REFERRALS A
LEFT JOIN RANKED_REFERRALS B ON B.DIM_PERSON_ID = A.DIM_PERSON_ID AND B.ROWNUM = A.ROWNUM - 1
</code>```

Title: How to select date and previous date

Body:
I have a table of referral records with a start date and end date. If the person has had previous referrals I need to retrieve the start and end date of the referral previous to the current one.

Any ideas would be greatly appreciated!

Example of what I hope to achieve

Per ID    Ref ID    Refrl_Start_D    Refrl_End_D    Prev_Refrl_S    Prev_Refrl_S
1         5         10/10/2018       Null           01/02/2018      03/03/2018
2         4         05/04/2018       Null           01/01/2017      01/03/2017
1         3         01/02/2018       03/03/2018     02/01/2017      20/01/2017
1         2         02/01/2018       20/01/2018     Null            Null
2         1         01/01/2018       01/03/2018     Null            Null

Is have tried adding a Rank calc grouped by person. My plan was to create another table offset it by 1 and join them (i.e. Join referral 5 with 4). However I couldn't figure out how to get the join right.

SELECT DIM_PERSON_ID,
       FACT_REFERRAL_ID,
       REFRL_START_DTTM,
       REFRL_END_DTTM
FROM FACT_REFERRALS;

Body:
You should be able to construct this with a CTE to calculate a rank/row number for each record based on the referral dates, then join the CTE to itself to get the previous referral. E.g:

WITH RANKED_REFERRALS AS (
  SELECT DIM_PERSON_ID,
         FACT_REFERRAL_ID,
         REFRL_START_DTTM,
         REFRL_END_DTTM,
         ROW_NUMBER() OVER(PARTITION BY DIM_PERSON_ID ORDER BY REFRL_START_DATE) AS ROWNUM
  FROM FACT_REFERRALS
)
SELECT A.DIM_PERSON_ID,
       A.ACT_REFERRAL_ID,
       A.REFRL_START_DTTM,
       A.REFRL_END_DTTM,
       B.REFRL_START_DTTM,
       B.REFRL_END_DTTM
FROM RANKED_REFERRALS A
LEFT JOIN RANKED_REFERRALS B ON B.DIM_PERSON_ID = A.DIM_PERSON_ID AND B.ROWNUM = A.ROWNUM - 1


问:
select from string from outcome of json file in postgresql
In postgre sql my table has attributes column with json format below

```<code>{"color": true,"view": [184],"school":
[805,812,855,856,857]}
</code>```

I would like write a column that if the school contains 805,812,855 then 1 else 0. Below I tried but it is not working.

```<code> case when  json_extract_path_text(attributes, 'school') in
 [805,812,855] then 1 else 0 end as school
</code>```

How can I fix this?
Thank you.

答:
Actually I got the answer</p>

```<code>case when json_extract_path_text(attributes, 'school')::jsonb@>'805' then 1
     when json_extract_path_text(attributes, 'school')::jsonb@>'812' then 1
     when json_extract_path_text(attributes, 'school')::jsonb@>'855' then 1
else
0 end as school
</code>```

Body:
In postgre sql my table has attributes column with json format below

{"color": true,"view": [184],"school":
[805,812,855,856,857]}

I would like write a column that if the school contains 805,812,855 then 1 else 0. Below I tried but it is not working.

 case when  json_extract_path_text(attributes, 'school') in
 [805,812,855] then 1 else 0 end as school

How can I fix this?
Thank you.

Body:
Actually I got the answer

case when json_extract_path_text(attributes, 'school')::jsonb@>'805' then 1
     when json_extract_path_text(attributes, 'school')::jsonb@>'812' then 1
     when json_extract_path_text(attributes, 'school')::jsonb@>'855' then 1
else
0 end as school


问:
how to treat special characters in variable names
I have a json which has the a particular format, I wanted to extract data from it, but it contains ':' in its key value which is giving error while printing</p>

```<code>metadata:
   {
      'A:B':'string'
   }

I have tried to take it in another varibale stills it gives error:

text='A'+':'+'B';
console.log(metadata.text);

//console.log(metadata.A:B);

</code>```

答:
You can simply use jsonVariableName["ObjectName"] instead of sonVariableName.ObjectName

```<code>var metadata = {
      'A:B':'string'
 };
console.log(metadata["A:B"]);
</code>```

Also I found you mention code as:
metadata:{...}
Which I think will be:
metadata = {...}

Body:
I have a json which has the a particular format, I wanted to extract data from it, but it contains ':' in its key value which is giving error while printing

metadata:
   {
      'A:B':'string'
   }

I have tried to take it in another varibale stills it gives error:

text='A'+':'+'B';
console.log(metadata.text);

//console.log(metadata.A:B);

Body:
You can simply use jsonVariableName["ObjectName"] instead of sonVariableName.ObjectName

var metadata = {
      'A:B':'string'
 };
console.log(metadata["A:B"]);

Also I found you mention code as:
metadata:{...}
Which I think will be:
metadata = {...}


问:
problem with Javascript dynamic module import containing variables
Okay, so I've been bumping my head on the walls trying to figure out what the hell's going on here. See, I've been trying to load a module dynamically in Vue.js. What confuses me here is that the following actually works (i.e. when I hardcode the path to my module):

```<code>currentModal(){
    return () => System.import(`../../ride/modals/boarding.vue`);
},
</code>```

However, if I do this:

```<code>currentModal(){
    let path = "../../ride/modals/";
    return () => System.import(`${path}boarding.vue`);
},
</code>```

I get the following error:

Cannot find module '../../ride/modals/boarding.vue'.

Then, if I go the other way around and do:

```<code>currentModal(){
    let content = "boarding.vue";
    return () => System.import(`../../ride/modals/${content}`);
},
</code>```

The error becomes:

Error in render: "TypeError: undefined is not a function"

Obviously, something's different when I use a variable instead of hardcoding the path... but for the life of me, I can't figure out what. Anyone has any clue?

答:
As Bergur mentioned in his comment, the problem is indeed that webpack cannot resolve a string that doesn't yet exist (issue explained here). What I did instead is add a property to my component that I called "content-list" and in the main page, I fill it with my desired components like so:

parent component:

```<code><template>

    .....

    <modal-window
                    :init-visible="modalVisible"
                    :content-list="contentList"
                    @modalClosed="modalClosed">
    </modal-window>

    .....

</template>

<script>
    import mainContent from './modals/main.vue';  //I doubt this is still useful
    import otherContent from './modals/other.vue'; //I doubt this is still useful

    export default{
        data(){
            return {

                modalVisible: false,

                contentList: {
                    main:       () => System.import("./modals/main.vue"),
                    other:      () => System.import("./modals/other.vue")
                },
            }
        },
    }

</script>
</code>```

Inside the modal component:

```<code><template>

    ...

    <div ref="scrolling-pane" class="scrolling-pane" :class="{ 'scrolling-pane-normal': !isDirty, 'scrolling-pane-dirty': isDirty }" key="b">
        <transition name="content-slide"
                    :enter-active-class="enterClassName"
                    :leave-active-class="leaveClassName"
                    @before-enter="beforeEnter"
                    @before-leave="beforeLeave"
                    @after-enter="afterEnter"
                    @after-leave="afterLeave">

            <keep-alive>
                <component :is="currentModal" @switchContent="onSwitchContent"></component>
            </keep-alive>
        </transition>
    </div>

    ...

</template>

<script>

export default{
        components: {
        },

        props: {
            initVisible: Boolean,
            contentList: Object
        },
        data(){
            return {
                currentContent: this.contentList['main']
            }
        }

        ...

</script>
</code>```

Body:
Okay, so I've been bumping my head on the walls trying to figure out what the hell's going on here. See, I've been trying to load a module dynamically in Vue.js. What confuses me here is that the following actually works (i.e. when I hardcode the path to my module):

currentModal(){
    return () => System.import(`../../ride/modals/boarding.vue`);
},

However, if I do this:

currentModal(){
    let path = "../../ride/modals/";
    return () => System.import(`${path}boarding.vue`);
},

I get the following error:

Cannot find module '../../ride/modals/boarding.vue'.

Then, if I go the other way around and do:

currentModal(){
    let content = "boarding.vue";
    return () => System.import(`../../ride/modals/${content}`);
},

The error becomes:

Error in render: "TypeError: undefined is not a function"

Obviously, something's different when I use a variable instead of hardcoding the path... but for the life of me, I can't figure out what. Anyone has any clue?

Body:
As Bergur mentioned in his comment, the problem is indeed that webpack cannot resolve a string that doesn't yet exist (issue explained here). What I did instead is add a property to my component that I called "content-list" and in the main page, I fill it with my desired components like so:

parent component:

<template>

    .....

    <modal-window
                    :init-visible="modalVisible"
                    :content-list="contentList"
                    @modalClosed="modalClosed">
    </modal-window>

    .....

</template>

<script>
    import mainContent from './modals/main.vue';  //I doubt this is still useful
    import otherContent from './modals/other.vue'; //I doubt this is still useful

    export default{
        data(){
            return {

                modalVisible: false,

                contentList: {
                    main:       () => System.import("./modals/main.vue"),
                    other:      () => System.import("./modals/other.vue")
                },
            }
        },
    }

</script>

Inside the modal component:

<template>

    ...

    <div ref="scrolling-pane" class="scrolling-pane" :class="{ 'scrolling-pane-normal': !isDirty, 'scrolling-pane-dirty': isDirty }" key="b">
        <transition name="content-slide"
                    :enter-active-class="enterClassName"
                    :leave-active-class="leaveClassName"
                    @before-enter="beforeEnter"
                    @before-leave="beforeLeave"
                    @after-enter="afterEnter"
                    @after-leave="afterLeave">

            <keep-alive>
                <component :is="currentModal" @switchContent="onSwitchContent"></component>
            </keep-alive>
        </transition>
    </div>

    ...

</template>

<script>

export default{
        components: {
        },

        props: {
            initVisible: Boolean,
            contentList: Object
        },
        data(){
            return {
                currentContent: this.contentList['main']
            }
        }

        ...

</script>


问:
Div with margin-left and width:100% overflowing on the right side
I have 2 nested div's that should be 100% wide. Unfortunately the inner div with the Textbox overflows and is actually larger than the outer div. It has a left margin and overflows by about the size of the margin.

How can I fix that?

```<code><div style="width:100%;">
    <div style="margin-left:45px; width:100%;">
    <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
    </div>
</div>
</code>```

If I don't do the 100%, then the textbox is not 100% wide.

答:
If some other portion of your layout is influencing the div width you can set width:auto and the div (which is a block element) will fill the space

```<code><div style="width:auto">
    <div style="margin-left:45px;width:auto">
        <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
    </div>
</div>
</code>```

If that's still not working we may need to see more of your layout HTML/CSS

Body:
I have 2 nested div's that should be 100% wide. Unfortunately the inner div with the Textbox overflows and is actually larger than the outer div. It has a left margin and overflows by about the size of the margin.

How can I fix that?

    <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox>

If I don't do the 100%, then the textbox is not 100% wide.

Body:
If some other portion of your layout is influencing the div width you can set width:auto and the div (which is a block element) will fill the space

<div style="width:auto">
    <div style="margin-left:45px;width:auto">
        <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
    </div>
</div>

If that's still not working we may need to see more of your layout HTML/CSS


问:
How to define common import packages with resolution optional in build.bnd
I wanted to import some packages in all bundles with resolution optional using build.bnd

I have tried below code but it's showing only package name in imports, not resolution optional

```<code>common-imports:${if;${debug};com.example.foo.debug\;resolution:=optional}
Import-Package: \
${common-imports}, \
*
</code>```

It should show

    Import:com.example.foo.debug;resolution:=optional but its showing
    Import:com.example.foo.debug

答:
You need 2 backslashes before the ;resolution.

common-imports: ${if;${debug};com.example.foo.debug\\;resolution:=optional}

This is because the bnd file is a Java properties file and the properties file processing will remove one of the backslashes.

Body:
I wanted to import some packages in all bundles with resolution optional using build.bnd

I have tried below code but it's showing only package name in imports, not resolution optional

common-imports:${if;${debug};com.example.foo.debug\;resolution:=optional}
Import-Package: \
${common-imports}, \
*

It should show

    Import:com.example.foo.debug;resolution:=optional but its showing
    Import:com.example.foo.debug


问:
sap.m.PlanningCalendar - How to display hour in 24-hour format?
I am using a planning calendar where I am displaying the appointments. I am showing the calendar from 7AM to 5PM. But I want the Hour format to be in 24-hour format, like after 12PM it should be 13, 14, 15.. likewise.</p>

答:
That doesn't work for us, my Fiori launchpad is set to 24hr as well as in SU01 backend system, but the Planning Calendar still shows 12PM.

Any other suggestions?


问:
Convert char array to single int?
Anyone know how to convert a char array to a single int? </p>

```<code>char hello[5];
hello = "12345";

int myNumber = convert_char_to_int(hello);
Printf("My number is: %d", myNumber);
</code>```

答:
I use :</p>

```<code>int convertToInt(char a[1000]){
    int i = 0;
    int num = 0;
    while (a[i] != 0)
    {
        num =  (a[i] - '0')  + (num * 10);
        i++;
    }
    return num;;
}
</code>```

Title: Convert char array to single int?

Body:
Anyone know how to convert a char array to a single int?

char hello[5];
hello = "12345";

int myNumber = convert_char_to_int(hello);
Printf("My number is: %d", myNumber);

Body:
I use :

int convertToInt(char a[1000]){
    int i = 0;
    int num = 0;
    while (a[i] != 0)
    {
        num =  (a[i] - '0')  + (num * 10);
        i++;
    }
    return num;;
}


问:
String added to start of current working directory instead of the end
Im getting the current working directory and adding more strings on top of it, when i add a backslash to the path, it adds it to the start of the stiring.

How do i stop this from happening?

```<code>print(os.getcwd() + "\aaaa\aaaa")

This prints # aaaa\aaaa\Desktop\Test\Tails

instead of #C:\Users\Rick\Desktop\technical-test\aaaa\aaaa
</code>```

Any help would be appreciated

答:
when dealing with paths in python your probably want to use os.path and not manipulate strings by yourself.
to add parts to the path use os.path.join()

try:

import os

current_path = os.getcwd()

new_path = os.path.join(current_path, "aaa", "bbb", "ccc")

print(new_path)

```

Body:
Im getting the current working directory and adding more strings on top of it, when i add a backslash to the path, it adds it to the start of the stiring.

How do i stop this from happening?

print(os.getcwd() + "\aaaa\aaaa")

This prints # aaaa\aaaa\Desktop\Test\Tails

instead of #C:\Users\Rick\Desktop\technical-test\aaaa\aaaa

Any help would be appreciated


问:
Error filling in empty Numpy array with `np.datetime64` objects
I've always been confused about the interaction between Python's standard library datetime objects and Numpy's datetime objects. The following code gives an error, which baffles me.

```<code>from datetime import datetime
import numpy as np

b = np.empty((1,), dtype=np.datetime64)
now = datetime.now()
b[0] = np.datetime64(now)
</code>```

This gives the following error:

```<code>TypeError: Cannot cast NumPy timedelta64 scalar from metadata [us] to  according to the rule 'same_kind'
</code>```

What am I doing wrong here?

答:
np.datetime64 is a class, whereas np.dtype('datetime64[us]') is a NumPy dtype:

```<code>import numpy as np
print(type(np.datetime64))
# <class 'type'>

print(type(np.dtype('datetime64[us]')))
# <class 'numpy.dtype'>
</code>```

Specify the dtype of b using the NumPy dtype, not the class:

```<code>from datetime import datetime
import numpy as np

b = np.empty((1,), dtype='datetime64[us]')
# b = np.empty((1,), dtype=np.dtype('datetime64[us]'))  # also works
now = datetime.now()
b[0] = np.datetime64(now)
print(b)
# ['2019-05-30T08:55:43.111008']
</code>```

Note that datetime64[us] is just one of a number of possible dtypes. For
instance, there are datetime64[ns], datetime64[ms], datetime64[s],
datetime64[D], datetime64[Y] dtypes, depending on the desired time
resolution.

datetime.dateitem.now() returns a a datetime with microsecond resolution,
so I chose datetime64[us] to match.

Body:
I've always been confused about the interaction between Python's standard library datetime objects and Numpy's datetime objects. The following code gives an error, which baffles me.

from datetime import datetime
import numpy as np

b = np.empty((1,), dtype=np.datetime64)
now = datetime.now()
b[0] = np.datetime64(now)

This gives the following error:

TypeError: Cannot cast NumPy timedelta64 scalar from metadata [us] to  according to the rule 'same_kind'

What am I doing wrong here?

Body:
np.datetime64 is a class, whereas np.dtype('datetime64[us]') is a NumPy dtype:

import numpy as np
print(type(np.datetime64))
# <class 'type'>

print(type(np.dtype('datetime64[us]')))
# <class 'numpy.dtype'>

Specify the dtype of b using the NumPy dtype, not the class:

from datetime import datetime
import numpy as np

b = np.empty((1,), dtype='datetime64[us]')
# b = np.empty((1,), dtype=np.dtype('datetime64[us]'))  # also works
now = datetime.now()
b[0] = np.datetime64(now)
print(b)
# ['2019-05-30T08:55:43.111008']

Note that datetime64[us] is just one of a number of possible dtypes. For
instance, there are datetime64[ns], datetime64[ms], datetime64[s],
datetime64[D], datetime64[Y] dtypes, depending on the desired time
resolution.

datetime.dateitem.now() returns a a datetime with microsecond resolution,
so I chose datetime64[us] to match.


问:
Why is the android emulator starting but then dying immediately?
I've installed Android Studio on my Ubuntu 16.04

I've set up a device using the AVD device manager

When I try to start the device the emulator flashes very quickly and then disappears.

I tried several different versions but for all of them the emulator window flashes for a fraction of a second then disappears.

How can I get the emulator to work?
Where are logs that will show what problem I am having?

答: Or you can select cold boot now from AVD drop down menu. It works fine.</p>


问:
How do you get Android Intent for showing "QuickContact"?
I'm working on my first Android application, and am trying to get an Intent for the QuickContact panel. Somewhere I had found mention of the method QuickContact.getQuickContactIntent(...). But when I try to use it, it tells me that it is undefined for the type QuickContact. After googling for several days, I find a bunch of pages using it in code, but nothing about how to use it or what imports are necessary or anything. So how do I use this method? I need to get the Intent used to launch the panel.

I've included the following import in my file:

```<code>import android.provider.ContactsContract.QuickContact;
</code>```

Alternatively, what other method could I use to get a QuickContact intent for passing to something expecting an intent? I am looking to pass the intent back in the cursor for a LiveFolder provider.

I am developing against the Google APIs Level 9, platform number 2.3.1.
Thanks!

答: Use the widget onUpdate() and onRecieve() events to communicate with the RemoteView like explained here. The documented source of that discussion is here if you want some reading material. I can't begin to assume why you're trying to get the intent, or how you initially created the ContactContract.QuickContact object you're referring to. Little more information might get a few more views, and probably alternate solutions; so if this doesn't help consider posting a bit more info.

Body:
I'm working on my first Android application, and am trying to get an Intent for the QuickContact panel. Somewhere I had found mention of the method QuickContact.getQuickContactIntent(...). But when I try to use it, it tells me that it is undefined for the type QuickContact. After googling for several days, I find a bunch of pages using it in code, but nothing about how to use it or what imports are necessary or anything. So how do I use this method? I need to get the Intent used to launch the panel.

I've included the following import in my file:

import android.provider.ContactsContract.QuickContact;

Alternatively, what other method could I use to get a QuickContact intent for passing to something expecting an intent? I am looking to pass the intent back in the cursor for a LiveFolder provider.

I am developing against the Google APIs Level 9, platform number 2.3.1.
Thanks!


问:
how to make a 2 level array to asimple array
I have an array like this:

```<code>[12601] => Array (
        ['docUpload'] => html dom.txt
)

[12602] => Array (
        ['docUpload'] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
)
[12603] => Array (
        ['docUpload'] =>
)
</code>```

How to get it like this:

```<code>12601 => html dom.txt
12602 => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
</code>```

can you help me please?

答:
Use  array_column() to get the values, then combine them with array_combine()  and array_keys().

$values = array_column($array, 'docUpload');
$newArray = array_combine(array_keys($array), $values);
```

Live demo at https://3v4l.org/lG4KO

Body:
I have an array like this:

[12601] => Array (
        ['docUpload'] => html dom.txt
)

[12602] => Array (
        ['docUpload'] => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt
)
[12603] => Array (
        ['docUpload'] =>
)

How to get it like this:

12601 => html dom.txt
12602 => PYTHON AND DJANGO ARE HUGE IN FINTECH.txt

can you help me please?

Body:
Use  array_column() to get the values, then combine them with array_combine()  and array_keys().

$values = array_column($array, 'docUpload');
$newArray = array_combine(array_keys($array), $values);

Live demo at https://3v4l.org/lG4KO


问:
Django Attribute error 'datetime.timedelta' object has no attribute 'decode'
I am using a simple generic view of django-rest-framework that is working fine on my local machine but gives an attribute error in the server. This is the error:

```<code>AttributeError at /api/getcarts/ 'datetime.timedelta' object has no attribute 'decode'
</code>```

Here is the class:

```<code>class GetCarts(generics.ListAPIView):
     serializer_class = CartSerializer
     queryset = TblCarts.objects.all()
</code>```

The strange thing is, all the other GET and POST APIs are working fine. Here is the TblCart:

```<code>class TblCarts(models.Model):
     price = models.IntegerField()
     location = models.CharField(max_length=500)
     location_coordinate = models.CharField(max_length=100, default=0)
     number = models.CharField(max_length=50)
     promo_code = models.CharField(max_length=50, default=0)
     receipt = models.CharField(max_length=100)
     order_receive_date = models.DateField(auto_now_add=True)
     order_receive_time = models.TimeField(auto_now_add=True)
     order_dispatch_time = models.TimeField(default='00:00', max_length=100)
     order_delivered_time = models.TimeField(default='00:00', max_length=100)
     order_status = models.CharField(max_length=100, default=1)

    class Meta:
         managed = False
         db_table = 'tbl_carts'
</code>```

Here is the serializer:

```<code>class CartSerializer(serializers.ModelSerializer):
    class Meta:
         model = TblCarts
         fields = '__all__'
</code>```

I cannot figure out what the problem is. The versions are: python 3.6.5, Django 2.1, djangorestframework 3.8.2.

The error traceback:

```<code>File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
  483.             response = self.handle_exception(exc)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
  443.             self.raise_uncaught_exception(exc)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
  480.             response = handler(request, *args, **kwargs)

File "/var/www/khaanpin/khanpinuser/api/views.py" in get
  51.         return Response({'error': 'false', 'data': CartSerializer(orders, many=True).data})

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/rest_framework/serializers.py" in data
  765.         ret = super(ListSerializer, self).data

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/rest_framework/serializers.py" in data
  262.                 self._data = self.to_representation(self.instance)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/rest_framework/serializers.py" in to_representation
  683.             self.child.to_representation(item) for item in iterable

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/db/models/query.py" in __iter__
  268.         self._fetch_all()

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/db/models/query.py" in _fetch_all
  1183.             self._result_cache = list(self._iterable_class(self))

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/db/models/query.py" in __iter__
  63.         for row in compiler.results_iter(results):

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in cursor_iter
  1462.         for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel):

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in <lambda>
  1462.         for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel):

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/db/utils.py" in inner
  96.                 return func(*args, **kwargs)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/mysql/connector/cursor_cext.py" in fetchmany
  510.             rows.extend(self._cnx.get_rows(size)[0])

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/mysql/connector/connection_cext.py" in get_rows
  280.                                                               row[i])

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/mysql/connector/conversion.py" in to_python
  205.             return self._cache_field_types[vtype[1]](value, vtype)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/mysql/connector/django/base.py" in _TIME_to_python
  106.         return dateparse.parse_time(value.decode('utf-8'))

Exception Type: AttributeError at /api/getcarts/
Exception Value: 'datetime.timedelta' object has no attribute 'decode'
Request information:
USER: 9999999999

GET: No GET data

POST: No POST data

FILES: No FILES data

COOKIES: No cookie data
</code>```

答: If you use 'mysql-connector-python' Try using version 8.0.5 instead. I had the same issue when using the newest version of 'mysql-connector-python'.</p>

Body:
I am using a simple generic view of django-rest-framework that is working fine on my local machine but gives an attribute error in the server. This is the error:

AttributeError at /api/getcarts/ 'datetime.timedelta' object has no attribute 'decode'

Here is the class:

class GetCarts(generics.ListAPIView):
     serializer_class = CartSerializer
     queryset = TblCarts.objects.all()

The strange thing is, all the other GET and POST APIs are working fine. Here is the TblCart:

class TblCarts(models.Model):
     price = models.IntegerField()
     location = models.CharField(max_length=500)
     location_coordinate = models.CharField(max_length=100, default=0)
     number = models.CharField(max_length=50)
     promo_code = models.CharField(max_length=50, default=0)
     receipt = models.CharField(max_length=100)
     order_receive_date = models.DateField(auto_now_add=True)
     order_receive_time = models.TimeField(auto_now_add=True)
     order_dispatch_time = models.TimeField(default='00:00', max_length=100)
     order_delivered_time = models.TimeField(default='00:00', max_length=100)
     order_status = models.CharField(max_length=100, default=1)

    class Meta:
         managed = False
         db_table = 'tbl_carts'

Here is the serializer:

class CartSerializer(serializers.ModelSerializer):
    class Meta:
         model = TblCarts
         fields = '__all__'

I cannot figure out what the problem is. The versions are: python 3.6.5, Django 2.1, djangorestframework 3.8.2.

The error traceback:

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
  483.             response = self.handle_exception(exc)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
  443.             self.raise_uncaught_exception(exc)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
  480.             response = handler(request, *args, **kwargs)

File "/var/www/khaanpin/khanpinuser/api/views.py" in get
  51.         return Response({'error': 'false', 'data': CartSerializer(orders, many=True).data})

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/rest_framework/serializers.py" in data
  765.         ret = super(ListSerializer, self).data

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/rest_framework/serializers.py" in data
  262.                 self._data = self.to_representation(self.instance)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/rest_framework/serializers.py" in to_representation
  683.             self.child.to_representation(item) for item in iterable

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/db/models/query.py" in __iter__
  268.         self._fetch_all()

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/db/models/query.py" in _fetch_all
  1183.             self._result_cache = list(self._iterable_class(self))

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/db/models/query.py" in __iter__
  63.         for row in compiler.results_iter(results):

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in cursor_iter
  1462.         for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel):

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in <lambda>
  1462.         for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel):

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/django/db/utils.py" in inner
  96.                 return func(*args, **kwargs)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/mysql/connector/cursor_cext.py" in fetchmany
  510.             rows.extend(self._cnx.get_rows(size)[0])

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/mysql/connector/connection_cext.py" in get_rows
  280.                                                               row[i])

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/mysql/connector/conversion.py" in to_python
  205.             return self._cache_field_types[vtype[1]](value, vtype)

File "/var/www/khaanpin/khanpinuser/venv3/lib/python3.6/site-packages/mysql/connector/django/base.py" in _TIME_to_python
  106.         return dateparse.parse_time(value.decode('utf-8'))

Exception Type: AttributeError at /api/getcarts/
Exception Value: 'datetime.timedelta' object has no attribute 'decode'
Request information:
USER: 9999999999

GET: No GET data

POST: No POST data

FILES: No FILES data

COOKIES: No cookie data


问:
Hide flexbox child and make visible again
I have a simple flexbox scenario - parent, few items etc.

I need to selectively hide one of the child items, which I do using display: none.

However, at a later point, I need to reinstate the item visibility - but as what? I It's not a flex, and I don't think it's an inline-flex, so what is it?

I can't use display: unset as it only seems to be moderately supported. Any ideas?

.container {
  margin: 40px;
}

.flexbox-container {
  display: flex;
}

.flexbox-item {
  flex: 1 0 0;
  height: 40px;
  background-color: aqua;
}

.flexbox-item:not(:first-child) {
  margin-left: 20px;
}

.hide-item {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="flexbox-container">
    <div class="flexbox-item">child</div>
    <div class="flexbox-item hide-item">child</div>
    <div class="flexbox-item">child</div>
  </div>
</div></code>```

答:
Just reset it back to display:block

.container {
  margin: 40px;
}

.flexbox-container {
  display: flex;
}

.flexbox-item {
  flex: 1 0 0;
  height: 40px;
  background-color: aqua;
}

.flexbox-item:not(:first-child) {
  margin-left: 20px;
}

input:checked+.flexbox-container>.hide-item {
  display: block;
}

.hide-item {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <label>Toggle This</label>
  <input type="checkbox">
  <div class="flexbox-container">
    <div class="flexbox-item">child</div>
    <div class="flexbox-item hide-item">child</div>
    <div class="flexbox-item">child</div>
  </div>
</div></code>```

Body:
I have a simple flexbox scenario - parent, few items etc.

I need to selectively hide one of the child items, which I do using display: none.

However, at a later point, I need to reinstate the item visibility - but as what? I It's not a flex, and I don't think it's an inline-flex, so what is it?

I can't use display: unset as it only seems to be moderately supported. Any ideas?

.container {
  margin: 40px;
}

.flexbox-container {
  display: flex;
}

.flexbox-item {
  flex: 1 0 0;
  height: 40px;
  background-color: aqua;
}

.flexbox-item:not(:first-child) {
  margin-left: 20px;
}

.hide-item {
  display: none;
}

child

child

child

Body:
Just reset it back to display:block

.container {
  margin: 40px;
}

.flexbox-container {
  display: flex;
}

.flexbox-item {
  flex: 1 0 0;
  height: 40px;
  background-color: aqua;
}

.flexbox-item:not(:first-child) {
  margin-left: 20px;
}

input:checked+.flexbox-container>.hide-item {
  display: block;
}

.hide-item {
  display: none;
}

<div class="container">
  <label>Toggle This</label>
  <input type="checkbox">
  <div class="flexbox-container">
    <div class="flexbox-item">child</div>
    <div class="flexbox-item hide-item">child</div>
    <div class="flexbox-item">child</div>
  </div>
</div>


问:
Get notified when object in third party S3 bucket gets updated
I need to monitor a file on a third party public s3 bucket and would like to get notified when the file gets updated(replaced). Please note that the third party is not going to implement a Lambda trigger for me so S3 Lambda event triggers etc won't help. Any solution other than polling?

Like i said the bucket is a third party bucket who is unlikely to make any modifications on their part to deliver created object events to a lambda or queue.

答:
If the bucket owner is unwilling to do anything (eg configure Amazon S3 Events), then there is no way to be automatically notified when an object is added/updated.

This is good — would you want other people to be able to monitor your buckets like that? Presumably not.

If the bucket is publicly accessible, you should be able to call HeadObject() on the file at regular intervals to determine whether it has changed. The Create Date and eTag should be sufficient to detect a change.


问:
Textual geolocation
I need to geolocate a series of entries in a single-country development projects database. I have a brief synopsis for each project within which I would like to identify municipalities (or even larger political entities) to allow me to geolocate each project later on with the GoogleMaps API.

I am trying to extract the geographic information without using natural language processing. I am not keen to use NLP because the project are located in small villages, whose name I can obtain from other sources.

I was considering splitting the text on spaces, and trying to find matches using a Python vocabulary in which the value is the name of the village and the key is the name of the village split at spaces.

Example:

"Project X has been built in The Hague, The Netherlands".
Would give me: "The Hague"

答:
Try https://geocode.xyz/textscan

https://geocode.xyz/?scantext=Project%20X%20has%20been%20built%20in%20The%20Hague,%20The%20Netherlands&geoit=XML

```<code><geodata>
<match>
<location>The Hague,NL</location>
<latt>52.06805</latt>
<longt>4.29647</longt>
<confidence>0.2</confidence>
<MentionIndices>32</MentionIndices>
<matchtype>locality</matchtype>
</match>
</geodata>
</code>```

Title: Textual geolocation

Body:
Try https://geocode.xyz/textscan

https://geocode.xyz/?scantext=Project%20X%20has%20been%20built%20in%20The%20Hague,%20The%20Netherlands&geoit=XML

<geodata>
<match>
<location>The Hague,NL</location>
<latt>52.06805</latt>
<longt>4.29647</longt>
<confidence>0.2</confidence>
<MentionIndices>32</MentionIndices>
<matchtype>locality</matchtype>
</match>
</geodata>


问:
Django: using user.get_profile()
I have a very newbie question on using django auth. Here is my model:

```<code>class UserProfile(models.Model):
    """ Main user profile used on a website """
    user            = models.ForeignKey(User, unique=True) # reference to built in django user
    display_name    = models.CharField(max_length=100, blank=True)
    # and several more fields

class Post(models.Model):
    """ Blog entry """
    author          = models.ForeignKey(User)
    tags            = models.ManyToManyField(Tag)
    title           = models.CharField(max_length=255)
    text            = models.TextField()
</code>```

Trouble comes, when I want to output a list of posts:

```<code>#view
posts = Post.objects.all()
#template
{% for post in posts %}
    {{ post.title }} by {{ post.author.get_profile.display_name }}
{% endfor %}
</code>```

For 100 posts this gives 101 queries, because every get_profile() goes to database to get the display_name field.

Is there a way to fix this? Can I use select_related(), or something? Or should I be referencing UserProfile istead of User in my Post model?

答: You should be able to use a OneToOneField(User, related_name='profile') in your UserProfile model and then do Post.objects.select_related('author__profile').

Title: Django: using user.get_profile()

Body:
I have a very newbie question on using django auth. Here is my model:

class UserProfile(models.Model):
    """ Main user profile used on a website """
    user            = models.ForeignKey(User, unique=True) # reference to built in django user
    display_name    = models.CharField(max_length=100, blank=True)
    # and several more fields

class Post(models.Model):
    """ Blog entry """
    author          = models.ForeignKey(User)
    tags            = models.ManyToManyField(Tag)
    title           = models.CharField(max_length=255)
    text            = models.TextField()

Trouble comes, when I want to output a list of posts:

#view
posts = Post.objects.all()
#template
{% for post in posts %}
    {{ post.title }} by {{ post.author.get_profile.display_name }}
{% endfor %}

For 100 posts this gives 101 queries, because every get_profile() goes to database to get the display_name field.

Is there a way to fix this? Can I use select_related(), or something? Or should I be referencing UserProfile istead of User in my Post model?


问:
async function - await not waiting for promise
I'm trying to learn async-await. In this code -

```<code>const myFun = () => {
    let state = false;

    setTimeout(() => {state = true}, 2000);

    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if(state) {
                resolve('State is true');
            } else {
                reject('State is false');
            }
        }, 3000);
    });
}

const getResult = async () => {
    return await myFun();
}

console.log(getResult());
</code>```

why am I getting output as -

```<code>Promise { <pending> }
</code>```

Instead of some value? Shouldn't the getResult() function wait for myFun() function resolve it's promise value?

答:
What you need to understand is that async/await does not make your code run synchronously, but let's you write it as if it is:

In short: The function with async in front of it is literally executed asynchronously, hence the keyword "async". And the "await" keyword wil make that line that uses it inside this async function wait for a promise during its execution. So although the line waits, the whole function is still run asynchronously, unless the caller of that function also 'awaits'...

More elaborately explained: When you put async in front of a function, what is actually does is make it return a promise with whatever that function returns inside it. The function runs asynchronously and when the return statement is executed the promise resolves the returning value.

Meaning, in your code:

```<code>const getResult = async () => {
    return await myFun();
}
</code>```

The function "getResult()" will return a Promise which will resolve once it has finished executing. So the lines inside the getResult() function are run asynchronously, unless you tell the function calling getResult() to 'await' for it as well.  Inside the getResult() function you may say it must await the result, which makes the execution of getResult() wait for it to resolve the promise, but the caller of getResult() will not wait unless you also tell the caller to 'await'.

So a solution would be calling either:

```<code>getResult().then(result=>{console.log(result)})
</code>```

Or when using in another function you can simply use 'await' again

```<code>async function callingFunction(){
    console.log(await(getResult());
}
</code>```

Body:
I'm trying to learn async-await. In this code -

const myFun = () => {
    let state = false;

    setTimeout(() => {state = true}, 2000);

    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if(state) {
                resolve('State is true');
            } else {
                reject('State is false');
            }
        }, 3000);
    });
}

const getResult = async () => {
    return await myFun();
}

console.log(getResult());

why am I getting output as -

Promise { <pending> }

Instead of some value? Shouldn't the getResult() function wait for myFun() function resolve it's promise value?

Body:
What you need to understand is that async/await does not make your code run synchronously, but let's you write it as if it is:

In short: The function with async in front of it is literally executed asynchronously, hence the keyword "async". And the "await" keyword wil make that line that uses it inside this async function wait for a promise during its execution. So although the line waits, the whole function is still run asynchronously, unless the caller of that function also 'awaits'...

More elaborately explained: When you put async in front of a function, what is actually does is make it return a promise with whatever that function returns inside it. The function runs asynchronously and when the return statement is executed the promise resolves the returning value.

Meaning, in your code:

const getResult = async () => {
    return await myFun();
}

The function "getResult()" will return a Promise which will resolve once it has finished executing. So the lines inside the getResult() function are run asynchronously, unless you tell the function calling getResult() to 'await' for it as well.  Inside the getResult() function you may say it must await the result, which makes the execution of getResult() wait for it to resolve the promise, but the caller of getResult() will not wait unless you also tell the caller to 'await'.

So a solution would be calling either:

getResult().then(result=>{console.log(result)})

Or when using in another function you can simply use 'await' again

async function callingFunction(){
    console.log(await(getResult());
}


问:
Split a string that holds characters in different sizes
I have an input string that holds characters in different sizes, for example const char * input = "aadđ€€¢¢".
The strlen gave result 15, which mean while 'aad' only took 3 bytes, the other special characters took 2 bytes or more each.

How can I cut characters that fit into 6 bytes from the start of that string? Which mean in this case only 'aadđ' will be taken because aadđ€ would occupy 8 bytes.

I tried normal split character methods but none worked so far. Edit: Because a wide character might get split in the middle and therefore I will get some garbage or a different character instead.

答:
strlen counts bytes not characters.
To step through the string characterwise, you might try mblen, which looks at the next character in a string. If the string's encoding is not UTF-8, you must adjust the call to setlocale accordingly

```<code>std::setlocale(LC_ALL, "en_US.utf8");
const char *input = "aadđ€€¢¢";
int clen;
mblen(0, 0);
for (const char *p = input; *p != 0; p += clen) {
    clen = mblen(p, 4);
    std::cout << p << ", clen=" << clen << '\n';
}
</code>```

To get exactly 6 bytes might prove difficult, because this might stop midway in a multi-byte character

```<code>int len = 0, clen;
mblen(0, 0);
for (const char *p = input; *p != 0 && len < 6; p += clen, len += clen) {
    clen = mblen(p, 4);
}

char buf[10];
strncpy(buf, input, len);
buf[len] = 0;
</code>```

This would stop as soon as 6 or more bytes are reached.

To get at most 6 bytes, subtract the last character before copying, if there's an overrun

```<code>if (len > 6)
    len -= clen;
</code>```

Body:
strlen counts bytes not characters.
To step through the string characterwise, you might try mblen, which looks at the next character in a string. If the string's encoding is not UTF-8, you must adjust the call to setlocale accordingly

std::setlocale(LC_ALL, "en_US.utf8");
const char *input = "aadđ€€¢¢";
int clen;
mblen(0, 0);
for (const char *p = input; *p != 0; p += clen) {
    clen = mblen(p, 4);
    std::cout << p << ", clen=" << clen << '\n';
}

To get exactly 6 bytes might prove difficult, because this might stop midway in a multi-byte character

int len = 0, clen;
mblen(0, 0);
for (const char *p = input; *p != 0 && len < 6; p += clen, len += clen) {
    clen = mblen(p, 4);
}

char buf[10];
strncpy(buf, input, len);
buf[len] = 0;

This would stop as soon as 6 or more bytes are reached.

To get at most 6 bytes, subtract the last character before copying, if there's an overrun

if (len > 6)
    len -= clen;


问:
How to find a consistent hash of a tarball
How do you create a tarball so that its md5 or sha512 hash will be deterministic?

I'm currently creating a tarball of a directory of source code files by running tar --exclude-vcs --create --verbose --dereference --gzip --file mycode.tgz *, and I'd like to record its hash so I can use it as a fingerprint for detecting changes in the future.

However, I've noticed that if I create duplicate tarballs without changing any files, running the Python hashlib.sha512(open('mycode.tgz').read()).hexdigest() on each archive returns a different hash.

Is this because tar's compression algorithm is not deterministic? If so, how can I efficiently archive a large collection of files in such a way that I can calculate a consistent hash to detect changes?

答:
Gnu tar can set the timestamps for consistent hashing.

```<code>tar --sort=name --owner=root:0 --group=root:0 --mtime='UTC 2019-01-01' ...
</code>```

Credits: https://stackoverflow.com/a/54908072

Body:
Gnu tar can set the timestamps for consistent hashing.

tar --sort=name --owner=root:0 --group=root:0 --mtime='UTC 2019-01-01' ...

Credits: https://stackoverflow.com/a/54908072


问:
How to run commands in parallel in bash?
This has been asked before and there are a lot of answers but my needs are bit more specific:

The processes I need to run are all long-running processes that won't end (normally).

I don't want to just run them on background since I need to see their output.

If any of the processes exits I want the rest to be automatically killed as well.

If I use Ctrl+C or other signal on the main command used to run them, I want to kill all the processes.

For example using & + wait does not satisfy the last point. GNU parallel seems quite complicated and is possibly able to do this but I can't find a good example how to use it.

答:
you can use xargs -P0

-P max-procs, --max-procs=max-procs
              Run up to max-procs processes at a time; the default is 1.  If max-procs is 0, xargs will run as many processes as possible at a time.  Use the  -n  option  or
              the  -L  option  with -P; otherwise chances are that only one exec will be done.  While xargs is running, you can send its process a SIGUSR1 signal to increase
              the number of commands to run simultaneously, or a SIGUSR2 to decrease the number.  You cannot increase it above  an  implementation-defined  limit  (which  is
              shown with --show-limits).  You cannot decrease it below 1.  xargs never terminates its commands; when asked to decrease, it merely waits for more than one ex‐
              isting command to terminate before starting another.


问:
Spring data mongo - Get sum of array of object
I have the following document:

```<code>{
   pmv: {
        budgets: [
           {
              amount: 10
           },
           {
              amount: 20
           }
         ]
     }
}
</code>```

and I need to sum the amount field from every object in budgets. But it's also possible that the budget object doesn't exist so I need to check that.

How could I do this? I've seen many questions but with projections, I just need a integer number which in this case would be 30.

How can I do it?

Thanks.

EDIT 1 FOR PUNIT

This is the code I tried but its giving me and empty aray

```<code>AggregationOperation filter = match(Criteria.where("pmv.budgets").exists(true).not().size(0));
            AggregationOperation unwind = unwind("pmv.budgets");
            AggregationOperation sum = group().sum("budgets").as("amount");

            Aggregation aggregation = newAggregation(filter, unwind, sum);

            mongoTemplate.aggregate(aggregation,"Iniciativas",String.class);

            AggregationResults<String> aggregationa = mongoTemplate.aggregate(aggregation,"Iniciativas",String.class);

            List<String> results = aggregationa.getMappedResults();
</code>```

答:
You can do this with aggregation pipeline

```<code>db.COLLECTION_NAME.aggregate([
  {"pmv.budgets":{$exists:true,$not:{$size:0}}},
  {$unwind:"$pmv.budgets"},
  {amount:{$sum:"$pmv.budgets"}}
]);
</code>```

This pipeline contains three queries:

get document having non-null and non-empty budgets

$unwind basically open the array and create one document for each array element. e.g. if one document of budgets has 3 elements then it will create 3 document and fill budgets property from each of the array element. You can read more about it here

sum all the budgets property using $sum operator

You can read more about aggregation pipeline here

EDIT: as per comments, adding code for java as well.

```<code>AggregationOperation filter = match(Criteria.where("pmv.budgets").exists(true).not().size(0));
AggregationOperation unwind = unwind("pmv.budgets");
AggregationOperation sum = group().sum("pmv.budgets").as("amount");

Aggregation aggregation = newAggregation(filter, unwind, sum);

mongoTemplate.aggregate(aggregation,COLLECTION_NAME,Output.class);
</code>```

You can do this in more inline way as well but I wrote it like this so that it will be easy to understand.

I hope this answer your question.

Body:
I have the following document:

{
   pmv: {
        budgets: [
           {
              amount: 10
           },
           {
              amount: 20
           }
         ]
     }
}

and I need to sum the amount field from every object in budgets. But it's also possible that the budget object doesn't exist so I need to check that.

How could I do this? I've seen many questions but with projections, I just need a integer number which in this case would be 30.

How can I do it?

Thanks.

EDIT 1 FOR PUNIT

This is the code I tried but its giving me and empty aray

AggregationOperation filter = match(Criteria.where("pmv.budgets").exists(true).not().size(0));
            AggregationOperation unwind = unwind("pmv.budgets");
            AggregationOperation sum = group().sum("budgets").as("amount");

            Aggregation aggregation = newAggregation(filter, unwind, sum);

            mongoTemplate.aggregate(aggregation,"Iniciativas",String.class);

            AggregationResults<String> aggregationa = mongoTemplate.aggregate(aggregation,"Iniciativas",String.class);

            List<String> results = aggregationa.getMappedResults();

Body:
You can do this with aggregation pipeline

db.COLLECTION_NAME.aggregate([
  {"pmv.budgets":{$exists:true,$not:{$size:0}}},
  {$unwind:"$pmv.budgets"},
  {amount:{$sum:"$pmv.budgets"}}
]);

This pipeline contains three queries:

get document having non-null and non-empty budgets

$unwind basically open the array and create one document for each array element. e.g. if one document of budgets has 3 elements then it will create 3 document and fill budgets property from each of the array element. You can read more about it here

sum all the budgets property using $sum operator

You can read more about aggregation pipeline here

EDIT: as per comments, adding code for java as well.

AggregationOperation filter = match(Criteria.where("pmv.budgets").exists(true).not().size(0));
AggregationOperation unwind = unwind("pmv.budgets");
AggregationOperation sum = group().sum("pmv.budgets").as("amount");

Aggregation aggregation = newAggregation(filter, unwind, sum);

mongoTemplate.aggregate(aggregation,COLLECTION_NAME,Output.class);

You can do this in more inline way as well but I wrote it like this so that it will be easy to understand.

I hope this answer your question.


问:
Run all Python scripts in a folder - from Python
How can I write a Python program that runs all Python scripts in the current folder? The program should run in Linux, Windows and any other OS in which python  is installed.

Here is what I tried:

```<code>import glob, importlib

for file in glob.iglob("*.py"):
    importlib.import_module(file)
</code>```

This returns an error: ModuleNotFoundError: No module named 'agents.py'; 'agents' is not a package
(here agents.py is one of the files in the folder; it is indeed not a package and not intended to be a package - it is just a script).

If I change the last line to:

```<code>    importlib.import_module(file.replace(".py",""))
</code>```

then I get no error, but also the scripts do not run.

Another attempt:

```<code>import glob, os

for file in glob.iglob("*.py"):
    os.system(file)
</code>```

This does not work on Windows - it tries to open each file in Notepad.

答:
Maybe you can make use of the subprocess module; this question shows a few options.

Your code could look like this:

```<code>import os
import subprocess

base_path = os.getcwd()
print('base_path', base_path)

# TODO: this might need to be 'python3' in some cases
python_executable = 'python'
print('python_executable', python_executable)

py_file_list = []
for dir_path, _, file_name_list in os.walk(base_path):
    for file_name in file_name_list:
        if file_name.endswith('.csv'):
            # add full path, not just file_name
            py_file_list.append(
                os.path.join(dir_path, file_name))

print('PY files that were found:')
for i, file_path in enumerate(py_file_list):
    print('   {:3d} {}'.format(i, file_path))

    # call script
    subprocess.run([python_executable, file_path])
</code>```

Does that work for you?

Note that the docs for os.system() even suggest using subprocess instead:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function.

Body:
How can I write a Python program that runs all Python scripts in the current folder? The program should run in Linux, Windows and any other OS in which python  is installed.

Here is what I tried:

import glob, importlib

for file in glob.iglob("*.py"):
    importlib.import_module(file)

This returns an error: ModuleNotFoundError: No module named 'agents.py'; 'agents' is not a package
(here agents.py is one of the files in the folder; it is indeed not a package and not intended to be a package - it is just a script).

If I change the last line to:

    importlib.import_module(file.replace(".py",""))

then I get no error, but also the scripts do not run.

Another attempt:

import glob, os

for file in glob.iglob("*.py"):
    os.system(file)

This does not work on Windows - it tries to open each file in Notepad.

Body:
Maybe you can make use of the subprocess module; this question shows a few options.

Your code could look like this:

import os
import subprocess

base_path = os.getcwd()
print('base_path', base_path)

# TODO: this might need to be 'python3' in some cases
python_executable = 'python'
print('python_executable', python_executable)

py_file_list = []
for dir_path, _, file_name_list in os.walk(base_path):
    for file_name in file_name_list:
        if file_name.endswith('.csv'):
            # add full path, not just file_name
            py_file_list.append(
                os.path.join(dir_path, file_name))

print('PY files that were found:')
for i, file_path in enumerate(py_file_list):
    print('   {:3d} {}'.format(i, file_path))

    # call script
    subprocess.run([python_executable, file_path])

Does that work for you?

Note that the docs for os.system() even suggest using subprocess instead:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function.


答:
.flexbox-container has display: flex.

So all the child elements of .flexbox-container are flex-children.

If you add .hide-item to one of those child elements, that element now has display: none.

If you remove .hide-item from that child element it goes back to being a flex-child again.

Example:

```<code>const hiddenChild = document.querySelector('.hide-item');

hiddenChild.classList.remove('hide-item');
</code>```

Title: Hide flexbox child and make visible again

Body:
.flexbox-container has display: flex.

So all the child elements of .flexbox-container are flex-children.

If you add .hide-item to one of those child elements, that element now has display: none.

If you remove .hide-item from that child element it goes back to being a flex-child again.

Example:

const hiddenChild = document.querySelector('.hide-item');

hiddenChild.classList.remove('hide-item');


问:
How to center nodes without using centering force?
I have a force layout graph where user adds nodes dynamically. How can i center all my nodes with a bit distance between, and make them move independently and not around the center.

I have tried removing the d3.forceCenter(width / 2, height / 2) which makes nodes move independently but then it possitions all nodes at (0, 0).

```<code>simulation = d3.forceSimulation()
    .force('charge', d3.forceManyBody().strength(0))
    .force('center', d3.forceCenter(width / 2, height / 2));

</code>```

I want all the nodes to be centered and move independently.

EDIT:

I tried setting cx and cy values but that did not work either.

```<code>  const nodeEnter = nodeElements
    .enter()
    .append('circle')
    .attr('r', 20)
    .attr('fill', 'orange')
    .attr('cx', (d, i) => {
      return (width / 2) + i * 10;
    })
    .attr('cy', (d, i) => {
      return (height / 2) + i * 10;
    })
    .call(dragDrop(simulation))
    .on('click', ({ id }) => handleClick(id));
</code>```

答:
Given what you said in your comment...

If i move 1 node then all other nodes move relatively in order to keep the center of mass at the same spot.

... you already know that forceCenter is the wrong tool for the task, since it will keep the centre of mass.

Therefore, just replace it for forceX and forceY:

```<code>const simulation = d3.forceSimulation()
    .force('centerX', d3.forceX(width / 2))
    .force('centerY', d3.forceY(height / 2));
</code>```

Since you didn't provide enough code here is a general demo:

svg {
  background-color: wheat;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg width="400" height="300"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
  const svg = d3.select('svg');

  const width = svg.attr('width');
  const height = svg.attr('height');

  const data = d3.range(50).map(() => ({}));

  const node = svg.selectAll()
    .data(data)
    .enter()
    .append('circle')
    .attr('r', 10)
    .attr('fill', 'teal')
    .attr('stroke', 'black')
    .call(d3.drag()
      .on('start', dragstarted)
      .on('drag', dragged)
      .on('end', dragended));

  const simulation = d3.forceSimulation()
    .force('charge', d3.forceManyBody().strength(-15))
    .force('centerX', d3.forceX(width / 2))
    .force('centerY', d3.forceY(height / 2));

  simulation
    .nodes(data)
    .on('tick', ticked);

  function ticked() {
    node.attr('cx', d => d.x)
      .attr('cy', d => d.y);
  }

  function dragstarted(d) {
    if (!d3.event.active) simulation.alphaTarget(0.3).restart();
    d.fx = d.x;
    d.fy = d.y;
  }

  function dragged(d) {
    d.fx = d3.event.x;
    d.fy = d3.event.y;
  }

  function dragended(d) {
    if (!d3.event.active) simulation.alphaTarget(0);
    d.fx = null;
    d.fy = null;
  }
</script></code>```

Body:
I have a force layout graph where user adds nodes dynamically. How can i center all my nodes with a bit distance between, and make them move independently and not around the center.

I have tried removing the d3.forceCenter(width / 2, height / 2) which makes nodes move independently but then it possitions all nodes at (0, 0).

simulation = d3.forceSimulation()
    .force('charge', d3.forceManyBody().strength(0))
    .force('center', d3.forceCenter(width / 2, height / 2));

I want all the nodes to be centered and move independently.

EDIT:

I tried setting cx and cy values but that did not work either.

  const nodeEnter = nodeElements
    .enter()
    .append('circle')
    .attr('r', 20)
    .attr('fill', 'orange')
    .attr('cx', (d, i) => {
      return (width / 2) + i * 10;
    })
    .attr('cy', (d, i) => {
      return (height / 2) + i * 10;
    })
    .call(dragDrop(simulation))
    .on('click', ({ id }) => handleClick(id));

Body:
Given what you said in your comment...

If i move 1 node then all other nodes move relatively in order to keep the center of mass at the same spot.

... you already know that forceCenter is the wrong tool for the task, since it will keep the centre of mass.

Therefore, just replace it for forceX and forceY:

const simulation = d3.forceSimulation()
    .force('centerX', d3.forceX(width / 2))
    .force('centerY', d3.forceY(height / 2));

Since you didn't provide enough code here is a general demo:

svg {
  background-color: wheat;
}

<svg width="400" height="300"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
  const svg = d3.select('svg');

  const width = svg.attr('width');
  const height = svg.attr('height');

  const data = d3.range(50).map(() => ({}));

  const node = svg.selectAll()
    .data(data)
    .enter()
    .append('circle')
    .attr('r', 10)
    .attr('fill', 'teal')
    .attr('stroke', 'black')
    .call(d3.drag()
      .on('start', dragstarted)
      .on('drag', dragged)
      .on('end', dragended));

  const simulation = d3.forceSimulation()
    .force('charge', d3.forceManyBody().strength(-15))
    .force('centerX', d3.forceX(width / 2))
    .force('centerY', d3.forceY(height / 2));

  simulation
    .nodes(data)
    .on('tick', ticked);

  function ticked() {
    node.attr('cx', d => d.x)
      .attr('cy', d => d.y);
  }

  function dragstarted(d) {
    if (!d3.event.active) simulation.alphaTarget(0.3).restart();
    d.fx = d.x;
    d.fy = d.y;
  }

  function dragged(d) {
    d.fx = d3.event.x;
    d.fy = d3.event.y;
  }

  function dragended(d) {
    if (!d3.event.active) simulation.alphaTarget(0);
    d.fx = null;
    d.fy = null;
  }
</script>


问:
Question about DateAdd function and information
I'm currently writing some SQL and have come upon an odd issue.

The code i'm using is:

```<code>select * from #table1
where datefield = DATEADD(day, -2, getdate())
</code>```

The issue i'm running into is it won't pull any information like this. If I add a '>' to the '=' it pulls information. If I put an exact date into teh query instead of the 'dateadd' piece it pulls the correct records.

I've tested the date parameters and there are matching records for 4/10/2011. But for some reason it just does not like the '= dateadd' in this instance.

I have also attempted to use the 'current_timestamp' string instead of 'getdate' as well with the same results.

Any suggestions?

答:
getdate() is 1/300 second precise. You are querying for exact times up to (almost) milliseconds.

If your datefield is a DATETIME but without actual time parts, use this:

```<code>SELECT  *
FROM    #table1
WHERE   datefield = DATEADD(day, -2, CAST(getdate() AS DATE))
</code>```

or, better, this:

```<code>SELECT  *
FROM    #table1
WHERE   datefield >= DATEADD(day, -2, CAST(getdate() AS DATE))
        AND datefield < DATEADD(day, -1, CAST(getdate() AS DATE))
</code>```

The latter query will return you all records for the date (even with the time portion set).

Body:
I'm currently writing some SQL and have come upon an odd issue.

The code i'm using is:

select * from #table1
where datefield = DATEADD(day, -2, getdate())

The issue i'm running into is it won't pull any information like this. If I add a '>' to the '=' it pulls information. If I put an exact date into teh query instead of the 'dateadd' piece it pulls the correct records.

I've tested the date parameters and there are matching records for 4/10/2011. But for some reason it just does not like the '= dateadd' in this instance.

I have also attempted to use the 'current_timestamp' string instead of 'getdate' as well with the same results.

Any suggestions?

Body:
getdate() is 1/300 second precise. You are querying for exact times up to (almost) milliseconds.

If your datefield is a DATETIME but without actual time parts, use this:

SELECT  *
FROM    #table1
WHERE   datefield = DATEADD(day, -2, CAST(getdate() AS DATE))

or, better, this:

SELECT  *
FROM    #table1
WHERE   datefield >= DATEADD(day, -2, CAST(getdate() AS DATE))
        AND datefield < DATEADD(day, -1, CAST(getdate() AS DATE))

The latter query will return you all records for the date (even with the time portion set).


问:
Codeigniter 3 - sess_time_to_update AND sess_save_path
So - I look in my 'sess_save_path' folder and I find over 1000 ci_sesson files

Is this necessary for a site that has maybe 3 people logging in every day?

How can I - or should I even try to - reduce the number of these being set?

What is the logic here?

答:
I had the same problem, but it's PHP decision of delete or not the file.

So to get rid of those files more often, I had to add the following code onbeggining of config.php

```<code>if(!headers_sent()){
    ini_set('session.gc_probability', 1);
    ini_set('session.gc_divisor', 100);
}
</code>```

This define a chance of 1% (1/100) to GC delete session files. In a low-traffic web, 1% is fine.

Body:
I had the same problem, but it's PHP decision of delete or not the file.

So to get rid of those files more often, I had to add the following code onbeggining of config.php

if(!headers_sent()){
    ini_set('session.gc_probability', 1);
    ini_set('session.gc_divisor', 100);
}

This define a chance of 1% (1/100) to GC delete session files. In a low-traffic web, 1% is fine.


问:
How do I add a square button with a '+' on it to uinavigationbar?
Like the right button shown in this image.
http://i.stack.imgur.com/D2Q61.jpg
Is it a default button provided by apple?
If yes then how do I add it to the navigationBar?</p>

答:
```<code>UIBarButtonItem *addButton =
  [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
  target:self
  action:@selector(myCallback:)];
self.navigationItem.rightBarButtonItem = addButton;
[addButton release];
</code>```


问:
XSLT output method "xml" not showing html tags as html ouput
In xsltransform scenario, we have xsl with declaration as below:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0" xmlns="http://www.w3.org/TR/REC-html40">
</code>```

```<code> <xsl:output method="xml" />
</code>```

XML has data, but xsl has

 interlined with xslt logic.

Issue: table tags are shown when inspected in Chrome browser but only text in table shown on webpage(html output) but not rendered as table.

When set <xsl:output method="html" />, the entire data comes as text without
 tags.

Any clue around this problem?

答: The XHTML namespace is the one you had in the first version of your question, now you have changed it to use the namespace http://www.w3.org/TR/REC-html40 which is not something any browser will recognize in X(HT)ML as it has no W3C defined meaning. So the table elements in that namespace http://www.w3.org/TR/REC-html40 are just elements in a namespace unknown to the browser and therefore are of course not rendered with HTML semantics. Use the XHTML namespace http://www.w3.org/1999/xhtml for any elements in XML you want to be recognized as XHTML elements.

Body:
In xsltransform scenario, we have xsl with declaration as below:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0" xmlns="http://www.w3.org/TR/REC-html40">

 <xsl:output method="xml" />

XML has data, but xsl has

 interlined with xslt logic.

Issue: table tags are shown when inspected in Chrome browser but only text in table shown on webpage(html output) but not rendered as table.

When set <xsl:output method="html" />, the entire data comes as text without
 tags.

Any clue around this problem?


问:
How can I sort List<Object> CRUD Repository
I'm trying to build simple REST for purchases I need 2 methods. The first method should show all purchases sorted by date. The second one removes all purchases for specified date I made a method to add and to get all purchases. Now I'm stuck.

```<code>@Entity
@Table (name="purchase")
public class Purchase {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "name")
private String name;

@CreationTimestamp
@Temporal(TemporalType.DATE)
@Column(name="createat")
private Date created;

@Column(name="price")
private BigDecimal price;

@Column(name="currency")
private String currency;
@Repository
public interface PurchaseRepository extends JpaRepository<Purchase, Long>
{
}

@Service
public class PurchaseService {

@Autowired
private PurchaseRepository purchaseRepository;

public void addPurchase(Purchase purchase) {
    purchaseRepository.save(purchase);
}

public List<Purchase> getAllPurchase() {

    List<Purchase> purchase = new ArrayList<>();
    purchaseRepository.findAll().forEach(purchase::add);
    return purchase;
}
}

@RestController
public class PurchaseController {

@Autowired
private PurchaseService purchaseService;

@PostMapping("/purchase")
public void addPurchase(@RequestBody Purchase purchase) {
    purchaseService.addPurchase(purchase);
}

@RequestMapping("/purchase")
public List<Purchase> getAllTopics() {
    return purchaseService.getAllPurchase();
}
}
</code>```

What I need:
1. method to sort my List sorted by date
2. method that removes all purchases for specified date

答:
I got it </p>

```<code>long deleteByCreated(Date date);
@Transactional
public long deleteAllByDate(Date date){
    return purchaseRepository.deleteByCreated(date);
}
@RequestMapping(method=RequestMethod.DELETE, value="/purchasess/{date}")
    public long findAllByCreatedBetween(@DateTimeFormat(pattern="yyyy-MM-dd")
@PathVariable  Date date){
        return purchaseService.deleteAllByDate(date);
    }
</code>```

Body:
I'm trying to build simple REST for purchases I need 2 methods. The first method should show all purchases sorted by date. The second one removes all purchases for specified date I made a method to add and to get all purchases. Now I'm stuck.

@Entity
@Table (name="purchase")
public class Purchase {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "name")
private String name;

@CreationTimestamp
@Temporal(TemporalType.DATE)
@Column(name="createat")
private Date created;

@Column(name="price")
private BigDecimal price;

@Column(name="currency")
private String currency;
@Repository
public interface PurchaseRepository extends JpaRepository<Purchase, Long>
{
}

@Service
public class PurchaseService {

@Autowired
private PurchaseRepository purchaseRepository;

public void addPurchase(Purchase purchase) {
    purchaseRepository.save(purchase);
}

public List<Purchase> getAllPurchase() {

    List<Purchase> purchase = new ArrayList<>();
    purchaseRepository.findAll().forEach(purchase::add);
    return purchase;
}
}

@RestController
public class PurchaseController {

@Autowired
private PurchaseService purchaseService;

@PostMapping("/purchase")
public void addPurchase(@RequestBody Purchase purchase) {
    purchaseService.addPurchase(purchase);
}

@RequestMapping("/purchase")
public List<Purchase> getAllTopics() {
    return purchaseService.getAllPurchase();
}
}

What I need:
1. method to sort my List sorted by date
2. method that removes all purchases for specified date

Body:
I got it

long deleteByCreated(Date date);
@Transactional
public long deleteAllByDate(Date date){
    return purchaseRepository.deleteByCreated(date);
}
@RequestMapping(method=RequestMethod.DELETE, value="/purchasess/{date}")
    public long findAllByCreatedBetween(@DateTimeFormat(pattern="yyyy-MM-dd")
@PathVariable  Date date){
        return purchaseService.deleteAllByDate(date);
    }


问:
onSaveInstanceState is called, but savedInstanceState in onCreate method throws null
put some serializable values to savedinstancestate, but savedInstanceState is null. onSaveInstanceState() is called with the log message, Code runs correcctly, but in onCreate method the null pointer is catched after restore the data and the saved state is null. the classes are correct. (serializable) is setted. i can't find the mistake. Thanks for help. </p>

```<code>@override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.mb_activity);
            mBList = new ArrayList<MBClass>();
            mKList = new ArrayList<MKClass>();
            nAList = new ArrayList<AClass>();
            aList = new ArrayList<AClass>();
            try {
                mBList = (ArrayList<MBClass>) savedInstanceState.getSerializable("MBList");
                mKList = (ArrayList<MKClass>) savedInstanceState.getSerializable("MKList");
                aList = (ArrayList<AClass>) savedInstanceState.getSerializable("AList");
                nAList = (ArrayList<AClass>) savedInstanceState.getSerializable("NAList");

                Log.i("MB", "State geschrieben");

            } catch (NullPointerException ne) {
                //ne.printStackTrace();
                Log.i("MB", "State Null");
            }
    }
    @override
    public void onSaveInstanceState(Bundle savedInstanceState) {
                savedInstanceState.putSerializable("MKList", (Serializable) mKList);
                savedInstanceState.putSerializable("MBList", (Serializable) mBList);
                savedInstanceState.putSerializable("NAList", (Serializable) nAList);
                savedInstanceState.putSerializable("AList", (Serializable) aList);
                super.onSaveInstanceState(savedInstanceState);
                Log.i("MB", "onSaveInstanceState");
            }
</code>```

答:
Replacing Serializable with Parcelable worked for me.

```<code>@Parcelize // this annotation is needed in Kotlin. Not Sure about Java
class DataClass implements Parcelable {
   //Data members
}
</code>```

Body:
put some serializable values to savedinstancestate, but savedInstanceState is null. onSaveInstanceState() is called with the log message, Code runs correcctly, but in onCreate method the null pointer is catched after restore the data and the saved state is null. the classes are correct. (serializable) is setted. i can't find the mistake. Thanks for help.

@override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.mb_activity);
            mBList = new ArrayList<MBClass>();
            mKList = new ArrayList<MKClass>();
            nAList = new ArrayList<AClass>();
            aList = new ArrayList<AClass>();
            try {
                mBList = (ArrayList<MBClass>) savedInstanceState.getSerializable("MBList");
                mKList = (ArrayList<MKClass>) savedInstanceState.getSerializable("MKList");
                aList = (ArrayList<AClass>) savedInstanceState.getSerializable("AList");
                nAList = (ArrayList<AClass>) savedInstanceState.getSerializable("NAList");

                Log.i("MB", "State geschrieben");

            } catch (NullPointerException ne) {
                //ne.printStackTrace();
                Log.i("MB", "State Null");
            }
    }
    @override
    public void onSaveInstanceState(Bundle savedInstanceState) {
                savedInstanceState.putSerializable("MKList", (Serializable) mKList);
                savedInstanceState.putSerializable("MBList", (Serializable) mBList);
                savedInstanceState.putSerializable("NAList", (Serializable) nAList);
                savedInstanceState.putSerializable("AList", (Serializable) aList);
                super.onSaveInstanceState(savedInstanceState);
                Log.i("MB", "onSaveInstanceState");
            }

Body:
Replacing Serializable with Parcelable worked for me.

@Parcelize // this annotation is needed in Kotlin. Not Sure about Java
class DataClass implements Parcelable {
   //Data members
}


问:
Text in pdf-file has mysterious spaces
I am trying to export text to a pdf document using the standard PDFdocument class in android. The code creates a pdf but in the text I write to the PDF, it put mysterious spaces half in words.

Tried using the canvas.drawText option and the drawItemn option.
Both give the same result. The problem code-line is almost at the bottom of the sample code below.

```<code>PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(mPageWidth, mPageHeight, pageNr).create();
PdfDocument.Page page = doc.startPage(pageInfo);

Memory memory = mMemoryData.get(pageNr);
Canvas canvas = page.getCanvas();

TextPaint paint = new TextPaint();
paint.setColor(Color.BLACK);

//Header
Yposition = drawItem( canvas,
                      paint,
                      18,
                      true,
                      Xposition,
                      Yposition,
                      memory.getTitle() );

//line
Yposition += 14; //Extra offset to get some space between the text and line
paint.setColor( ContextCompat.getColor(this, R.color.default_Accent) );
canvas.drawLine( Xposition, Yposition, pageInfo.getPageWidth() - Xposition, Yposition, paint );

Yposition += 20;
paint.setColor(Color.BLACK);
paint.setTextSize(10);
// **this is the line that gives the problem**
canvas.drawText(memory.getText(),Xposition, Yposition, paint);

doc.finishPage(page);
</code>```

The result of this action is:

At first sight this looks ok but if you zoom in a bit or better yet copy/past the text into notepad (or something) you get this:

No w le ts try this

In stead of the problem line, I also tried this:

```<code>drawItem( canvas, paint, 10, false, Xposition, Yposition, memory.getText() );
</code>```

This has some benefits especially with bigger text but other that that it gives the same problem.

Does anybody have an idea how to solve this?

答:
Thanks to the tip from Henry the problem is now solved.
For others having the same problem:
i was close with the setting of the font but "Arial" just doesn't work
This also goes for "Typeface.SANS_SERIF". I kept getting these strange spaces in my text.

Now it put it like below.

paint.setTypeface(Typeface.create( Typeface.MONOSPACE, Typeface.NORMAL));

Not the best looking text markup but it does the trick for now.

Title: Text in pdf-file has mysterious spaces

Body:
I am trying to export text to a pdf document using the standard PDFdocument class in android. The code creates a pdf but in the text I write to the PDF, it put mysterious spaces half in words.

Tried using the canvas.drawText option and the drawItemn option.
Both give the same result. The problem code-line is almost at the bottom of the sample code below.

PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(mPageWidth, mPageHeight, pageNr).create();
PdfDocument.Page page = doc.startPage(pageInfo);

Memory memory = mMemoryData.get(pageNr);
Canvas canvas = page.getCanvas();

TextPaint paint = new TextPaint();
paint.setColor(Color.BLACK);

//Header
Yposition = drawItem( canvas,
                      paint,
                      18,
                      true,
                      Xposition,
                      Yposition,
                      memory.getTitle() );

//line
Yposition += 14; //Extra offset to get some space between the text and line
paint.setColor( ContextCompat.getColor(this, R.color.default_Accent) );
canvas.drawLine( Xposition, Yposition, pageInfo.getPageWidth() - Xposition, Yposition, paint );

Yposition += 20;
paint.setColor(Color.BLACK);
paint.setTextSize(10);
// **this is the line that gives the problem**
canvas.drawText(memory.getText(),Xposition, Yposition, paint);

doc.finishPage(page);

The result of this action is:

At first sight this looks ok but if you zoom in a bit or better yet copy/past the text into notepad (or something) you get this:

No w le ts try this

In stead of the problem line, I also tried this:

drawItem( canvas, paint, 10, false, Xposition, Yposition, memory.getText() );

This has some benefits especially with bigger text but other that that it gives the same problem.

Does anybody have an idea how to solve this?