问:
Javascript await sequence problem in expo-sqlite
I am using react native expo to do the init data load and insert it into DB.
But seems the sequence is not my expectations.

and below is my init function

```<code>import { getData } from './GetData'
const db = SQLite.openDatabase('db.db') // returns Database object

const initDB = async (res: any) => {
    await db.transaction(async tx => {
        await tx.executeSql(`create table if not exists table (
            id integer primary key AUTOINCREMENT not null,
            ...... // create db query
        )`, [],
        () => {
            console.log("created table")
        })

        await tx.executeSql(insertQuery
            , res.list,
            () => {
                console.log(`inserted data success`)
            },
            (_, err): boolean | any => {
                console.log(`err: ${err}`)
            }
        )
    })
}

export const initLoading = async () => {
    const res = await getData() // get data from API
    await initDB(res)
}
</code>```
```<code>await new Promise(async resolve => {
    await initLoading()
    console.log("init done")
})
</code>```

my expected console log should be

```<code>created table
inserted data success
init done
</code>```

but the result is

```<code>init done
created table
inserted data success
</code>```

what thing I am doing wrong to make the sequence incorrect?

答:
The problem is that in db.transaction you pass a function as argument. You dont await the function  you passed, but you await just the execution of db.transaction. I think the best way to fix this is to wrap db.transaction in a Promise and resolve it when you need it to.

const initDB = async (res: any) => {
    return new Promise(async resolve =>
        await db.transaction(async tx => {
            await tx.executeSql(`create table if not exists table (
                id integer primary key AUTOINCREMENT not null,
                ...... // create db query
            )`, [],
            () => {
                console.log("created table")
            })

            await tx.executeSql(insertQuery
                , res.list,
                () => {
                    console.log(`inserted data success`)
                    // Resovle when the data is successful
                    resolve()
                },
                (_, err): boolean | any => {
                    console.log(`err: ${err}`)
                }
            )
        })
    )
}
```

I would recommend you to also resolve on error. Else your code get's stuck.

Body:
I am using react native expo to do the init data load and insert it into DB.
But seems the sequence is not my expectations.

and below is my init function

import { getData } from './GetData'
const db = SQLite.openDatabase('db.db') // returns Database object

const initDB = async (res: any) => {
    await db.transaction(async tx => {
        await tx.executeSql(`create table if not exists table (
            id integer primary key AUTOINCREMENT not null,
            ...... // create db query
        )`, [],
        () => {
            console.log("created table")
        })

        await tx.executeSql(insertQuery
            , res.list,
            () => {
                console.log(`inserted data success`)
            },
            (_, err): boolean | any => {
                console.log(`err: ${err}`)
            }
        )
    })
}

export const initLoading = async () => {
    const res = await getData() // get data from API
    await initDB(res)
}

await new Promise(async resolve => {
    await initLoading()
    console.log("init done")
})

my expected console log should be

created table
inserted data success
init done

but the result is

init done
created table
inserted data success

what thing I am doing wrong to make the sequence incorrect?

Body:
The problem is that in db.transaction you pass a function as argument. You dont await the function  you passed, but you await just the execution of db.transaction. I think the best way to fix this is to wrap db.transaction in a Promise and resolve it when you need it to.

const initDB = async (res: any) => {
    return new Promise(async resolve =>
        await db.transaction(async tx => {
            await tx.executeSql(`create table if not exists table (
                id integer primary key AUTOINCREMENT not null,
                ...... // create db query
            )`, [],
            () => {
                console.log("created table")
            })

            await tx.executeSql(insertQuery
                , res.list,
                () => {
                    console.log(`inserted data success`)
                    // Resovle when the data is successful
                    resolve()
                },
                (_, err): boolean | any => {
                    console.log(`err: ${err}`)
                }
            )
        })
    )
}

I would recommend you to also resolve on error. Else your code get's stuck.


来源: stackexchange

问:
is two different ERC721 contract can mint same NFT
I'm learning blockchain development recently and I'm
implementing ERC721 contract to mint NFT and store the mapping of ownership. What if I deploy a second contract which mints NFT using same characteristics, does it have different NFTs or it will be replication of NFTs on the blockchain? Also, is there a possibility of minting same NFTs on the blockchain?</p>

答: absolutely not, even if you are forking an existing contract (i.e. a replica), the contracts will be completely separate from each other, the ownership mapping of your contract will be completely different from that of the already existing contract</p>

ContentLicense: CC BY-SA 4.0


问:
firebaseAppDistribution with Github Actions throwing error "Missing app id", even with google services plugin set
I'm implementing app distribution for android with github actions, everything seems to be okay but I'm getting an error:

```<code>* What went wrong:
Execution failed for task ':app:appDistributionUploadQaRelease'.
> Missing app id. Please check that it was passed in and try again
</code>```

I'm using google play plugin so it should get the app id automatically.

https://firebase.google.com/docs/app-distribution/android/distribute-gradle#step_3_configure_your_distribution_properties

appId -- Your app's Firebase App ID. Required only if you don't have the Google Services Gradle plugin installed.

I have google-services.json file in app module,

in root build.gradle:

```<code>classpath 'com.google.gms:google-services:4.3.10'
classpath 'com.google.firebase:firebase-appdistribution-gradle:3.0.0'
</code>```

in app's build.gradle:

```<code>plugins {
....
    id 'com.google.gms.google-services'
    id 'com.google.firebase.appdistribution'
}
</code>```

in qa flavour:

```<code>productFlavors {
   ....
    qa {
        applicationId "custom.package.for.qa"
        ....
        firebaseAppDistribution {
            releaseNotes =  "something 123"
            groups = "testers"
        }
    }
}
</code>```

if I add "appId = ...." inside firebaseAppDistribution, the build is uploaded successfully. but this shouldn't be necessary because of google play plugin.

and in github action:

```<code>-   name: Build & Deploy
    run: |
        export FIREBASE_TOKEN=${{ secrets.FIREBASE_TOKEN }}
        ./gradlew --stop
        ./gradlew clean
        ./gradlew assembleQaRelease appDistributionUploadQaRelease
</code>```

Thanks!

答:
I also confirm it's a bug in the latest version of their library:

```<code>com.google.firebase:firebase-appdistribution-gradle:3.0.0
</code>```

I opened an issue on their GitHub so hopefully they will fix it soon.

Body:
I'm implementing app distribution for android with github actions, everything seems to be okay but I'm getting an error:

* What went wrong:
Execution failed for task ':app:appDistributionUploadQaRelease'.
> Missing app id. Please check that it was passed in and try again

I'm using google play plugin so it should get the app id automatically.

https://firebase.google.com/docs/app-distribution/android/distribute-gradle#step_3_configure_your_distribution_properties

appId -- Your app's Firebase App ID. Required only if you don't have the Google Services Gradle plugin installed.

I have google-services.json file in app module,

in root build.gradle:

classpath 'com.google.gms:google-services:4.3.10'
classpath 'com.google.firebase:firebase-appdistribution-gradle:3.0.0'

in app's build.gradle:

plugins {
....
    id 'com.google.gms.google-services'
    id 'com.google.firebase.appdistribution'
}

in qa flavour:

productFlavors {
   ....
    qa {
        applicationId "custom.package.for.qa"
        ....
        firebaseAppDistribution {
            releaseNotes =  "something 123"
            groups = "testers"
        }
    }
}

if I add "appId = ...." inside firebaseAppDistribution, the build is uploaded successfully. but this shouldn't be necessary because of google play plugin.

and in github action:

-   name: Build & Deploy
    run: |
        export FIREBASE_TOKEN=${{ secrets.FIREBASE_TOKEN }}
        ./gradlew --stop
        ./gradlew clean
        ./gradlew assembleQaRelease appDistributionUploadQaRelease

Thanks!

Body:
I also confirm it's a bug in the latest version of their library:

com.google.firebase:firebase-appdistribution-gradle:3.0.0

I opened an issue on their GitHub so hopefully they will fix it soon.


问:
What happens if you check for < condition in ternary or conditional operator(x < y ? num1 : num2) in c, but the input value is equal
So I was just trying to write a C code for comparing numbers, which one of the three number is largest and which one is the smallest.

Then I found that I can use the ternary operator (ex: x < y ? num1 : num2), so I thought yeah okay this will work and then I wrote this code:

```<code>#include <stdio.h>
int main(){
int num1, num2, num3, largest, smallest;

printf("Enter three integers: ");
scanf("%d %d %d", &num1, &num2, &num3);

//largest among three integers.

largest = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);
printf("\nThe largest among the three is: %d", largest);

//smallest among three integers

smallest = num1 < num2 ? (num1 < num3 ? num1 : num3) : (num2 < num3 ? num2 : num3);
printf("\nThe smallest among the three is: %d", smallest);

return 0;
}
</code>```

So, if I give input like num1 = 10, num2 = 20 and num3 = 30, then the output is

```<code>Enter three integers: 10 20 30

The largest among the three is: 30
The smallest among the three is: 10
</code>```

But what happens when all these numbers are equal? Will the condition of the Ternary operator be true or false?

```<code>Enter three integers: 20 20 20

The largest among the three is: 20
The smallest among the three is: 20
</code>```

I don't know what the condition but the program works fine nothing wrong the output is correct.

I am using this on windows 10 latest and gcc.exe (MinGW.org GCC-6.3.0-1) 6.3.0

I am sorry if this is a lame question but I didn't found anything about this.

答:
> larger operator is true only if the left value is larger than the rigth value. Otherwise it will be false

Will the condition of the Ternary operator be true or false?

```<code>n = x > y ? x : y;
</code>```

n will be assigned with the value of x if x is larger than y, otherwise (including the case when x == y) it will be assigned with the value of y

Body:
So I was just trying to write a C code for comparing numbers, which one of the three number is largest and which one is the smallest.

Then I found that I can use the ternary operator (ex: x < y ? num1 : num2), so I thought yeah okay this will work and then I wrote this code:

#include <stdio.h>
int main(){
int num1, num2, num3, largest, smallest;

printf("Enter three integers: ");
scanf("%d %d %d", &num1, &num2, &num3);

//largest among three integers.

largest = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);
printf("\nThe largest among the three is: %d", largest);

//smallest among three integers

smallest = num1 < num2 ? (num1 < num3 ? num1 : num3) : (num2 < num3 ? num2 : num3);
printf("\nThe smallest among the three is: %d", smallest);

return 0;
}

So, if I give input like num1 = 10, num2 = 20 and num3 = 30, then the output is

Enter three integers: 10 20 30

The largest among the three is: 30
The smallest among the three is: 10

But what happens when all these numbers are equal? Will the condition of the Ternary operator be true or false?

Enter three integers: 20 20 20

The largest among the three is: 20
The smallest among the three is: 20

I don't know what the condition but the program works fine nothing wrong the output is correct.

I am using this on windows 10 latest and gcc.exe (MinGW.org GCC-6.3.0-1) 6.3.0

I am sorry if this is a lame question but I didn't found anything about this.

Body:
> larger operator is true only if the left value is larger than the rigth value. Otherwise it will be false

Will the condition of the Ternary operator be true or false?

n = x > y ? x : y;

n will be assigned with the value of x if x is larger than y, otherwise (including the case when x == y) it will be assigned with the value of y


问:
How to use multiple models inside one viewset/serializer?
I have 2 items inside my system that I have to use.But I am trying to develop a system which i have to get them inside one view and order them by "timestamp".

```<code>class CalendarEventSerializer(serializers.ModelSerializer):

    class Meta:
        model = CalendarEvent
        fields = ("id","author",...)

class CalendarItemSerializer(serializers.ModelSerializer):

    class Meta:
        model = CalendarItem
        fields = ("id","author",...)
</code>```

I use ViewSet to regulate my models to paginate and filter them.

```<code>class CalendarItemViewSet(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated,)
    queryset = CalendarItem.objects.all().order_by('-timestamp')
    serializer_class = CalendarItemSerializer
    filter_backends = [UserFilterBackend,DjangoFilterBackend]
    pagination_class = StandardResultsSetPagination
    filterset_fields = ['author']

class CalendarEventViewSet(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated,)
    queryset = CalendarEvent.objects.all().order_by('-timestamp')
    serializer_class = CalendarEventSerializer
    filter_backends = [UserFilterBackend,DjangoFilterBackend]
    pagination_class = StandardResultsSetPagination
    filterset_fields = ['author']
</code>```

How can I use this system to merge 2 or models into one viewset or serializer like this?

Note:I know there are some answers for similar kind of questions in stackoverflow but my code structure is but different, I want to get some viewpoints

Update

So here is what i want to do:
-I am forming a feed page like facebook/instagram and combine multiple models inside one view.

-I can already do it with the viewsets above,but i want to now merge them.

-I want to sort each item by its timestamp and retrieve them inside JSON but inside one system, not like :

```<code>calendarevents:[] calendaritems []
</code>```

but like:

```<code>calendarevent 1(created 2 mins ago)
calendaritem 1 (created 3 mins ago)
calendarevent 2(created 4 mins ago)
calendaritem 2(created 5 mins ago)
</code>```

I am happy to include more information,just ask.

Update 2:

```<code>class CalendarEvent(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.ForeignKey(User,  on_delete=models.CASCADE,related_name='calendarevents')
    charfield1 = models.CharField(max_length=300)
    integerfield1 = models.IntegerField(default='0')
    charfield2 = models.CharField(max_length=200,null=True, blank=True)
    charfield3= models.CharField(null=True,blank=True,max_length=64000)

class CalendarItem(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.ForeignKey(User,  on_delete=models.CASCADE,related_name='calendaritems')
    charfield1 = models.CharField(max_length=300)
    integerfield1 = models.IntegerField(default='0')
    charfield2 = models.CharField(max_length=200,null=True, blank=True)
    charfield3= models.CharField(null=True,blank=True,max_length=64000)

</code>```

答:
You can customize the login using APIView and Generic APIVIEW

Here is one of the ways you can achieve what you are trying to achieve.

```<code>class GetCalenderEventAndItemsAPIView(APIView, GenericAPIView):
    permission_classes = (IsAuthenticated,)
    item_queryset = CalendarItem.objects.all().order_by('-timestamp')
    event_queryset = CalendarEvent.objects.all().order_by('-timestamp')
    item_serializer_class = CalendarItemSerializer
    event_serializer_class = CalendarEventSerializer
    filterset_fields = ['author']

    def get_paginated_query(self, _query_set):
        page = self.paginate_queryset(self.filter_queryset(_query_set))
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        return page

    def get(self, request, *args, **kwargs):
        event_serializer = self.event_serializer_class(self.get_paginated_query(self.event_queryset),
                                                       many=True)
        item_serializer = self.event_serializer_class(self.get_paginated_query(self.item_queryset), many=True)

        response_results = {
            "calendarevents": event_serializer.data,
            "calendaritems": item_serializer.data

        }
        return Response(response_results)
</code>```

It will get you in the right direction. Just play around above way of doing it.

Body:
I have 2 items inside my system that I have to use.But I am trying to develop a system which i have to get them inside one view and order them by "timestamp".

class CalendarEventSerializer(serializers.ModelSerializer):

    class Meta:
        model = CalendarEvent
        fields = ("id","author",...)

class CalendarItemSerializer(serializers.ModelSerializer):

    class Meta:
        model = CalendarItem
        fields = ("id","author",...)

I use ViewSet to regulate my models to paginate and filter them.

class CalendarItemViewSet(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated,)
    queryset = CalendarItem.objects.all().order_by('-timestamp')
    serializer_class = CalendarItemSerializer
    filter_backends = [UserFilterBackend,DjangoFilterBackend]
    pagination_class = StandardResultsSetPagination
    filterset_fields = ['author']

class CalendarEventViewSet(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated,)
    queryset = CalendarEvent.objects.all().order_by('-timestamp')
    serializer_class = CalendarEventSerializer
    filter_backends = [UserFilterBackend,DjangoFilterBackend]
    pagination_class = StandardResultsSetPagination
    filterset_fields = ['author']

How can I use this system to merge 2 or models into one viewset or serializer like this?

Note:I know there are some answers for similar kind of questions in stackoverflow but my code structure is but different, I want to get some viewpoints

Update

So here is what i want to do:
-I am forming a feed page like facebook/instagram and combine multiple models inside one view.

-I can already do it with the viewsets above,but i want to now merge them.

-I want to sort each item by its timestamp and retrieve them inside JSON but inside one system, not like :

calendarevents:[] calendaritems []

but like:

calendarevent 1(created 2 mins ago)
calendaritem 1 (created 3 mins ago)
calendarevent 2(created 4 mins ago)
calendaritem 2(created 5 mins ago)

I am happy to include more information,just ask.

Update 2:

class CalendarEvent(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.ForeignKey(User,  on_delete=models.CASCADE,related_name='calendarevents')
    charfield1 = models.CharField(max_length=300)
    integerfield1 = models.IntegerField(default='0')
    charfield2 = models.CharField(max_length=200,null=True, blank=True)
    charfield3= models.CharField(null=True,blank=True,max_length=64000)

class CalendarItem(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.ForeignKey(User,  on_delete=models.CASCADE,related_name='calendaritems')
    charfield1 = models.CharField(max_length=300)
    integerfield1 = models.IntegerField(default='0')
    charfield2 = models.CharField(max_length=200,null=True, blank=True)
    charfield3= models.CharField(null=True,blank=True,max_length=64000)

Body:
You can customize the login using APIView and Generic APIVIEW

Here is one of the ways you can achieve what you are trying to achieve.

class GetCalenderEventAndItemsAPIView(APIView, GenericAPIView):
    permission_classes = (IsAuthenticated,)
    item_queryset = CalendarItem.objects.all().order_by('-timestamp')
    event_queryset = CalendarEvent.objects.all().order_by('-timestamp')
    item_serializer_class = CalendarItemSerializer
    event_serializer_class = CalendarEventSerializer
    filterset_fields = ['author']

    def get_paginated_query(self, _query_set):
        page = self.paginate_queryset(self.filter_queryset(_query_set))
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        return page

    def get(self, request, *args, **kwargs):
        event_serializer = self.event_serializer_class(self.get_paginated_query(self.event_queryset),
                                                       many=True)
        item_serializer = self.event_serializer_class(self.get_paginated_query(self.item_queryset), many=True)

        response_results = {
            "calendarevents": event_serializer.data,
            "calendaritems": item_serializer.data

        }
        return Response(response_results)

It will get you in the right direction. Just play around above way of doing it.


问:
Remove duplicates from dict values in python
I have a defaultdict of list like this

```<code>{'A':[1,2,3,3,2],'B':[1,2,3,3,2]}
</code>```

Need to remove duplicates in the values only. The dict should be like

```<code>{'A':[1,2,3],'B':[1,2,3]}
</code>```

Tried

```<code>dict((k, tuple(v)) for k, v in list_of_value.items())
</code>```

Not helping much.

答:
Just change the tuple to Set. As the property of set is to make it unique. The change it back to list.</p>
```<code>list_of_value = {'A':[1,2,3,3,2],'B':[1,2,3,3,2]}
dict((k, list(set(v))) for k, v in list_of_value.items())
</code>```

Body:
I have a defaultdict of list like this

{'A':[1,2,3,3,2],'B':[1,2,3,3,2]}

Need to remove duplicates in the values only. The dict should be like

{'A':[1,2,3],'B':[1,2,3]}

Tried

dict((k, tuple(v)) for k, v in list_of_value.items())

Not helping much.

Body:
Just change the tuple to Set. As the property of set is to make it unique. The change it back to list.

list_of_value = {'A':[1,2,3,3,2],'B':[1,2,3,3,2]}
dict((k, list(set(v))) for k, v in list_of_value.items())


问:
Serialize a MongoRecord using Lift
I'm having trouble building a restful service with Lift. All I want to do at this point is serialize a MongoRecord to JSON. Here is my model:

```<code>class Team extends MongoRecord[Team] with MongoId[Team] {
  def meta = Team

  object name extends StringField(this, 100)
  object slug extends StringField(this, 100)
}

object Team extends Team with MongoMetaRecord[Team] {
  def all = Team orderAsc (_.slug) fetch()

  def apply(in: JValue): Box[Team] = Helpers.tryo{in.extract[Team]}

  def unapply(in: String): Option[Team] = Team where (_.slug eqs in) get()

  implicit def toJson(team: Team): JValue =
    Extraction.decompose(team)

  implicit def toJson(teams: Seq[Team]): JValue =
    Extraction.decompose(teams)
}
</code>```

And here is my implementation of RestHelper:

```<code>object TeamRestService extends RestHelper {
  serve( "api" / "teams" prefix {
    case Nil JsonGet _ => Team.all: JValue

    case Team(team) :: Nil JsonGet _ => team: JValue
  })
}
</code>```

Using curl -i -H "Accept: application/json" http://localhost:8080/api/teams I get [{}, {}], and with curl -i -H "Accept: application/json" http://localhost:8080/api/teams/team-1 I get {}. If I put a print statement in the TeamRestService before returning either the single team or the list of teams, I can clearly see that all of the data has been set on the Team instances. For some reason, the serialization is just returning empty objects. What do I need to do to make my Team instances serialize properly? Do I need to make a custom format or use some kind of TypeHint? If so, how would I go about doing that?

答:
Yeah, I was stupid. Extraction.decompose only works with case classes. MongoRecord has a method asJValue. Using that in the implicit defs solved the issue.

```<code>implicit def toJson(team: Team): JValue = team.asJValue

implicit def toJson(teams: Seq[Team]): JValue = teams map { _.asJValue }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Serialize a MongoRecord using Lift

Body:
I'm having trouble building a restful service with Lift. All I want to do at this point is serialize a MongoRecord to JSON. Here is my model:

class Team extends MongoRecord[Team] with MongoId[Team] {
  def meta = Team

  object name extends StringField(this, 100)
  object slug extends StringField(this, 100)
}

object Team extends Team with MongoMetaRecord[Team] {
  def all = Team orderAsc (_.slug) fetch()

  def apply(in: JValue): Box[Team] = Helpers.tryo{in.extract[Team]}

  def unapply(in: String): Option[Team] = Team where (_.slug eqs in) get()

  implicit def toJson(team: Team): JValue =
    Extraction.decompose(team)

  implicit def toJson(teams: Seq[Team]): JValue =
    Extraction.decompose(teams)
}

And here is my implementation of RestHelper:

object TeamRestService extends RestHelper {
  serve( "api" / "teams" prefix {
    case Nil JsonGet _ => Team.all: JValue

    case Team(team) :: Nil JsonGet _ => team: JValue
  })
}

Using curl -i -H "Accept: application/json" http://localhost:8080/api/teams I get [{}, {}], and with curl -i -H "Accept: application/json" http://localhost:8080/api/teams/team-1 I get {}. If I put a print statement in the TeamRestService before returning either the single team or the list of teams, I can clearly see that all of the data has been set on the Team instances. For some reason, the serialization is just returning empty objects. What do I need to do to make my Team instances serialize properly? Do I need to make a custom format or use some kind of TypeHint? If so, how would I go about doing that?

Body:
Yeah, I was stupid. Extraction.decompose only works with case classes. MongoRecord has a method asJValue. Using that in the implicit defs solved the issue.

implicit def toJson(team: Team): JValue = team.asJValue

implicit def toJson(teams: Seq[Team]): JValue = teams map { _.asJValue }


问:
How to install jdk 8 on ubuntu server 18.04?
I am trying to install JDK 8 ON Ubuntu server 18.04 LTS, with the following commands:

```<code>sudo apt install openjdk-8-jre
sudo apt install openjdk-8-jdk
</code>```

/usr/lib/jvm folder has:

I also set the path into /etc/environment for JAVA_HOME
But I still get an error while java -version as:

```<code>Command 'java' not found, but can be installed with:

sudo apt install default-jre
sudo apt install openjdk-11-jre-headless
sudo apt install openjdk-8-jre-headless

</code>```

Can anyone please suggest to solve an error?
Thank you in advance.

答:
try this one.

```<code>apt install oracle-java8-set-default
</code>```

The above commands will automatically install selected java version and set all necessary java environment variables.

Body:
I am trying to install JDK 8 ON Ubuntu server 18.04 LTS, with the following commands:

sudo apt install openjdk-8-jre
sudo apt install openjdk-8-jdk

/usr/lib/jvm folder has:

I also set the path into /etc/environment for JAVA_HOME
But I still get an error while java -version as:

Command 'java' not found, but can be installed with:

sudo apt install default-jre
sudo apt install openjdk-11-jre-headless
sudo apt install openjdk-8-jre-headless

Can anyone please suggest to solve an error?
Thank you in advance.

Body:
try this one.

apt install oracle-java8-set-default

The above commands will automatically install selected java version and set all necessary java environment variables.


问:
Convert object to array of prorperties
I need to convert object:

```<code>{
        middleName: null,
        name: "Test Name",
        university: {
            country: {
                code: "PL"
            },
            isGraduated: true,
            speciality: "Computer Science"
        }
    }
</code>```

to array:

```<code>[{
        key: "name",
        propertyValue: "Test Name",
    },
    {
        key: "middleName",
        propertyValue: null,
    },
    {
        key: "university.isGraduated",
        propertyValue: true,
    },
    {
        key: "university.speciality",
        propertyValue: "Computer Science",
    },
    {
        key: "university.country.code",
        propertyValue: "PL"
    }];
</code>```

I wrote algorithm, but it's pretty dummy, how can I improve it? Important, if object has nested object than I need to write nested object via dot (e.g university.contry: "value")

```<code>let arr = [];
    Object.keys(parsedObj).map((key) => {
        if (parsedObj[key] instanceof Object) {
            Object.keys(parsedObj[key]).map((keyNested) => {
                if (parsedObj[key][keyNested] instanceof Object) {
                    Object.keys(parsedObj[key][keyNested]).map((keyNestedNested) => {
                        arr.push({ 'key': key + '.' + keyNested + '.' + keyNestedNested, 'propertyValue': parsedObj[key][keyNested][keyNestedNested] })
                    })
                } else {
                    arr.push({ 'key': key + '.' + keyNested, 'propertyValue': parsedObj[key][keyNested] })
                }
            })
        } else {
            arr.push({ 'key': key, 'propertyValue': parsedObj[key] })
        }
    });
</code>```

Thanks

答:
I wrote a small version using recursive function and another for validation is an object.

let values = {
  middleName: null,
  name: "Test Name",
  university: {
    country: {
      code: "PL"
    },
    isGraduated: true,
    speciality: "Computer Science"
  }
}

function isObject(obj) {
  return obj != null && obj.constructor.name === "Object"
}

function getValues(values) {
  let arrValues = Object.keys(values).map(
    v => {
      return { key: v, value: isObject(values[v]) ? getValues(values[v]) : values[v] };

    });
  console.log(arrValues);
}

getValues(values);```

Title: Convert object to array of prorperties

Body:
I need to convert object:

{
        middleName: null,
        name: "Test Name",
        university: {
            country: {
                code: "PL"
            },
            isGraduated: true,
            speciality: "Computer Science"
        }
    }

to array:

[{
        key: "name",
        propertyValue: "Test Name",
    },
    {
        key: "middleName",
        propertyValue: null,
    },
    {
        key: "university.isGraduated",
        propertyValue: true,
    },
    {
        key: "university.speciality",
        propertyValue: "Computer Science",
    },
    {
        key: "university.country.code",
        propertyValue: "PL"
    }];

I wrote algorithm, but it's pretty dummy, how can I improve it? Important, if object has nested object than I need to write nested object via dot (e.g university.contry: "value")

let arr = [];
    Object.keys(parsedObj).map((key) => {
        if (parsedObj[key] instanceof Object) {
            Object.keys(parsedObj[key]).map((keyNested) => {
                if (parsedObj[key][keyNested] instanceof Object) {
                    Object.keys(parsedObj[key][keyNested]).map((keyNestedNested) => {
                        arr.push({ 'key': key + '.' + keyNested + '.' + keyNestedNested, 'propertyValue': parsedObj[key][keyNested][keyNestedNested] })
                    })
                } else {
                    arr.push({ 'key': key + '.' + keyNested, 'propertyValue': parsedObj[key][keyNested] })
                }
            })
        } else {
            arr.push({ 'key': key, 'propertyValue': parsedObj[key] })
        }
    });

Thanks


答:
you can use the same dict to save to memoy</p>
```<code>dict_t = {'A':[1,2,3,3,2],'B':[1,2,3,3,2]}

for key,val in  dict_t.items():
  dict_t[key] = list(set(dict_t[key]))

#output {'A': [1, 2, 3], 'B': [1, 2, 3]}

</code>```

Title: Remove duplicates from dict values in python

Body:
you can use the same dict to save to memoy

dict_t = {'A':[1,2,3,3,2],'B':[1,2,3,3,2]}

for key,val in  dict_t.items():
  dict_t[key] = list(set(dict_t[key]))

#output {'A': [1, 2, 3], 'B': [1, 2, 3]}


Title: Merge two dataframes by nearest date in R

Body:
I have two dataframes which I want to merge by nearest date. There´re often the same date of df2 which fits to df1. Also there´re values of df2 which doesn´t fit to df1 at all. After merging I want to know the time difference between the merging dates. For example ship Sally fits to two Peaks, ship Carl to no one.
I tried different solutions e.g. with data.table roll='nearest' function

df1 <- data.frame(date = (c("23.11.2021 20:56:06", "23.11.2021 20:56:07","23.11.2021 20:56:08",
                                      "23.11.2021 20:56:09","23.11.2021 20:56:10",
                                      "23.11.2021 20:56:11", "23.11.2021 22:13:56",
                                      "23.11.2021 22:13:57", "23.11.2021 22:13:58",
                                      "23.11.2021 22:13:59", "24.11.2021 03:23:21",
                                      "24.11.2021 03:23:22", "24.11.2021 03:23:23",
                                      "24.11.2021 03:23:24", "24.11.2021 03:23:25",
                                      "24.11.2021 03:24:34", "24.11.2021 03:24:35",
                                      "24.11.2021 03:24:36", "24.11.2021 03:24:37")),
                  value = (c(500, 900, 1000, 200, 300, 10, 1000, 450, 950, 600,
                             100, 750, 150, 200, 300, 400, 900, 1020, 800)))

df2 <- data.frame(date = (c("23.11.2021 20:55:47", "23.11.2021 21:17:48",
                            "23.11.2021 21:44:19", "23.11.2021 21:55:57",
                            "23.11.2021 22:16:01","23.11.2021 22:26:35",
                            "23.11.2021 22:28:43", "23.11.2021 23:14:52",
                            "23.11.2021 23:32:30","23.11.2021 23:33:43",
                            "24.11.2021 03:11:30", "24.11.2021 03:23:37",
                            "24.11.2021 04:42:41", "24.11.2021 04:53:09",
                            "24.11.2021 04:58:19")),
                  value = (c("Ship Emma", "Ship Carl", "Ship Rudi", "Ship Tim", "Ship Amy",
                             "Ship Fred", "Ship Noemi"
                             , "Ship Fanny", "Ship Ole", "Ship Ally",
                             "Ship Hugo", "Ship Sally", "Ship Peter", "Ship Harry", "Ship Piet")))

result <- data.frame(date = (c("23.11.2021 20:56:06", "23.11.2021 20:56:07",
                               "23.11.2021 20:56:08", "23.11.2021 20:56:09",
                               "23.11.2021 20:56:10","23.11.2021 20:56:11",
                               "23.11.2021 22:13:56", "23.11.2021 22:13:57",
                               "23.11.2021 22:13:58", "23.11.2021 22:13:59",
                               "24.11.2021 03:23:21", "24.11.2021 03:23:22",
                               "24.11.2021 03:23:23", "24.11.2021 03:23:24",
                               "24.11.2021 03:23:25", "24.11.2021 03:24:34",
                               "24.11.2021 03:24:35", "24.11.2021 03:24:36",
                               "24.11.2021 03:24:37")),
                     value = (c(500, 900, 1000, 200, 300, 10, 1000, 450, 950, 600,
                             100, 750, 150, 200, 300, 400, 900, 1020, 800)),
                     id = (c("Ship Emma", "Ship Emma", "Ship Emma", "Ship Emma", "Ship Emma",
                             "Ship Emma", "Ship Amy", "Ship Amy", "Ship Amy", "Ship Amy",
                                "Ship Sally", "Ship Sally", "Ship Sally", "Ship Sally",
                             "Ship Sally", "Ship Sally", "Ship Sally", "Ship Sally","Ship Sally")),
                     difference = (c("00:00:19", "00:00:20", "00:00:21", "00:00:22", "00:00:23",
                                     "00:00:24", "00:00:05", "00:00:04", "00:00:03", "00:00:02",
                                     "00:00:16", "00:00:15", "00:00:14", "00:00:13", "00:00:12",
                                     "00:00:57", "00:00:58", "00:00:59", "00:01:00")))

df1$date<- as.POSIXct(df1$date, tz = "GMT", format = "%d.%m.%Y %H:%M:%S")
df2$date<- as.POSIXct(df2$date, tz = "GMT", format = "%d.%m.%Y %H:%M:%S")
result$date<- as.POSIXct(result$date, tz = "GMT", format = "%d.%m.%Y %H:%M:%S")

Body:
I suggest two approaches. The first uses a distance matrix and perform a left_join of df1 to df2. Namely the distance matrix is given by:

dateDist <- outer(pull(df1, date), pull(df2, date), "-") %>%
    abs()

Next, for each row of df1, the row of df2 with closest distance is given by:

  closest.df1 <- apply(dateDist, 1, which.min)

Finally, the merge is performed manually:

cbind(rename_with(df1, ~paste0("df1.", "", .x)),
      rename_with(df2[closest.df1,], ~paste0("df2.", "", .x)))

##>+                 df1.date df1.value            df2.date  df2.value
##>1    2021-11-23 20:56:06       500 2021-11-23 20:55:47  Ship Emma
##>1.1  2021-11-23 20:56:07       900 2021-11-23 20:55:47  Ship Emma
##>1.2  2021-11-23 20:56:08      1000 2021-11-23 20:55:47  Ship Emma
##>1.3  2021-11-23 20:56:09       200 2021-11-23 20:55:47  Ship Emma
##>1.4  2021-11-23 20:56:10       300 2021-11-23 20:55:47  Ship Emma
##>1.5  2021-11-23 20:56:11        10 2021-11-23 20:55:47  Ship Emma
##>5    2021-11-23 22:13:56      1000 2021-11-23 22:16:01   Ship Amy
##>5.1  2021-11-23 22:13:57       450 2021-11-23 22:16:01   Ship Amy
##>5.2  2021-11-23 22:13:58       950 2021-11-23 22:16:01   Ship Amy
##>5.3  2021-11-23 22:13:59       600 2021-11-23 22:16:01   Ship Amy
##>12   2021-11-24 03:23:21       100 2021-11-24 03:23:37 Ship Sally
##>12.1 2021-11-24 03:23:22       750 2021-11-24 03:23:37 Ship Sally
##>12.2 2021-11-24 03:23:23       150 2021-11-24 03:23:37 Ship Sally
##>12.3 2021-11-24 03:23:24       200 2021-11-24 03:23:37 Ship Sally
##>12.4 2021-11-24 03:23:25       300 2021-11-24 03:23:37 Ship Sally
##>12.5 2021-11-24 03:24:34       400 2021-11-24 03:23:37 Ship Sally
##>12.6 2021-11-24 03:24:35       900 2021-11-24 03:23:37 Ship Sally
##>12.7 2021-11-24 03:24:36      1020 2021-11-24 03:23:37 Ship Sally
##>12.8 2021-11-24 03:24:37       800 2021-11-24 03:23:37 Ship Sally

The second approach involves first calculating the cartesian product of all the rows of df1 and df2 and then selecting only the rows with the minimum distance. The trick here is to use inner_join(..., by =character()) to get all the combinations of the two dataframes :

mutate(df1, id = row_number()) %>%
    inner_join(mutate(df2, id = row_number()),by = character()) |>
    mutate(dist = abs(date.x - date.y)) |>
    group_by(id.x) |>
    filter(dist == min(dist)) |>
    select(-id.x, -id.y, -dist)

  ##>+ # A tibble: 19 × 7
  ##># Groups:   id.x [19]
  ##>   date.x              value.x  id.x date.y              value.y     id.y dist
  ##>   <dttm>                <dbl> <int> <dttm>              <chr>      <int> <drtn>
  ##> 1 2021-11-23 20:56:06     500     1 2021-11-23 20:55:47 Ship Emma      1  19 s…
  ##> 2 2021-11-23 20:56:07     900     2 2021-11-23 20:55:47 Ship Emma      1  20 s…
  ##> 3 2021-11-23 20:56:08    1000     3 2021-11-23 20:55:47 Ship Emma      1  21 s…
  ##> 4 2021-11-23 20:56:09     200     4 2021-11-23 20:55:47 Ship Emma      1  22 s…
  ##> 5 2021-11-23 20:56:10     300     5 2021-11-23 20:55:47 Ship Emma      1  23 s…
  ##> 6 2021-11-23 20:56:11      10     6 2021-11-23 20:55:47 Ship Emma      1  24 s…
  ##> 7 2021-11-23 22:13:56    1000     7 2021-11-23 22:16:01 Ship Amy       5 125 s…
  ##> 8 2021-11-23 22:13:57     450     8 2021-11-23 22:16:01 Ship Amy       5 124 s…
  ##> 9 2021-11-23 22:13:58     950     9 2021-11-23 22:16:01 Ship Amy       5 123 s…
  ##>10 2021-11-23 22:13:59     600    10 2021-11-23 22:16:01 Ship Amy       5 122 s…
  ##>11 2021-11-24 03:23:21     100    11 2021-11-24 03:23:37 Ship Sally    12  16 s…
  ##>12 2021-11-24 03:23:22     750    12 2021-11-24 03:23:37 Ship Sally    12  15 s…
  ##>13 2021-11-24 03:23:23     150    13 2021-11-24 03:23:37 Ship Sally    12  14 s…
  ##>14 2021-11-24 03:23:24     200    14 2021-11-24 03:23:37 Ship Sally    12  13 s…
  ##>15 2021-11-24 03:23:25     300    15 2021-11-24 03:23:37 Ship Sally    12  12 s…
  ##>16 2021-11-24 03:24:34     400    16 2021-11-24 03:23:37 Ship Sally    12  57 s…
  ##>17 2021-11-24 03:24:35     900    17 2021-11-24 03:23:37 Ship Sally    12  58 s…
  ##>18 2021-11-24 03:24:36    1020    18 2021-11-24 03:23:37 Ship Sally    12  59 s…
  ##>19 2021-11-24 03:24:37     800    19 2021-11-24 03:23:37 Ship Sally    12  60 s…


Body:
d = {'A':[1,2,3,3,2],'B':[1,2,3,3,2]}

u = {k : list(set(d[k])) for k, v in d.items()}


问:
Google App Script: How to fix "Please turn JavaScript on and reload the page"
When I am using "Google App Script" in order to retrieve a json page, I face with the following message:
Please turn JavaScript on and reload the page.

I am not sure how to handle this, hence I can open the same page on my web-browser.

[Q] How could I fix this in order retrieve json-page's information only using "Google App Script"?

```<code>function getJsonFromUrl(strUrl) {
  let _options = {
    method: 'GET',
    muteHttpExceptions: true,
    contentType: 'application/json',
  };
  let _res = UrlFetchApp.fetch(strUrl, _options);
  Logger.log(_res.getContentText());
  return JSON.parse(_res.getContentText());
}
</code>```

答:
As mentioned in the comment #3 and verified with the URL provided:

There is no other way, of course if you have time to explain to Google why this is important feature, you can try create feature request here: issuetracker.google.com

You can use the following template to create the feature request:

https://issuetracker.google.com/issues/new?component=191640&template=824113

Body:
When I am using "Google App Script" in order to retrieve a json page, I face with the following message:
Please turn JavaScript on and reload the page.

I am not sure how to handle this, hence I can open the same page on my web-browser.

[Q] How could I fix this in order retrieve json-page's information only using "Google App Script"?

function getJsonFromUrl(strUrl) {
  let _options = {
    method: 'GET',
    muteHttpExceptions: true,
    contentType: 'application/json',
  };
  let _res = UrlFetchApp.fetch(strUrl, _options);
  Logger.log(_res.getContentText());
  return JSON.parse(_res.getContentText());
}


问:
Javascript split array
I have a JavaScript array which contain the staff's Chinese and English names.

Example:

```<code>XXX MA Yo-Yo
</code>```

Where XXX represents the Chinese name: 馬友友.

I want to split this into two parts by using the 1st space " " as an indicator.

```<code>for (i = 0; i < /* ... */)
{
    w_temp = arr[i];
    w_name = w_temp[1].split(' ', 1);

    /* ... */
}
</code>```

w_name[0] successfully returns 馬友友. But w_name[1] returns undefined, which cannot return MA Yo-Yo.

How can I split it into two parts?

答:
You have

```<code> split(' ', 1)
</code>```

The 1 means to return at most one part.  You should just ommit that or change it to two if thats what you need.

Title: Javascript split array

Body:
I have a JavaScript array which contain the staff's Chinese and English names.

Example:

XXX MA Yo-Yo

Where XXX represents the Chinese name: 馬友友.

I want to split this into two parts by using the 1st space " " as an indicator.

for (i = 0; i < /* ... */)
{
    w_temp = arr[i];
    w_name = w_temp[1].split(' ', 1);

    /* ... */
}

w_name[0] successfully returns 馬友友. But w_name[1] returns undefined, which cannot return MA Yo-Yo.

How can I split it into two parts?

Body:
You have

 split(' ', 1)

The 1 means to return at most one part.  You should just ommit that or change it to two if thats what you need.


问:
HTML2Canvas does not render full div, only what is visible on screen?
I'm trying to use HTML2Canvas to render the contents of a div. Here is the code:

```<code>var htmlSource = $('#potenzial-page')[0];

$('#btn').on("click", function() {

    html2canvas(htmlSource).then(function(canvas) {
        var img = canvas.toDataURL();
        window.open(img);
    });

});
</code>```

I'm using v5 beta 3.

When this code runs, it only renders what is visible on the screen. The #potenzial-page div is essentially the entire page, minus the header and footer. All content in this div is visible by scrolling (there are some hidden elements, but I do not want the hidden elements visible in the image.)

I cannot find what's wrong or why it won't save the entire div. I should also note that it appears the image is as tall as the div but only partially visible.

To give an example of what I mean, here is a comparison:

The left is how HTML2Canvas should render the div. The right shows how it renders when it runs the code above. The right image is what's visible in my browsers screen.

I did try adding the height option but it doesn't make a difference.

UPDATE

If I scroll to the very top of the page then run the script it will render the entire div as it should.

How do I render the div without having to scroll to the top?

答:
```<code><div #potentialContainer id="potentialContainer" class="potentialContainer" style="height: auto;">
some large content here--------------------
</div>

import html2canvas from 'html2canvas';

downloadImage() {

html2canvas(document.querySelector('#potentialContainer'), {
  logging: true,
  allowTaint: false,
  useCORS: true,
  width: document.querySelector('#potentialContainer').scrollWidth,
  height: section.scrollHeight,
  scrollX: -window.scrollX,
  scrollY: -window.scrollY,
}).then((canvas) => {
  var imgWidth = 210;
  var pageHeight = 290;
  var imgHeight = canvas.height * imgWidth / canvas.width;
  var heightLeft = imgHeight;

  var doc = new jsPDF('p', 'mm');
  var position = 0;
  var pageData = canvas.toDataURL('image/jpeg', 1.0);
  var imgData = encodeURIComponent(pageData);
  doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
  doc.setLineWidth(5);
  doc.setDrawColor(255, 255, 255);
  doc.rect(0, 0, 210, 295);
  heightLeft -= pageHeight;

  while (heightLeft >= 0) {
    position = heightLeft - imgHeight;
    doc.addPage();
    doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
    doc.setLineWidth(5);
    doc.setDrawColor(255, 255, 255);
    doc.rect(0, 0, 210, 295);
    heightLeft -= pageHeight;
  }
  doc.save('file.pdf');

 });
 }
</code>```

Note:- It is important to add style height:auto

The above code will convert a large image to a multipage pdf

Body:
I'm trying to use HTML2Canvas to render the contents of a div. Here is the code:

var htmlSource = $('#potenzial-page')[0];

$('#btn').on("click", function() {

    html2canvas(htmlSource).then(function(canvas) {
        var img = canvas.toDataURL();
        window.open(img);
    });

});

I'm using v5 beta 3.

When this code runs, it only renders what is visible on the screen. The #potenzial-page div is essentially the entire page, minus the header and footer. All content in this div is visible by scrolling (there are some hidden elements, but I do not want the hidden elements visible in the image.)

I cannot find what's wrong or why it won't save the entire div. I should also note that it appears the image is as tall as the div but only partially visible.

To give an example of what I mean, here is a comparison:

The left is how HTML2Canvas should render the div. The right shows how it renders when it runs the code above. The right image is what's visible in my browsers screen.

I did try adding the height option but it doesn't make a difference.

UPDATE

If I scroll to the very top of the page then run the script it will render the entire div as it should.

How do I render the div without having to scroll to the top?

Body:
<div #potentialContainer id="potentialContainer" class="potentialContainer" style="height: auto;">
some large content here--------------------
</div>

import html2canvas from 'html2canvas';

downloadImage() {

html2canvas(document.querySelector('#potentialContainer'), {
  logging: true,
  allowTaint: false,
  useCORS: true,
  width: document.querySelector('#potentialContainer').scrollWidth,
  height: section.scrollHeight,
  scrollX: -window.scrollX,
  scrollY: -window.scrollY,
}).then((canvas) => {
  var imgWidth = 210;
  var pageHeight = 290;
  var imgHeight = canvas.height * imgWidth / canvas.width;
  var heightLeft = imgHeight;

  var doc = new jsPDF('p', 'mm');
  var position = 0;
  var pageData = canvas.toDataURL('image/jpeg', 1.0);
  var imgData = encodeURIComponent(pageData);
  doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
  doc.setLineWidth(5);
  doc.setDrawColor(255, 255, 255);
  doc.rect(0, 0, 210, 295);
  heightLeft -= pageHeight;

  while (heightLeft >= 0) {
    position = heightLeft - imgHeight;
    doc.addPage();
    doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
    doc.setLineWidth(5);
    doc.setDrawColor(255, 255, 255);
    doc.rect(0, 0, 210, 295);
    heightLeft -= pageHeight;
  }
  doc.save('file.pdf');

 });
 }

Note:- It is important to add style height:auto

The above code will convert a large image to a multipage pdf


问:
Error:Unable to locate adb within SDK in Android Studio
Does anyone know what this means? When I click the "run" button on my simulator I get this message.

Throwable: Unable to locate adb within SDK

I am running the latest version, 0.8.14.

答:
It worked for me in this way

open your android studio First, and go to SDK manager :

and Copy your Android SDK location then open PowerShell on your windows
and go to that folder like :

```<code>cd C:\Users\YOURUSERNAME\AppData\Local\Android\Sdk
</code>```

then go to platform-tools folder:

```<code>cd platform-tools
</code>```

and then start ADB like this:

```<code>.\adb.exe
</code>```

you can also check if there is any adb.exe by ls or dir in windows command line

if there isn't any platform tools you should first install it and then
paste it into that directory that I've mentioned earlier

you can download platform-tool(adb) from here:
https://developer.android.com/studio/releases/platform-tools

Body:
It worked for me in this way

open your android studio First, and go to SDK manager :

and Copy your Android SDK location then open PowerShell on your windows
and go to that folder like :

cd C:\Users\YOURUSERNAME\AppData\Local\Android\Sdk

then go to platform-tools folder:

cd platform-tools

and then start ADB like this:

.\adb.exe

you can also check if there is any adb.exe by ls or dir in windows command line

if there isn't any platform tools you should first install it and then
paste it into that directory that I've mentioned earlier

you can download platform-tool(adb) from here:
https://developer.android.com/studio/releases/platform-tools


问:
How to convert the following json string to java object?
I want to convert the following JSON string to a java object:

```<code>String jsonString = "{
  "libraryname": "My Library",
  "mymusic": [
    {
      "Artist Name": "Aaron",
      "Song Name": "Beautiful"
    },
    {
      "Artist Name": "Britney",
      "Song Name": "Oops I did It Again"
    },
    {
      "Artist Name": "Britney",
      "Song Name": "Stronger"
    }
  ]
}"
</code>```

My goal is to access it easily something like:

```<code>(e.g. MyJsonObject myobj = new MyJsonObject(jsonString)
myobj.mymusic[0].id would give me the ID, myobj.libraryname gives me "My Library").
</code>```

I've heard of Jackson, but I am unsure how to use it to fit the json string I have since its not just key value pairs due to the "mymusic" list involved. How can I accomplish this with Jackson or is there some easier way I can accomplish this if Jackson is not the best for this?

答:
Underscore-java (which I am the developer of) can convert json to Object.

```<code>import com.github.underscore.U;

    String jsonString = "{\n" +
            "        \"libraryname\":\"My Library\",\n" +
            "                \"mymusic\":[{\"Artist Name\":\"Aaron\",\"Song Name\":\"Beautiful\"},\n" +
            "        {\"Artist Name\":\"Britney\",\"Song Name\":\"Oops I did It Again\"},\n" +
            "        {\"Artist Name\":\"Britney\",\"Song Name\":\"Stronger\"}]}";
    Map<String, Object> jsonObject = U.fromJsonMap(jsonString);
    System.out.println(jsonObject);

    // {libraryname=My Library, mymusic=[{Artist Name=Aaron, Song Name=Beautiful}, {Artist Name=Britney, Song Name=Oops I did It Again}, {Artist Name=Britney, Song Name=Stronger}]}

    System.out.println(U.<String>get(jsonObject, "mymusic[0].Artist Name"));
    // Aaron
</code>```

Body:
I want to convert the following JSON string to a java object:

String jsonString = "{
  "libraryname": "My Library",
  "mymusic": [
    {
      "Artist Name": "Aaron",
      "Song Name": "Beautiful"
    },
    {
      "Artist Name": "Britney",
      "Song Name": "Oops I did It Again"
    },
    {
      "Artist Name": "Britney",
      "Song Name": "Stronger"
    }
  ]
}"

My goal is to access it easily something like:

(e.g. MyJsonObject myobj = new MyJsonObject(jsonString)
myobj.mymusic[0].id would give me the ID, myobj.libraryname gives me "My Library").

I've heard of Jackson, but I am unsure how to use it to fit the json string I have since its not just key value pairs due to the "mymusic" list involved. How can I accomplish this with Jackson or is there some easier way I can accomplish this if Jackson is not the best for this?

Body:
Underscore-java (which I am the developer of) can convert json to Object.

import com.github.underscore.U;

    String jsonString = "{\n" +
            "        \"libraryname\":\"My Library\",\n" +
            "                \"mymusic\":[{\"Artist Name\":\"Aaron\",\"Song Name\":\"Beautiful\"},\n" +
            "        {\"Artist Name\":\"Britney\",\"Song Name\":\"Oops I did It Again\"},\n" +
            "        {\"Artist Name\":\"Britney\",\"Song Name\":\"Stronger\"}]}";
    Map<String, Object> jsonObject = U.fromJsonMap(jsonString);
    System.out.println(jsonObject);

    // {libraryname=My Library, mymusic=[{Artist Name=Aaron, Song Name=Beautiful}, {Artist Name=Britney, Song Name=Oops I did It Again}, {Artist Name=Britney, Song Name=Stronger}]}

    System.out.println(U.<String>get(jsonObject, "mymusic[0].Artist Name"));
    // Aaron


问:
Download Excel File via button on website with Python
I am currently working on a code that downloads an excel file from a website. The respective file is actually hidden behind an Export button (see website: https://www.amundietf.co.uk/retail/product/view/LU1437018838). However, I have already identified the link behind which is the following: https://www.amundietf.co.uk/retail/ezaap/service/ExportDataProductSheet/Fwd/en-GB/718/LU1437018838/object/export/repartition?idFonctionnel=export-repartition-pie-etf&exportIndex=3&hasDisclaimer=1. Since the link does not directly guide to the file but rather executes some Java widget, I am not able to download the file via python. I have tried the folling code:

```<code>import re
import requests
link = 'https://www.amundietf.co.uk/retail/ezaap/service/ExportDataProductSheet/Fwd/en-GB/718/LU1437018838/object/export/repartition?idFonctionnel=export-repartition-pie-etf&exportIndex=3&hasDisclaimer=1'

r = requests.get(link, verify= False)
</code>```

However, I am not able to connect to the file. Does somebody has an idea for doing this?

答:
I would recommend using HTML:

    Click here to download

```

In the href attribute to  tag, you can put the path to your own excel file. I used an external link to an example file I found on google. To open in new tab, use target="_blank" as attribute to .

Hope it works!

Body:
I am currently working on a code that downloads an excel file from a website. The respective file is actually hidden behind an Export button (see website: https://www.amundietf.co.uk/retail/product/view/LU1437018838). However, I have already identified the link behind which is the following: https://www.amundietf.co.uk/retail/ezaap/service/ExportDataProductSheet/Fwd/en-GB/718/LU1437018838/object/export/repartition?idFonctionnel=export-repartition-pie-etf&exportIndex=3&hasDisclaimer=1. Since the link does not directly guide to the file but rather executes some Java widget, I am not able to download the file via python. I have tried the folling code:

import re
import requests
link = 'https://www.amundietf.co.uk/retail/ezaap/service/ExportDataProductSheet/Fwd/en-GB/718/LU1437018838/object/export/repartition?idFonctionnel=export-repartition-pie-etf&exportIndex=3&hasDisclaimer=1'

r = requests.get(link, verify= False)

However, I am not able to connect to the file. Does somebody has an idea for doing this?

Body:
I would recommend using HTML:

<html lang=en>
  <body>
    <a href="https://file-examples-com.github.io/uploads/2017/02/file_example_XLSX_10.xlsx" target="_blank">Click here to download</a>
  </body>
</html>

In the href attribute to  tag, you can put the path to your own excel file. I used an external link to an example file I found on google. To open in new tab, use target="_blank" as attribute to .

Hope it works!


问:
Adding a new column in R data.frame converts the type of all other columns
I'm running into an issue I cannot explain:
I have a data.frame of numeric columns and adding a new column in any way ($ operator, cbind ...) changes the type of all other columns to character

```<code>> ab_dt = data.frame(ab_mat)
> unique(apply(ab_dt, 2, class))
[1] "numeric"
> a = meta[rownames(ab_dt), "Location"]
> class(a)
[1] "factor"
> ab_dt$Location = a
> unique(apply(ab_dt, 2, class))
[1] "character"
</code>```

Does anyone know why this is happening?

答:
It has something to do with how you calculate the class. I would suggest to use sapply instead. Using a tibble instead of a data.frame allows you to always keep track of column classes in printing:

data <- data.frame(
  a = factor("foo", levels = c("foo", "bar")),
  b = "baz"
)
data
#>     a   b
#> 1 foo baz
unique(apply(data, 2, class))
#> [1] "character"
sapply(data, class)
#>           a           b
#>    "factor" "character"
tibble::as_tibble(data)
#> # A tibble: 1 x 2
#>   a     b
#>   <fct> <chr>
#> 1 foo   baz
```
</code>```

Body:
I'm running into an issue I cannot explain:
I have a data.frame of numeric columns and adding a new column in any way ($ operator, cbind ...) changes the type of all other columns to character

> ab_dt = data.frame(ab_mat)
> unique(apply(ab_dt, 2, class))
[1] "numeric"
> a = meta[rownames(ab_dt), "Location"]
> class(a)
[1] "factor"
> ab_dt$Location = a
> unique(apply(ab_dt, 2, class))
[1] "character"

Does anyone know why this is happening?


问:
Please do I interprete this ternary operator?
Please if this function was to be converted to a "normal" if else statement, how would it look like?

```<code>export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));
</code>```

I want to add another condition, but I'm finding it hard to read or digest the current flow.

答:
Edit:

According to @Erich Kitzmueller's answer, I removed a[key] === b[key] part:

```<code>export const orderArr = (arr: any[], key: string) => arr.sort((a, b) =>
{
    if(a[key] > b[key]){
        return 1;
    } else {
        return -1;
    }
}
);
</code>```

Original Answer:

I am not sure about sort function's structure but the if statement might look like below:

```<code>export const orderArr = (arr: any[], key: string) => arr.sort((a, b) =>
{
    if(a[key] > b[key] || a[key] === b[key]){
        return 1;
    } else {
        return -1;
    }
}
);
</code>```

Body:
Please if this function was to be converted to a "normal" if else statement, how would it look like?

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));

I want to add another condition, but I'm finding it hard to read or digest the current flow.

Body:
Edit:

According to @Erich Kitzmueller's answer, I removed a[key] === b[key] part:

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) =>
{
    if(a[key] > b[key]){
        return 1;
    } else {
        return -1;
    }
}
);

Original Answer:

I am not sure about sort function's structure but the if statement might look like below:

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) =>
{
    if(a[key] > b[key] || a[key] === b[key]){
        return 1;
    } else {
        return -1;
    }
}
);


答:
Replace your existing w_name = ... line with something like this:

```<code>w_name = w_temp[1].split(' ');
w_name = [w_name[0], w_name.slice(1).join(' ')];
</code>```

The ,1 you had earlier meant to stop parsing as soon as it came to the first space. This is not what you want; you want the part before the first space as one item and the part after as another. The new code parses all of the elements. After that, it sets it to an array consisting of:

The already-existing first element, and

The parts after the first element re-joined.

Title: Javascript split array

Body:
Replace your existing w_name = ... line with something like this:

w_name = w_temp[1].split(' ');
w_name = [w_name[0], w_name.slice(1).join(' ')];

The ,1 you had earlier meant to stop parsing as soon as it came to the first space. This is not what you want; you want the part before the first space as one item and the part after as another. The new code parses all of the elements. After that, it sets it to an array consisting of:

The already-existing first element, and

The parts after the first element re-joined.


问:
How can I cut the 1st letter from a cell and add to another cell in PSQL?
I have a long list, and I want to add the first letter into another cell with psql command.

A header
Another header

John
J

Lila
L

Dwane
D

Zaba
Z

Kiol
K

Longi
L

Uthe
U

Hell
H

Like this.

答:
You can use the left() postgres function to extract the first charater from a string, see the manual. Try something like this :

```<code>SELECT "A header", left("A header", 1) AS "Another header"
  FROM your_table
</code>```

Body:
You can use the left() postgres function to extract the first charater from a string, see the manual. Try something like this :

SELECT "A header", left("A header", 1) AS "Another header"
  FROM your_table


问:
Install Crypto using pip in windows
I tried with pycrypto, pycryptodome, and crypto seperately.. But it shows ModuleNotFoundError: No module named 'Crypto'

```<code>python -m venv .venv
.venv\scripts\activate
pip install pycryptodome
pip install pycrypto
pip install crypto
</code>```

Installed all the above library..

```<code>(.venv) C:\Users\Gokul\Desktop\New Meter>python send_string.py
Traceback (most recent call last):
  File "C:\Users\Gokul\Desktop\New Meter\send_string.py", line 7, in <module>
    from Crypto.Cipher import AES
ModuleNotFoundError: No module named 'Crypto'
</code>```

答:
simply deleted my existing folder of pycrpto/pycryptodome-3.11.0 located at ..\Python\Python310\Lib\site-packages (if any..), then tried

pip install pycryptodome

Title: Install Crypto using pip in windows

Body:
I tried with pycrypto, pycryptodome, and crypto seperately.. But it shows ModuleNotFoundError: No module named 'Crypto'

python -m venv .venv
.venv\scripts\activate
pip install pycryptodome
pip install pycrypto
pip install crypto

Installed all the above library..

(.venv) C:\Users\Gokul\Desktop\New Meter>python send_string.py
Traceback (most recent call last):
  File "C:\Users\Gokul\Desktop\New Meter\send_string.py", line 7, in <module>
    from Crypto.Cipher import AES
ModuleNotFoundError: No module named 'Crypto'


问:
Fixing header (navbar) in webview flutter
I am currently working on a project where I need to convert a website to a mobile app using flutter
I did it with the widget WEBVIEW but the header of the webview in my mobile is not fixed when i scroll the page the header (navBar) of my website scroll too but i want it to be fixed even if i scroll the page
this is my code :

```<code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin{

  final Completer<WebViewController> _controller =
  Completer<WebViewController>();

  late WebViewController _webViewController;

  @override
  Widget build(BuildContext context) {
    String hexString = "1b5c80";
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Welcome to Flutter',
      home: Scaffold(
        body: WebView(
          initialUrl: "https://www.journaldunet.fr/web-tech/dictionnaire-du-webmastering/1203251-blog-definition-et-acteurs/",
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController) {
            _webViewController = webViewController;
            _controller.complete(webViewController);
            },
          onPageFinished: (String url) {
            _webViewController.evaluateJavascript("javascript:(function() { " +
                "var footer = document.getElementsByTagName('footer')[0];" +
                "footer.parentNode.removeChild(footer);" +
                "})()");
            },
          gestureNavigationEnabled: true,
        ),
      ),
    );
  }

  JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'Toaster',
        onMessageReceived: (JavascriptMessage message) {
          // ignore: deprecated_member_use
          Scaffold.of(context).showSnackBar(
            SnackBar(content: Text(message.message)),
          );
        });
  }
}
</code>```

this is my mobiel app :

答:
Wrap your Scaffold with SafeArea.</p>
```<code>SafeArea(
  child: Scaffold
</code>```

Body:
I am currently working on a project where I need to convert a website to a mobile app using flutter
I did it with the widget WEBVIEW but the header of the webview in my mobile is not fixed when i scroll the page the header (navBar) of my website scroll too but i want it to be fixed even if i scroll the page
this is my code :

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin{

  final Completer<WebViewController> _controller =
  Completer<WebViewController>();

  late WebViewController _webViewController;

  @override
  Widget build(BuildContext context) {
    String hexString = "1b5c80";
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Welcome to Flutter',
      home: Scaffold(
        body: WebView(
          initialUrl: "https://www.journaldunet.fr/web-tech/dictionnaire-du-webmastering/1203251-blog-definition-et-acteurs/",
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController) {
            _webViewController = webViewController;
            _controller.complete(webViewController);
            },
          onPageFinished: (String url) {
            _webViewController.evaluateJavascript("javascript:(function() { " +
                "var footer = document.getElementsByTagName('footer')[0];" +
                "footer.parentNode.removeChild(footer);" +
                "})()");
            },
          gestureNavigationEnabled: true,
        ),
      ),
    );
  }

  JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'Toaster',
        onMessageReceived: (JavascriptMessage message) {
          // ignore: deprecated_member_use
          Scaffold.of(context).showSnackBar(
            SnackBar(content: Text(message.message)),
          );
        });
  }
}

this is my mobiel app :

Body:
Wrap your Scaffold with SafeArea.

SafeArea(
  child: Scaffold


问:
process items in Generic list/collections with Reflection
I have a generic class that I am using Reflection to pull out the properties of the type of the generic and looking for an attribute.  I am recursing into each property to do the same for each of their properties.  My issue is when I come to some sort of collection property (property that is a collection) or ICollection property.  I will not be able to cast the value returned from GetValue into a specific type (tried to cast into IEnumerable but does not work for generic IEnumerables).

Here is some code to help understand a little more:

```<code> public class NotificationMessageProcessor<T> : INotificationProcessor<T>
    {
          IList<string> availableTags = new List<string>();

          public string ReplaceNotificationTags<T>(string message, T instance)
          {

             LoadTagValues(instance);
             return ReplaceTags(message);

          }

          private string ReplaceTags(string message)
          {
             foreach (KeyValuePair<string, string> tagVal in tagValues)
             {
                 message = message.Replace(string.Format("<{0}>", tagVal.Key),     tagVal.Value);
             }
             return message;
          }

          private void LoadTagValues(object val)
          {
              Type elementType = val.GetType();
              PropertyInfo[] typeProperties = elementType.GetProperties();
              foreach (PropertyInfo prop in typeProperties)
              {

                 NotificationTag[] tags =      (NotificationTag[])prop.GetCustomAttributes(typeof(NotificationTag), false);
                if (tags != null && tags.Length > 0)
                {
                    string tagName = tags[0].TagName;
                    object propValue = prop.GetValue(val, null);
                    string propTypeString = prop.PropertyType.FullName;
                    tagName = prop.ReflectedType.Name + "." + tagName;
                    if (propValue != null)
                    {
                      tagValues.Add(tagName, propValue.ToString());
                    }

                    if (propValue != null)
                    {
                       if (!prop.PropertyType.IsPrimitive)
                       {
                         LoadTagValues(propValue);
                       }
                    }
                }
                else
                {
                   if (!prop.PropertyType.IsPrimitive)
                   {
                     object propValue = null;

                        if (prop.GetGetMethod().GetParameters().Count() == 0)
                        {
                            propValue = prop.GetValue(val, null);
                        }
                        else
                        {
                           //have a collection...need to process but do not know how many in collection....
                                propValue = prop.GetValue(val, new object[] { 0 });

                        }
                    if (propValue != null)
                    {
                        LoadTagValues(propValue);
                    }
                }
            }
        }
    }

 NotificationMessageProcessor<User> userProcessor = new NotificationMessageProcessor();
    userProcessor.ReplaceNotificationTags<User>(someMessage, instanceOfUser);
</code>```

The User object has the proper attributes

答:
You could try casting the collection type of the property to the actual type of collection?

are you doing something like the following:

```<code>List<OfObject> myCollection = new List<OfObject>;
myCollection = (List<OfObject>)objPropertyInfo.GetValue(List<ObjectHere>, Nothing);
</code>```

Hope this helps

OwnerDisplayName: CSharpAtl

ContentLicense: CC BY-SA 2.5

Body:
I have a generic class that I am using Reflection to pull out the properties of the type of the generic and looking for an attribute.  I am recursing into each property to do the same for each of their properties.  My issue is when I come to some sort of collection property (property that is a collection) or ICollection property.  I will not be able to cast the value returned from GetValue into a specific type (tried to cast into IEnumerable but does not work for generic IEnumerables).

Here is some code to help understand a little more:

 public class NotificationMessageProcessor<T> : INotificationProcessor<T>
    {
          IList<string> availableTags = new List<string>();

          public string ReplaceNotificationTags<T>(string message, T instance)
          {

             LoadTagValues(instance);
             return ReplaceTags(message);

          }

          private string ReplaceTags(string message)
          {
             foreach (KeyValuePair<string, string> tagVal in tagValues)
             {
                 message = message.Replace(string.Format("<{0}>", tagVal.Key),     tagVal.Value);
             }
             return message;
          }

          private void LoadTagValues(object val)
          {
              Type elementType = val.GetType();
              PropertyInfo[] typeProperties = elementType.GetProperties();
              foreach (PropertyInfo prop in typeProperties)
              {

                 NotificationTag[] tags =      (NotificationTag[])prop.GetCustomAttributes(typeof(NotificationTag), false);
                if (tags != null && tags.Length > 0)
                {
                    string tagName = tags[0].TagName;
                    object propValue = prop.GetValue(val, null);
                    string propTypeString = prop.PropertyType.FullName;
                    tagName = prop.ReflectedType.Name + "." + tagName;
                    if (propValue != null)
                    {
                      tagValues.Add(tagName, propValue.ToString());
                    }

                    if (propValue != null)
                    {
                       if (!prop.PropertyType.IsPrimitive)
                       {
                         LoadTagValues(propValue);
                       }
                    }
                }
                else
                {
                   if (!prop.PropertyType.IsPrimitive)
                   {
                     object propValue = null;

                        if (prop.GetGetMethod().GetParameters().Count() == 0)
                        {
                            propValue = prop.GetValue(val, null);
                        }
                        else
                        {
                           //have a collection...need to process but do not know how many in collection....
                                propValue = prop.GetValue(val, new object[] { 0 });

                        }
                    if (propValue != null)
                    {
                        LoadTagValues(propValue);
                    }
                }
            }
        }
    }

 NotificationMessageProcessor<User> userProcessor = new NotificationMessageProcessor();
    userProcessor.ReplaceNotificationTags<User>(someMessage, instanceOfUser);

The User object has the proper attributes

LastEditorDisplayName: CSharpAtl

Body:
You could try casting the collection type of the property to the actual type of collection?

are you doing something like the following:

List<OfObject> myCollection = new List<OfObject>;
myCollection = (List<OfObject>)objPropertyInfo.GetValue(List<ObjectHere>, Nothing);

Hope this helps


问:
android startActivityForResult giving error
I am new to android can someone help me please, following is the code i tried to run for scanning the barcode but it gives an error whenever i click the button it says force to close what should i do help me please.

```<code>this.btnCheck = (Button) findViewById(R.id.btnsearch);
this.btnCheck.setOnClickListener(
new OnClickListener() {
public void onClick(View v)
{
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
}
);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
Toast.makeText(this, "the scaned code is = "+ contents, Toast.LENGTH_SHORT).show();
// Handle successful scan
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
</code>```

Edit Logcat:

this is the log cat now Starting:

```<code>Intent { act=com.google.zxing.client.android.SCAN (has extras) } from pid 359 thread exiting with uncaught exception (group=0x40015560)

08-18 01:52:00.995: ERROR/AndroidRuntime(359): FATAL EXCEPTION: main

08-18 01:52:00.995: ERROR/AndroidRuntime(359): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.google.zxing.client.android.SCAN (has extras) }

08-18 01:52:00.995: ERROR/AndroidRuntime(359): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1408)
</code>```

答:
This exception probably means that the device you are trying to use doesn't have BarcodeScanner installed. You can use this code somewhere in your app to check, and prompt the user to install it form the market if they do not already have.

```<code>      //Check for Barcode scanner, if not found put up an alert that allows user to install it.
    PackageManager pm = getPackageManager();
    try {
        ApplicationInfo appInfo = pm.getApplicationInfo("com.google.zxing.client.android", 0);
    } catch (NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
         new AlertDialog.Builder(this)
            .setTitle("WARNING:")
            .setMessage("You don't have Barcode Scanner installed. Please install it.")
             .setCancelable(false)
            .setNeutralButton("Install it now", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                          Uri uri = Uri.parse("market://search?q=pname:com.google.zxing.client.android");
                          startActivity(new Intent(Intent.ACTION_VIEW, uri));
                    }
            })
            .show();
    }
</code>```

Edit: Change this line:

```<code>intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
</code>```

to this:

```<code>intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
</code>```

I highly suggest you go to this page Read it thoroughly, and then follow the two links that are underneath the code example and look at all of the code that it shows. Even if you do not understand it, it will give you some idea what is capable via Intents with the BarcodeScanner app.

Body:
I am new to android can someone help me please, following is the code i tried to run for scanning the barcode but it gives an error whenever i click the button it says force to close what should i do help me please.

this.btnCheck = (Button) findViewById(R.id.btnsearch);
this.btnCheck.setOnClickListener(
new OnClickListener() {
public void onClick(View v)
{
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
}
);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
Toast.makeText(this, "the scaned code is = "+ contents, Toast.LENGTH_SHORT).show();
// Handle successful scan
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}

Edit Logcat:

this is the log cat now Starting:

Intent { act=com.google.zxing.client.android.SCAN (has extras) } from pid 359 thread exiting with uncaught exception (group=0x40015560)

08-18 01:52:00.995: ERROR/AndroidRuntime(359): FATAL EXCEPTION: main

08-18 01:52:00.995: ERROR/AndroidRuntime(359): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.google.zxing.client.android.SCAN (has extras) }

08-18 01:52:00.995: ERROR/AndroidRuntime(359): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1408)

Body:
This exception probably means that the device you are trying to use doesn't have BarcodeScanner installed. You can use this code somewhere in your app to check, and prompt the user to install it form the market if they do not already have.

      //Check for Barcode scanner, if not found put up an alert that allows user to install it.
    PackageManager pm = getPackageManager();
    try {
        ApplicationInfo appInfo = pm.getApplicationInfo("com.google.zxing.client.android", 0);
    } catch (NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
         new AlertDialog.Builder(this)
            .setTitle("WARNING:")
            .setMessage("You don't have Barcode Scanner installed. Please install it.")
             .setCancelable(false)
            .setNeutralButton("Install it now", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                          Uri uri = Uri.parse("market://search?q=pname:com.google.zxing.client.android");
                          startActivity(new Intent(Intent.ACTION_VIEW, uri));
                    }
            })
            .show();
    }

Edit: Change this line:

intent.putExtra("SCAN_MODE", "QR_CODE_MODE");

to this:

intent.putExtra("SCAN_MODE", "PRODUCT_MODE");

I highly suggest you go to this page Read it thoroughly, and then follow the two links that are underneath the code example and look at all of the code that it shows. Even if you do not understand it, it will give you some idea what is capable via Intents with the BarcodeScanner app.


问:
Does the datetime.datetime.ctime() function return a fixed width string?
If I were to run the following code:

```<code>import datetime
dt = datetime.datetime.now()
date_str = dt.ctime()
</code>```

Will the result of len(date_str) always be the same, regardless of when I happen to run the code?  I think it will be, but I'm not certain. I looked at the datetime module reference but the relevant section says:

Return a string representing the date:

```<code>>>> from datetime import date
>>> date(2002, 12, 4).ctime()
'Wed Dec  4 00:00:00 2002'
</code>```

d.ctime() is equivalent to:

```<code>time.ctime(time.mktime(d.timetuple()))
</code>```

on platforms where the native C ctime() function (which time.ctime() invokes, but which date.ctime() does not invoke) conforms to the C standard.

But looking at the article on cppreference.com, the answer is less than clear to me. I did find a reference here which suggests that it will be a 24-character wide string, but I was hoping for a more official source or reference if possible. It's possible that I didn't delve far enough into the C-standard to divine the answer.

Also, based on that quote, does that mean the behavior might be platform-dependent?  Or is it likely to be generally uniform outside of niche operating systems?

(yes I know that I can manually format to fixed-width, but I want to know whether the built-in one already is that way)

答:
Well, cppreference clearly states that the C standard requires ctime to return a 25 characters strings ending with a newline.

The resulting string has the following format:

```<code>Www Mmm dd hh:mm:ss yyyy\n
</code>```

...

The function does not support localization.

The doc for the time module states (emphasize mine):

Most of the functions defined in this module call platform C library functions with the same name.

A ctime is required by C standard, it should be available on any platform. So it should be always used by time.ctime.

Let us go on:

time.ctime([secs])

...

If secs is not provided or None, the current time as returned by time() is used. ctime(secs) is equivalent to asctime(localtime(secs)). Locale information is not used by ctime().

and

time.asctime([t])

Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string of the following form: 'Sun Jun 20 23:21:05 1993'. The day field is two characters long and is space padded if the day is a single digit, e.g.: 'Wed Jun  9 04:26:40 1993'.
...
Note:
Unlike the C function of the same name, asctime() does not add a trailing newline.

So instead of the 25 characters string returned by the C function, the ctime or asctime functions of the Python standard library time module return a non localized 24 characters string.

So if you use CPython, and except on a specific system where the C standard library would be non conformant, you can trust time.ctime to always return a 24 character string.

And even if you use a different implementation (Jython, PyPy, etc.) the Python standard library documentation states that this non localized 24 characters string should be returned. So I cannot imagine a system returning a different size...

Body:
If I were to run the following code:

import datetime
dt = datetime.datetime.now()
date_str = dt.ctime()

Will the result of len(date_str) always be the same, regardless of when I happen to run the code?  I think it will be, but I'm not certain. I looked at the datetime module reference but the relevant section says:

Return a string representing the date:

>>> from datetime import date
>>> date(2002, 12, 4).ctime()
'Wed Dec  4 00:00:00 2002'

d.ctime() is equivalent to:

time.ctime(time.mktime(d.timetuple()))

on platforms where the native C ctime() function (which time.ctime() invokes, but which date.ctime() does not invoke) conforms to the C standard.

But looking at the article on cppreference.com, the answer is less than clear to me. I did find a reference here which suggests that it will be a 24-character wide string, but I was hoping for a more official source or reference if possible. It's possible that I didn't delve far enough into the C-standard to divine the answer.

Also, based on that quote, does that mean the behavior might be platform-dependent?  Or is it likely to be generally uniform outside of niche operating systems?

(yes I know that I can manually format to fixed-width, but I want to know whether the built-in one already is that way)

Body:
Well, cppreference clearly states that the C standard requires ctime to return a 25 characters strings ending with a newline.

The resulting string has the following format:

Www Mmm dd hh:mm:ss yyyy\n

...

The function does not support localization.

The doc for the time module states (emphasize mine):

Most of the functions defined in this module call platform C library functions with the same name.

A ctime is required by C standard, it should be available on any platform. So it should be always used by time.ctime.

Let us go on:

time.ctime([secs])

...

If secs is not provided or None, the current time as returned by time() is used. ctime(secs) is equivalent to asctime(localtime(secs)). Locale information is not used by ctime().

and

time.asctime([t])

Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string of the following form: 'Sun Jun 20 23:21:05 1993'. The day field is two characters long and is space padded if the day is a single digit, e.g.: 'Wed Jun  9 04:26:40 1993'.
...
Note:
Unlike the C function of the same name, asctime() does not add a trailing newline.

So instead of the 25 characters string returned by the C function, the ctime or asctime functions of the Python standard library time module return a non localized 24 characters string.

So if you use CPython, and except on a specific system where the C standard library would be non conformant, you can trust time.ctime to always return a 24 character string.

And even if you use a different implementation (Jython, PyPy, etc.) the Python standard library documentation states that this non localized 24 characters string should be returned. So I cannot imagine a system returning a different size...


问:
App Engine datastore paging - previous page
I'm trying to create a paging mechanism to page through a query. Going forward is not an issue. Going to a previous page seems to be non-trivial though.

What I have so far is this (why do I have the feeling that it should be simpler?):

```<code>cursor_urlsafe = self.request.get('cursor', None)
rev = bool(self.request.get('rev', None))
cursor = ndb.Cursor(urlsafe=cursor_urlsafe)
if rev:
    next_query = Shot.query(Shot.schedule_key == schedule.key).order(Shot.date_created)
    cursor = cursor.reversed()
else:
    next_query = Shot.query(Shot.schedule_key == schedule.key).order(-Shot.date_created)

shots, next_cursor, more = next_query.fetch_page(PAGE_LENGTH, start_cursor=cursor)

if rev:
    shots.sort(key=lambda x: -x.date_created_epoch)

next_cursor_url_safe = next_cursor.urlsafe() if next_cursor else None
template_params = {
    'shots': shots,
    'next_cursor': next_cursor_url_safe,
    'prev_cursor': next_cursor_url_safe if cursor_urlsafe else None
}
</code>```

and on the client side:

```<code><a href="/schedule/{{ s.id }}?cursor={{ prev_cursor }}&rev=true">Previous</a><br>
<a href="/schedule/{{ s.id }}?cursor={{ next_cursor }}">Next</a>
</code>```

This sort of works. The only problem is that when the user "changes direction" (pages back) it brings him to the page he is on again, and only after another click on previous it goes to the previous page.

So if click, Previous and then Next I remain on the same page all the time.

Please advise.

答:
One solution is to have the client keep a list of cursors as they move forward. When they page backwards, use the previous cursor in the list. Cursors on the backend can be exported to a string. In Java, you use the toUrlSafe method. There's probably an equivalent for Python.

When using the previous cursor, I recommend removing the last cursor in the list so that a fresh instance of it gets created when the user pages forward again. Then again, that depends on how often the data will change. If the data seldom changes, you can skip removing cursors from the list and just use the cached ones instead to speed up time on the backend.

Body:
I'm trying to create a paging mechanism to page through a query. Going forward is not an issue. Going to a previous page seems to be non-trivial though.

What I have so far is this (why do I have the feeling that it should be simpler?):

cursor_urlsafe = self.request.get('cursor', None)
rev = bool(self.request.get('rev', None))
cursor = ndb.Cursor(urlsafe=cursor_urlsafe)
if rev:
    next_query = Shot.query(Shot.schedule_key == schedule.key).order(Shot.date_created)
    cursor = cursor.reversed()
else:
    next_query = Shot.query(Shot.schedule_key == schedule.key).order(-Shot.date_created)

shots, next_cursor, more = next_query.fetch_page(PAGE_LENGTH, start_cursor=cursor)

if rev:
    shots.sort(key=lambda x: -x.date_created_epoch)

next_cursor_url_safe = next_cursor.urlsafe() if next_cursor else None
template_params = {
    'shots': shots,
    'next_cursor': next_cursor_url_safe,
    'prev_cursor': next_cursor_url_safe if cursor_urlsafe else None
}

and on the client side:

Previous

Next

This sort of works. The only problem is that when the user "changes direction" (pages back) it brings him to the page he is on again, and only after another click on previous it goes to the previous page.

So if click, Previous and then Next I remain on the same page all the time.

Please advise.


问:
Using shell variable to select awk column identifier
This one works:

```<code>temp=($(awk -F" "  '$2 == 84' "$1".db))
</code>```

This one does not (fieldnumber stores the column i wish to search, and val stores the value I'm searching for):

```<code>temp=($(awk -F" " -v column="$""$field_number" -v val="$3" '{ if(column == val) print $0;}' "$1".db))
</code>```

I am trying to manipulate the awk command based on command line inputs within shell script:
./dr.sh cop4342 exam1 84 (84 is the value to be searched for) (exam1 is used within the shell script to find the column number)

答:
This is terribly unclear, but I guess you are looking for

```<code>temp=($(awk -F " " -v column="$field_number" \
            -v val="$3" '{ if($column == val) print $0;}' "$1".db))
</code>```

which of course can be simplified to just

```<code>temp=($(awk -v column="$field_number" \
            -v val="$3" '$column == val' "$1".db))
</code>```

Body:
This one works:

temp=($(awk -F" "  '$2 == 84' "$1".db))

This one does not (fieldnumber stores the column i wish to search, and val stores the value I'm searching for):

temp=($(awk -F" " -v column="$""$field_number" -v val="$3" '{ if(column == val) print $0;}' "$1".db))

I am trying to manipulate the awk command based on command line inputs within shell script:
./dr.sh cop4342 exam1 84 (84 is the value to be searched for) (exam1 is used within the shell script to find the column number)

Body:
This is terribly unclear, but I guess you are looking for

temp=($(awk -F " " -v column="$field_number" \
            -v val="$3" '{ if($column == val) print $0;}' "$1".db))

which of course can be simplified to just

temp=($(awk -v column="$field_number" \
            -v val="$3" '$column == val' "$1".db))


答:
```<code>export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));
</code>```

is equal to:

```<code>export const orderArr = (arr: any[], key: string) => {
    return arr.sort((a, b) => {
        if (a[key] > b[key]) {
            return 1;
        } else if (a[key] === b[key]) {
            if (a[key] > b[key]) {
                return 1;
            } else {
                return -1;
            }
        } else {
            return -1;
        }
    })
}
</code>```

I'm strongly believe it's not necessary to use 3+ level nested ternary operators anywhere 'cause it's huge code readability sacrifice for no reason.

Feel free to rewrite method to common if/else or switch statements to keep your code clear.

Title: Please do I interprete this ternary operator?

Body:
export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));

is equal to:

export const orderArr = (arr: any[], key: string) => {
    return arr.sort((a, b) => {
        if (a[key] > b[key]) {
            return 1;
        } else if (a[key] === b[key]) {
            if (a[key] > b[key]) {
                return 1;
            } else {
                return -1;
            }
        } else {
            return -1;
        }
    })
}

I'm strongly believe it's not necessary to use 3+ level nested ternary operators anywhere 'cause it's huge code readability sacrifice for no reason.

Feel free to rewrite method to common if/else or switch statements to keep your code clear.


问:
Kubernetes - read arguments "args" properties from .INI file or configMap
I have kubernetes file with arguments that I am propagating through the args. Everything works OK!
Instead of the args can I read the configuration from some .ini or properties file or configMap ? I cannot find example for using the values from properties file or configMap instead of the args properties.
Or what will be the proposed best approach how these values should be read and how I should modify my deployment YAML.
Thanks!

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: ads
spec:
  replicas: 1
  template:
    metadata:
      name: ads
    spec:
      containers:
      - name: ads
        image: repo/ads:test1
        #args:
        args: ["-web_server", "10.1.1.1",
               "-web_name", "WEB_Test1",
               "-server_name", "ads"]
  selector:
    matchLabels:
      app: ads
</code>```

答: Sure you can, here's the official K8s example how to store properties in ConfigMap and how to access them in your container. If this document doesn't meet your requirement, do update your question with the reason and your exact expectation.</p>

Body:
I have kubernetes file with arguments that I am propagating through the args. Everything works OK!
Instead of the args can I read the configuration from some .ini or properties file or configMap ? I cannot find example for using the values from properties file or configMap instead of the args properties.
Or what will be the proposed best approach how these values should be read and how I should modify my deployment YAML.
Thanks!

apiVersion: apps/v1
kind: Deployment
metadata:
  name: ads
spec:
  replicas: 1
  template:
    metadata:
      name: ads
    spec:
      containers:
      - name: ads
        image: repo/ads:test1
        #args:
        args: ["-web_server", "10.1.1.1",
               "-web_name", "WEB_Test1",
               "-server_name", "ads"]
  selector:
    matchLabels:
      app: ads