答:
Here's an approach that creates the target and then uses a join to add in the visits information. The ifelse statement just helps up clean up the NA from the merge. You could also leave them in and replace them with := in the new data.table.

```<code>target <- data.table(
  customer = rep(unique(df$customer), each = 24),
  hour = 0:23)

df_join <- df[target, on = c("customer", "hour"),
   .(customer, hour, visits = ifelse(is.na(visits), 0, visits))
   ]

all.equal(df_expected, df_join)

</code>```

Edit:

This addresses the request to include the location_id column. One way to do this is with by=location in the creation of the target. I've also added in some of the code from chinsoon12's answer.

```<code>target <- df[ , .("customer" = rep(unique(customer), each = 24L),
                  "hour" = rep(0L:23L, times = uniqueN(customer))),
              by = location_id]

df_join <- df[target, on = .NATURAL,
              .(customer, location_id, hour, visits = fcoalesce(visits, 0))]

all.equal(df_expected, df_join)
</code>```

Title: how to insert sequential rows in data.table in R (Example given)?

Body:
df is data.table and df_expected is desired data.table . I want to add hour column from 0 to 23 and visits value would be filled as 0 for hours newly added .

df<-data.table(customer=c("x","x","x","y","y"),location_id=c(1,1,1,2,3),hour=c(2,5,7,0,4),visits=c(40,50,60,70,80))

df_expected<-data.table(customer=c("x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x","x",
                               "y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y",
                               "y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y","y"),

                    location_id=c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
                                  2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
                                  3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3),

                    hour=c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,
                           0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,
                           0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23),

                    visits=c(0,0,40,0,0,50,0,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
                             70,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
                             0,0,0,0,80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0))

This is what I tried to obtain my result , but it did not work

df1<-df[,':='(hour=seq(0:23)),by=(customer)]
Error in `[.data.table`(df, , `:=`(hour = seq(0L:23L)), by = (customer)) :
Type of RHS ('integer') must match LHS ('double'). To check and coerce would impact
performance too much for the fastest cases. Either change the type of the target column, or
coerce the RHS of := yourself (e.g. by using 1L instead of 1)

Body:
Here's an approach that creates the target and then uses a join to add in the visits information. The ifelse statement just helps up clean up the NA from the merge. You could also leave them in and replace them with := in the new data.table.

target <- data.table(
  customer = rep(unique(df$customer), each = 24),
  hour = 0:23)

df_join <- df[target, on = c("customer", "hour"),
   .(customer, hour, visits = ifelse(is.na(visits), 0, visits))
   ]

all.equal(df_expected, df_join)

Edit:

This addresses the request to include the location_id column. One way to do this is with by=location in the creation of the target. I've also added in some of the code from chinsoon12's answer.

target <- df[ , .("customer" = rep(unique(customer), each = 24L),
                  "hour" = rep(0L:23L, times = uniqueN(customer))),
              by = location_id]

df_join <- df[target, on = .NATURAL,
              .(customer, location_id, hour, visits = fcoalesce(visits, 0))]

all.equal(df_expected, df_join)


来源: stackexchange

问:
Django REST framework - Serializer relations User.username
Im working on a django project, and I have a model that looks like this:

```<code>class Comment(models.Model):
    user            = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,on_delete=models.CASCADE)
    slug            = models.SlugField(unique=True,null=True, blank=True)
    content_type    = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id       = models.PositiveIntegerField()
    content_object  = GenericForeignKey('content_type', 'object_id')
    parent          = models.ForeignKey("self", null=True, blank=True,on_delete=models.CASCADE)
    content         = models.TextField()
    timestamp       = models.DateTimeField(auto_now_add=True)

    objects = CommentManager()

    def __str__(self):
        return str(self.user.username)
</code>```

I use this serializer:

```<code>class CommentDetailSerializer(ModelSerializer):
    user = SerializerMethodField()
    replies = SerializerMethodField()
    class Meta:
        model = Comment
        fields = [
            'user',
            'content',
            'replies',
            'timestamp'
        ]
    def get_user(self,obj):
        return str(obj.user.username)

    def get_replies(self,obj):
        if obj.is_parent:
            return CommentChildSerializer(obj.children(),many=True).data
</code>```

for this view:

```<code>class CommentDetailApiView(RetrieveAPIView):
    queryset = Comment.objects.all()
    serializer_class = CommentDetailSerializer
    lookup_field = 'slug'
</code>```

here is the PostSerializer I use,

```<code>class PostSerializer(ModelSerializer):
    user = SerializerMethodField()
    comments = SerializerMethodField()
    class Meta:
        model = Post
        fields = [
            'user',
            'title',
            'content',
            'comments'
        ]
    def get_user(self,obj):
        return str(obj.user.username)

    def get_comments(self,obj):
        comments_qs = Comment.objects.filter_by_instance(obj)
        comments = CommentSerializer(comments_qs, many=True).data
        return comments
</code>```

this is what I get in the PostDetailAPIView:

```<code>{
    "user": "abc",
    "title": "blabla",
    "content": "bla",
    "comments": [
        {
            "user": 1,
            "content": "hey",
            "timestamp": "2020-02-18T00:07:29.932850Z"
        }
    ]
}
</code>```

How do I get the comment user username instead of its id?

I get the username of the comment user only in the CommentDetailApiView.

Thank you

答:
I added the get_user method to the CommentSerializer and now it works:

```<code>class CommentSerializer(serializers.ModelSerializer):
    user = SerializerMethodField()
    class Meta:
        model = Comment
        fields = [
            'user',
            'content',
            'timestamp'
        ]
    def get_user(self,obj):
        return str(obj.user.username)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Im working on a django project, and I have a model that looks like this:

class Comment(models.Model):
    user            = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,on_delete=models.CASCADE)
    slug            = models.SlugField(unique=True,null=True, blank=True)
    content_type    = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id       = models.PositiveIntegerField()
    content_object  = GenericForeignKey('content_type', 'object_id')
    parent          = models.ForeignKey("self", null=True, blank=True,on_delete=models.CASCADE)
    content         = models.TextField()
    timestamp       = models.DateTimeField(auto_now_add=True)

    objects = CommentManager()

    def __str__(self):
        return str(self.user.username)

I use this serializer:

class CommentDetailSerializer(ModelSerializer):
    user = SerializerMethodField()
    replies = SerializerMethodField()
    class Meta:
        model = Comment
        fields = [
            'user',
            'content',
            'replies',
            'timestamp'
        ]
    def get_user(self,obj):
        return str(obj.user.username)

    def get_replies(self,obj):
        if obj.is_parent:
            return CommentChildSerializer(obj.children(),many=True).data

for this view:

class CommentDetailApiView(RetrieveAPIView):
    queryset = Comment.objects.all()
    serializer_class = CommentDetailSerializer
    lookup_field = 'slug'

here is the PostSerializer I use,

class PostSerializer(ModelSerializer):
    user = SerializerMethodField()
    comments = SerializerMethodField()
    class Meta:
        model = Post
        fields = [
            'user',
            'title',
            'content',
            'comments'
        ]
    def get_user(self,obj):
        return str(obj.user.username)

    def get_comments(self,obj):
        comments_qs = Comment.objects.filter_by_instance(obj)
        comments = CommentSerializer(comments_qs, many=True).data
        return comments

this is what I get in the PostDetailAPIView:

{
    "user": "abc",
    "title": "blabla",
    "content": "bla",
    "comments": [
        {
            "user": 1,
            "content": "hey",
            "timestamp": "2020-02-18T00:07:29.932850Z"
        }
    ]
}

How do I get the comment user username instead of its id?

I get the username of the comment user only in the CommentDetailApiView.

Thank you

Body:
I added the get_user method to the CommentSerializer and now it works:

class CommentSerializer(serializers.ModelSerializer):
    user = SerializerMethodField()
    class Meta:
        model = Comment
        fields = [
            'user',
            'content',
            'timestamp'
        ]
    def get_user(self,obj):
        return str(obj.user.username)


问:
How to change variable from another page Ionic4
I'm creating a simple tabs-based app in Ionic4, and I want to change a variable in the main tabs page, where tabs switcher is shown, from the first tab, and I want to change this variable, when the scrolling position is on the right level on the first tab ionic content. The question is, how to change variable in tabs.page.ts from tab1.page.ts. I have info about the current day in html of tabs page, and it should change according to scroll position.

tabs.page.ts file
(I want to change current_day, because it's in my html file)

import { Component ,OnInit} from '@angular/core';
import {formatDate} from '@angular/common';
import { Storage } from '@ionic/storage';
import { DatabaseService }  from '../database.service'
import {NavController} from "@ionic/angular"
@Component({
  selector: 'app-tabs',
  templateUrl: 'tabs.page.html',
  styleUrls: ['tabs.page.scss']
})
export class TabsPage {
  constructor() {
  }
  last_text:String = "";
  cur_text:String = "";
  som = 0
  beginning = 1564617600 * 1000
  date:any = new Date()
  current_day:String = String(Math.floor((new Date(this.date.getTime() - this.beginning).getTime()+3 * 60*60*1000) / 1000 / 60 / 60 / 24)+1)
  lasts = new Date(this.date.getTime() - this.beginning)
  timerow:String = this.lasts.getHours()+":"+this.lasts.getMinutes()
  sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
  }
  tonorm(str:String){
    let dobav;
    if (str.length == 1){
        dobav = "0"
    }
    else{
        dobav = ""
    }
    return dobav+str
  }
  iter(){
    this.date = new Date()
    this.current_day = String(Math.floor((new Date(this.date.getTime() - this.beginning).getTime()+3 * 60*60*1000) / 1000 / 60 / 60 / 24)+1)
    this.lasts = new Date(this.date.getTime() - this.beginning)
    this.timerow = this.tonorm(String(23-this.lasts.getHours()))+":"+this.tonorm(String(60 - this.lasts.getMinutes()))
  }
  updater(){
    this.iter()
    this.sleep(1000);

    }
  }
```

<p>in tab1.page.ts code</p>

<pre class="lang-js prettyprint-override"><code>onPageScroll(event) {
        this.scrlpos = event.detail.scrollTop
        if (this.scrlpos >= 500){
            //change that variable
        }
    }
</code>```

tabs.page.html

<ion-tabs>
  <ion-list-header no-border slot="top">
    <ion-label position="stacked" class="my-label">День {{current_day}}</ion-label>
    <ion-label position="stacked" class="my-label">{{timerow}}</ion-label>
  </ion-list-header>
  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="tab1">
      <ion-icon name="book"></ion-icon>
      <ion-label>текст</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tab2">
      <ion-icon name="star"></ion-icon>
      <ion-label>избранное</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tab3">
      <ion-icon name="settings"></ion-icon>
      <ion-label>настройки</ion-label>
    </ion-tab-button>
  </ion-tab-bar>
  {{updater()}}
</ion-tabs>

```

答:
I'll probably get slammed for this, but another different way you can do it is to have a "globals.ts" file that just handles variables that need to be accessed from multiple pages.

Just import that globals file on each page that needs those variables.

```<code>import { GlobalsProvider } from '../providers/globals/globals';

constructor(public platform: Platform,
      public globalvals: GlobalsProvider)
</code>```

Then you can call them on each page...

```<code>this.globalvals.setting = true;
</code>```

Body:
I'm creating a simple tabs-based app in Ionic4, and I want to change a variable in the main tabs page, where tabs switcher is shown, from the first tab, and I want to change this variable, when the scrolling position is on the right level on the first tab ionic content. The question is, how to change variable in tabs.page.ts from tab1.page.ts. I have info about the current day in html of tabs page, and it should change according to scroll position.

tabs.page.ts file
(I want to change current_day, because it's in my html file)

import { Component ,OnInit} from '@angular/core';
import {formatDate} from '@angular/common';
import { Storage } from '@ionic/storage';
import { DatabaseService }  from '../database.service'
import {NavController} from "@ionic/angular"
@Component({
  selector: 'app-tabs',
  templateUrl: 'tabs.page.html',
  styleUrls: ['tabs.page.scss']
})
export class TabsPage {
  constructor() {
  }
  last_text:String = "";
  cur_text:String = "";
  som = 0
  beginning = 1564617600 * 1000
  date:any = new Date()
  current_day:String = String(Math.floor((new Date(this.date.getTime() - this.beginning).getTime()+3 * 60*60*1000) / 1000 / 60 / 60 / 24)+1)
  lasts = new Date(this.date.getTime() - this.beginning)
  timerow:String = this.lasts.getHours()+":"+this.lasts.getMinutes()
  sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
  }
  tonorm(str:String){
    let dobav;
    if (str.length == 1){
        dobav = "0"
    }
    else{
        dobav = ""
    }
    return dobav+str
  }
  iter(){
    this.date = new Date()
    this.current_day = String(Math.floor((new Date(this.date.getTime() - this.beginning).getTime()+3 * 60*60*1000) / 1000 / 60 / 60 / 24)+1)
    this.lasts = new Date(this.date.getTime() - this.beginning)
    this.timerow = this.tonorm(String(23-this.lasts.getHours()))+":"+this.tonorm(String(60 - this.lasts.getMinutes()))
  }
  updater(){
    this.iter()
    this.sleep(1000);

    }
  }

in tab1.page.ts code

onPageScroll(event) {
        this.scrlpos = event.detail.scrollTop
        if (this.scrlpos >= 500){
            //change that variable
        }
    }

tabs.page.html

<ion-tabs>
  <ion-list-header no-border slot="top">
    <ion-label position="stacked" class="my-label">День {{current_day}}</ion-label>
    <ion-label position="stacked" class="my-label">{{timerow}}</ion-label>
  </ion-list-header>
  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="tab1">
      <ion-icon name="book"></ion-icon>
      <ion-label>текст</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tab2">
      <ion-icon name="star"></ion-icon>
      <ion-label>избранное</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tab3">
      <ion-icon name="settings"></ion-icon>
      <ion-label>настройки</ion-label>
    </ion-tab-button>
  </ion-tab-bar>
  {{updater()}}
</ion-tabs>

Body:
I'll probably get slammed for this, but another different way you can do it is to have a "globals.ts" file that just handles variables that need to be accessed from multiple pages.

Just import that globals file on each page that needs those variables.

import { GlobalsProvider } from '../providers/globals/globals';

constructor(public platform: Platform,
      public globalvals: GlobalsProvider)

Then you can call them on each page...

this.globalvals.setting = true;


问:
Error in Getting newly inserted record through trigger-PLSQL
I am trying to create a trigger on EMP table which will audit insertions in EMP_AUDIT table and send mail to respective empno. The thing I am not getting is to get newly inserted record in CSV attachment that is being generated in v_block_query. I want to get that data basis of :new.FIELD_NAME but it's throwing the error:

ORA-01008: not all variables bound ORA-06512: at
  "SCOTT.EMP_AFTER_INSERT", line 18 ORA-04088: error during execution of
  trigger 'SCOTT.EMP_AFTER_INSERT'

```<code> create or replace TRIGGER emp_after_insert
                              AFTER INSERT
                                   ON emp
                                   FOR EACH ROW
                                DECLARE
        v_block_qry VARCHAR2(3000);
                          v_block_row VARCHAR2(6000);
                        TYPE bl_cur IS REF CURSOR;
                       v_result bl_cur;
                       v_rowcount NUMBER;
                   v_attachment CLOB;
           v_username varchar2(10);
            v_no number(4);
                v_name varchar2(10);
    v_email varchar2(30);
    v_subj varchar2(30);
             BEGIN
          insert into emp_audit(id,name,insertion_date) values(:new.empno,:new.ename,sysdate);
            dbms_output.put_line('inserted'||:new.empno);
               v_attachment := '"COL1", "COL2"' || CHR(13) || CHR(10);
                      v_block_qry := 'SELECT ''"'' || new.empno || ''", "'' || new.ename || ''", "'' || insertion_date ||''"'' AS ROWTXT FROM emp_audit ';
                      OPEN v_result FOR v_block_qry;
                        LOOP
                        v_rowcount := v_result%ROWCOUNT;
                        FETCH v_result INTO v_block_row;
                          EXIT WHEN v_result%NOTFOUND;
                          v_attachment := v_attachment || v_block_row || chr(13) || chr(10);
                        END LOOP;
                      CLOSE v_result;

                       dbms_output.put_line(v_attachment);
     select email into v_email from dept_email where deptno=:new.empno;
     dbms_output.put_line(v_email);
        v_subj:= 'MAIL_SUBJECT ' || TO_CHAR(TRUNC(SYSDATE-1), 'YYYY-MM-DD');
              UTL_MAIL.send_attach_varchar2(sender => 'abc@gmail.com',
              recipients        => v_email,
              subject           => 'mail testing',
              message           =>  'current record',
             mime_type         => 'text/html; charset=us-ascii', -- send html e-mail
             attachment        => v_attachment,
             att_inline        => FALSE,
             att_filename      => 'Change_Report' || TO_CHAR(TRUNC(SYSDATE-1), 'YYYY-MM-DD') || '.csv');

                 END;
</code>```

Please Help. Thanks in advance

答:
```<code>v_block_qry := 'SELECT ''"'' || BRANCH_NUMB || ''", "'' || LOAN_CODE || ''", "'' || LOAN_PRODUCT_NUMB || ''"
               , "'' || BRM_NUM || "'', "'' || CURR_CODE || "'', "'' || NAME_DESN || ''", "'' || CNIC_NUMB || ''"
               , "'' || PRINCIPAL_NEW || ''", "'' || AMOUNT_APPLIED_NEW || ''", "'' || ACCT_BASC || ''", "'' || ACCT_SFIX || ''"
               , "'' || DATE_ADDED_NEW || ''", "'' || DATE_DUE_NEW || ''", "'' || B_STATUS || ''", "'' || S_STATUS || ''", "'' || DISB_TOTAL_AMOUNT_NEW || ''"''
               , "'' || OUTSTANDING_PRINCIPAL_NEW || ''", "'' || GROUPBR_NEW || ''", "'' || INSERTED_DATE || ''"''

               AS ROWTXT FROM SMFB.LMFLOANSNEW where branch_numb='||:new.branch_code;
</code>```

from keyword not found where expected. This is at live environment. Previous code was on my DB

Body:
I am trying to create a trigger on EMP table which will audit insertions in EMP_AUDIT table and send mail to respective empno. The thing I am not getting is to get newly inserted record in CSV attachment that is being generated in v_block_query. I want to get that data basis of :new.FIELD_NAME but it's throwing the error:

ORA-01008: not all variables bound ORA-06512: at
  "SCOTT.EMP_AFTER_INSERT", line 18 ORA-04088: error during execution of
  trigger 'SCOTT.EMP_AFTER_INSERT'

 create or replace TRIGGER emp_after_insert
                              AFTER INSERT
                                   ON emp
                                   FOR EACH ROW
                                DECLARE
        v_block_qry VARCHAR2(3000);
                          v_block_row VARCHAR2(6000);
                        TYPE bl_cur IS REF CURSOR;
                       v_result bl_cur;
                       v_rowcount NUMBER;
                   v_attachment CLOB;
           v_username varchar2(10);
            v_no number(4);
                v_name varchar2(10);
    v_email varchar2(30);
    v_subj varchar2(30);
             BEGIN
          insert into emp_audit(id,name,insertion_date) values(:new.empno,:new.ename,sysdate);
            dbms_output.put_line('inserted'||:new.empno);
               v_attachment := '"COL1", "COL2"' || CHR(13) || CHR(10);
                      v_block_qry := 'SELECT ''"'' || new.empno || ''", "'' || new.ename || ''", "'' || insertion_date ||''"'' AS ROWTXT FROM emp_audit ';
                      OPEN v_result FOR v_block_qry;
                        LOOP
                        v_rowcount := v_result%ROWCOUNT;
                        FETCH v_result INTO v_block_row;
                          EXIT WHEN v_result%NOTFOUND;
                          v_attachment := v_attachment || v_block_row || chr(13) || chr(10);
                        END LOOP;
                      CLOSE v_result;

                       dbms_output.put_line(v_attachment);
     select email into v_email from dept_email where deptno=:new.empno;
     dbms_output.put_line(v_email);
        v_subj:= 'MAIL_SUBJECT ' || TO_CHAR(TRUNC(SYSDATE-1), 'YYYY-MM-DD');
              UTL_MAIL.send_attach_varchar2(sender => 'abc@gmail.com',
              recipients        => v_email,
              subject           => 'mail testing',
              message           =>  'current record',
             mime_type         => 'text/html; charset=us-ascii', -- send html e-mail
             attachment        => v_attachment,
             att_inline        => FALSE,
             att_filename      => 'Change_Report' || TO_CHAR(TRUNC(SYSDATE-1), 'YYYY-MM-DD') || '.csv');

                 END;

Please Help. Thanks in advance

Body:
v_block_qry := 'SELECT ''"'' || BRANCH_NUMB || ''", "'' || LOAN_CODE || ''", "'' || LOAN_PRODUCT_NUMB || ''"
               , "'' || BRM_NUM || "'', "'' || CURR_CODE || "'', "'' || NAME_DESN || ''", "'' || CNIC_NUMB || ''"
               , "'' || PRINCIPAL_NEW || ''", "'' || AMOUNT_APPLIED_NEW || ''", "'' || ACCT_BASC || ''", "'' || ACCT_SFIX || ''"
               , "'' || DATE_ADDED_NEW || ''", "'' || DATE_DUE_NEW || ''", "'' || B_STATUS || ''", "'' || S_STATUS || ''", "'' || DISB_TOTAL_AMOUNT_NEW || ''"''
               , "'' || OUTSTANDING_PRINCIPAL_NEW || ''", "'' || GROUPBR_NEW || ''", "'' || INSERTED_DATE || ''"''

               AS ROWTXT FROM SMFB.LMFLOANSNEW where branch_numb='||:new.branch_code;

from keyword not found where expected. This is at live environment. Previous code was on my DB


问:
Unknown initial character set index '255' received from server
During attempt to create HibernateSession application fails with exception:

Caused by: java.sql.SQLException: Unknown initial character set index
  '255' received from server. Initial client character set can be forced
  via the 'characterEncoding' property.     at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)    at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)     at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)

I found one possible solution here but unfortunately I do not have access to DB server thus I cannot change its configuration.
So please pay attention that this is not a duplicate, because suggested solution was provided for the DB server changes and in my case I don't have such access.

Is it any chance to fix this issue on client side? Below you can find my pom.xml file and java code where I create session.

```<code>import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }
}
</code>```

And my pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    ...
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.5.Final</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.9.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
</code>```

答:
This Works for me!     </p>

```<code> <property name="JDBC.ConnectionURL"  value="jdbc:mysql://localhost:3306/empdemo?characterEncoding=utf8"></property>
</code>```

Body:
During attempt to create HibernateSession application fails with exception:

Caused by: java.sql.SQLException: Unknown initial character set index
  '255' received from server. Initial client character set can be forced
  via the 'characterEncoding' property.     at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)    at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)     at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)

I found one possible solution here but unfortunately I do not have access to DB server thus I cannot change its configuration.
So please pay attention that this is not a duplicate, because suggested solution was provided for the DB server changes and in my case I don't have such access.

Is it any chance to fix this issue on client side? Below you can find my pom.xml file and java code where I create session.

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }
}

And my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    ...
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.5.Final</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.9.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

Body:
This Works for me!

 <property name="JDBC.ConnectionURL"  value="jdbc:mysql://localhost:3306/empdemo?characterEncoding=utf8"></property>


问:
Export bitfield to an array
I've declared this bit field. What I am trying to do is to get the whole value of the bitfield in binary and convert it into an array so I can use the index and address every '1' value.

```<code>union{
    struct shape{
        uint8_t p0 : 1;
        uint8_t p1 : 1;
        uint8_t p2 : 1;
        uint8_t p3 : 1;
        uint8_t p4 : 1;
        uint8_t p5 : 1;
        uint8_t p6 : 1;
        uint8_t p7 : 1;
    };
    uint8_t row;
}rows[8*2+4];
</code>```

what I am trying to do is to export the bitfield to have it an array like uint8_t tab[8] = {0,1,1,0,0,1,0,1};

Is that even possible? Any tips?
Thanks in advance

答:
If you want to just export your bitfields, it is possible with user-defined conversion from your union to std::array. Note that, it is just possible to read bits( not set ).

```<code>union{
    struct shape{
        uint8_t p0 : 1;
        uint8_t p1 : 1;
        uint8_t p2 : 1;
        uint8_t p3 : 1;
        uint8_t p4 : 1;
        uint8_t p5 : 1;
        uint8_t p6 : 1;
        uint8_t p7 : 1;
    } bits;

    operator std::array<bool , 8>(){
        std::array<bool , 8> exported_array;
        exported_array[ 0 ] = bits.p0;
        exported_array[ 1 ] = bits.p1;
        exported_array[ 2 ] = bits.p2;
        exported_array[ 3 ] = bits.p3;
        exported_array[ 4 ] = bits.p4;
        exported_array[ 5 ] = bits.p5;
        exported_array[ 6 ] = bits.p6;
        exported_array[ 7 ] = bits.p7;

        return exported_array;
    }

    uint8_t row;
} rows[8*2+4];

int main()
{
    rows[0].row = static_cast<uint8_t>( 643211 );
    std::array< bool , 8 > data = rows[ 0 ];

    for ( auto bit : data )
        std::cout << static_cast<int>( bit );
}
</code>```

But I don't suggest to use this method. As far as i understand, you read a value from somewhere and you want to access/manipulate the bits like an array. std::bitset is a good option to do that.

Possible implementation like this :

```<code>#include <cstdint>
#include <iostream>
#include <bitset>

int main()
{
    uint8_t data_comes_from_somewhere = 0b01001001;
    std::string data_comes_from_somewhere_as_string { "11101001" };
    std::bitset<8> bitfields { data_comes_from_somewhere };
    std::bitset<8> bitfields_2 { data_comes_from_somewhere_as_string };

    std::cout << bitfields << std::endl;
    std::cout << bitfields_2 << std::endl;

    // Set leftmost bit
    bitfields[ 7 ] = 1;
    int leftmost_bit = bitfields[ 7 ];

    std::cout << bitfields << std::endl;
    std::cout << leftmost_bit << std::endl;
}
</code>```

Title: Export bitfield to an array

Body:
I've declared this bit field. What I am trying to do is to get the whole value of the bitfield in binary and convert it into an array so I can use the index and address every '1' value.

union{
    struct shape{
        uint8_t p0 : 1;
        uint8_t p1 : 1;
        uint8_t p2 : 1;
        uint8_t p3 : 1;
        uint8_t p4 : 1;
        uint8_t p5 : 1;
        uint8_t p6 : 1;
        uint8_t p7 : 1;
    };
    uint8_t row;
}rows[8*2+4];

what I am trying to do is to export the bitfield to have it an array like uint8_t tab[8] = {0,1,1,0,0,1,0,1};

Is that even possible? Any tips?
Thanks in advance

Body:
If you want to just export your bitfields, it is possible with user-defined conversion from your union to std::array. Note that, it is just possible to read bits( not set ).

union{
    struct shape{
        uint8_t p0 : 1;
        uint8_t p1 : 1;
        uint8_t p2 : 1;
        uint8_t p3 : 1;
        uint8_t p4 : 1;
        uint8_t p5 : 1;
        uint8_t p6 : 1;
        uint8_t p7 : 1;
    } bits;

    operator std::array<bool , 8>(){
        std::array<bool , 8> exported_array;
        exported_array[ 0 ] = bits.p0;
        exported_array[ 1 ] = bits.p1;
        exported_array[ 2 ] = bits.p2;
        exported_array[ 3 ] = bits.p3;
        exported_array[ 4 ] = bits.p4;
        exported_array[ 5 ] = bits.p5;
        exported_array[ 6 ] = bits.p6;
        exported_array[ 7 ] = bits.p7;

        return exported_array;
    }

    uint8_t row;
} rows[8*2+4];

int main()
{
    rows[0].row = static_cast<uint8_t>( 643211 );
    std::array< bool , 8 > data = rows[ 0 ];

    for ( auto bit : data )
        std::cout << static_cast<int>( bit );
}

But I don't suggest to use this method. As far as i understand, you read a value from somewhere and you want to access/manipulate the bits like an array. std::bitset is a good option to do that.

Possible implementation like this :

#include <cstdint>
#include <iostream>
#include <bitset>

int main()
{
    uint8_t data_comes_from_somewhere = 0b01001001;
    std::string data_comes_from_somewhere_as_string { "11101001" };
    std::bitset<8> bitfields { data_comes_from_somewhere };
    std::bitset<8> bitfields_2 { data_comes_from_somewhere_as_string };

    std::cout << bitfields << std::endl;
    std::cout << bitfields_2 << std::endl;

    // Set leftmost bit
    bitfields[ 7 ] = 1;
    int leftmost_bit = bitfields[ 7 ];

    std::cout << bitfields << std::endl;
    std::cout << leftmost_bit << std::endl;
}


问:
Check if any value in any 2 arrays with different dimension is same in php
I have 2 arrays -

```<code>$arr1 =

Array
(
    [0] => Array
        (
            [id] => 1
            [sender_email] => test1@test.com
            [to_email] => test@test.com
            [description] => 5390BF675E1464F32202B
            [created_at] => 2020-01-21 04:50:21
            [status] => 1
        )

    [1] => Array
        (
            [id] => 30
            [sender_email] => abcd@gmail.com
            [to_email] => test@test.com
            [description] => 729237A55E2EDCB80B18F
            [created_at] => 2020-01-27 12:51:34
            [status] => 1
        )
[2] => Array
        (
            [id] => 31
            [sender_email] => abc@gmail.com
            [to_email] => test@test.com
            [description] => 729237A55E2EDCB80B18F
            [created_at] => 2020-01-27 12:51:34
            [status] => 1
        )

)

$arr2 =
Array
(
    [0] => test1@test.com
    [1] =>  abb@abb.com
    [2] =>  abc@gmail.com
)
</code>```

I am trying to find the matching values from $arr2 which also exist in $arr1.

I tried with

```<code>if(array_intersect($arr2, $arr1)) {
            die('wrong');
        }
</code>```

But it show error like -

```<code> Notice: Array to string conversion in
</code>```

I think due to difference in structure. How can this be achieved? It will be really helpful if I can get all matching values in one array. The column name will always be same but I request to not make that an inclusion in the code.

答:
This recursive function loops through all elements in every depth and searches for the elements in the $needle. It returns an array with all matched values:

```<code>function array_search_recursive( $needle, $haystack, $strict = false, &$matches = array() )  {
  foreach( $haystack as $value )  {
    if( is_array( $value ) )  {
      array_search_recursive( $needle, $value, $strict, $matches );
    } else {
      if( in_array( $value, $needle, $strict ) ) {
        $matches[] = $value;
      }
    }
  }
  return $matches;
}

// Parameters
// $needle: The array containing the searched values
// $haystack: The array to search in
// $strict: If it is set to true, it will also perform a strict type comparison
// $matches: Is only needed for recursion
</code>```

Usage:

```<code>$haystack = array(
  array(
    'id' => 1,
    'email' => 'test@mail.de'
  ),
  array(
    'id' => 2,
    'email' => 'mymail@web.de'
  ),
);

$needle = array( 'mymail@web.de', 1, 'lala@web.de' );

$matches = array_search_recursive( $needle, $haystack );
</code>```

The value of $matches:

```<code>Array
(
    [0] => 1
    [1] => mymail@web.de
)
</code>```

Body:
I have 2 arrays -

$arr1 =

Array
(
    [0] => Array
        (
            [id] => 1
            [sender_email] => test1@test.com
            [to_email] => test@test.com
            [description] => 5390BF675E1464F32202B
            [created_at] => 2020-01-21 04:50:21
            [status] => 1
        )

    [1] => Array
        (
            [id] => 30
            [sender_email] => abcd@gmail.com
            [to_email] => test@test.com
            [description] => 729237A55E2EDCB80B18F
            [created_at] => 2020-01-27 12:51:34
            [status] => 1
        )
[2] => Array
        (
            [id] => 31
            [sender_email] => abc@gmail.com
            [to_email] => test@test.com
            [description] => 729237A55E2EDCB80B18F
            [created_at] => 2020-01-27 12:51:34
            [status] => 1
        )

)

$arr2 =
Array
(
    [0] => test1@test.com
    [1] =>  abb@abb.com
    [2] =>  abc@gmail.com
)

I am trying to find the matching values from $arr2 which also exist in $arr1.

I tried with

if(array_intersect($arr2, $arr1)) {
            die('wrong');
        }

But it show error like -

 Notice: Array to string conversion in

I think due to difference in structure. How can this be achieved? It will be really helpful if I can get all matching values in one array. The column name will always be same but I request to not make that an inclusion in the code.

Body:
This recursive function loops through all elements in every depth and searches for the elements in the $needle. It returns an array with all matched values:

function array_search_recursive( $needle, $haystack, $strict = false, &$matches = array() )  {
  foreach( $haystack as $value )  {
    if( is_array( $value ) )  {
      array_search_recursive( $needle, $value, $strict, $matches );
    } else {
      if( in_array( $value, $needle, $strict ) ) {
        $matches[] = $value;
      }
    }
  }
  return $matches;
}

// Parameters
// $needle: The array containing the searched values
// $haystack: The array to search in
// $strict: If it is set to true, it will also perform a strict type comparison
// $matches: Is only needed for recursion

Usage:

$haystack = array(
  array(
    'id' => 1,
    'email' => 'test@mail.de'
  ),
  array(
    'id' => 2,
    'email' => 'mymail@web.de'
  ),
);

$needle = array( 'mymail@web.de', 1, 'lala@web.de' );

$matches = array_search_recursive( $needle, $haystack );

The value of $matches:

Array
(
    [0] => 1
    [1] => mymail@web.de
)


问:
Laravel Validator: limiting unique field check to specific product
I'm trying to make a unique validator to check against a specific product. Like:

```<code>// Validate Request for name and url
$this->validate($request, [
    'nome' => 'bail|required|min:2|unique:produto,name',
    'url'  => 'required|unique:produto',
]);

// Grab the user->id
$user_id = Auth::user()->id;

// Create a new product
if ($product = Product::create([
    'user_id'   => $user_id,
    'name'      => $request['nome'],
    'url'       => $request['url'],
    'is_active' => $request['is_active'],
])) {
    flash()->success('Produto criado.');
} else {
    flash()->error('Não foi possivel criar produto.');
}

// Check if $request data is unique at above created product
$this->validate($request, [
    'addmore.*.plataforma' => 'required|unique:plataforma_produto,plataforma_id,' . $product->id . ',id,product_id',
]);

// For each of the addmore.*. fields create an entry on DB
foreach ($request->addmore as $value) {
    Plataformaprod::create([
        'product_key'          => $value['product_key'],
        'basic_authentication' => $value['basic_authentication'],
        'codigo_produto'       => $value['codigo_produto'],
        'plataforma_id'        => $value['plataforma'],
        'product_id'           => $product->id,
    ]);
}

return redirect()->route('products.index');
</code>```

Checking the comments inside my code its basically doing this:

Validate $request for name and url

Grab the user->id

Create a new product

(this is what I can't get to work) RUN THE UNIQUE RULE JUST AGAINST A SPECIFIC PRODUCT_ID AND CHECK IF IT HAS UNIQUE PLATAFORMA_ID ENTRIES!

答:
Couldn't make the validation rule to work properly so I found this solution:

Created a unique index between the product_id and plataforma_id inside my migration file.

Created a try catch encapsulating the hole store method.

Catch the $e and turn it to a 500 error message saying: "The product already have a plataforma_id with that ID. Just added the first
record, change it's info in Edit page. It this error persists contact
dev@"

Body:
I'm trying to make a unique validator to check against a specific product. Like:

// Validate Request for name and url
$this->validate($request, [
    'nome' => 'bail|required|min:2|unique:produto,name',
    'url'  => 'required|unique:produto',
]);

// Grab the user->id
$user_id = Auth::user()->id;

// Create a new product
if ($product = Product::create([
    'user_id'   => $user_id,
    'name'      => $request['nome'],
    'url'       => $request['url'],
    'is_active' => $request['is_active'],
])) {
    flash()->success('Produto criado.');
} else {
    flash()->error('Não foi possivel criar produto.');
}

// Check if $request data is unique at above created product
$this->validate($request, [
    'addmore.*.plataforma' => 'required|unique:plataforma_produto,plataforma_id,' . $product->id . ',id,product_id',
]);

// For each of the addmore.*. fields create an entry on DB
foreach ($request->addmore as $value) {
    Plataformaprod::create([
        'product_key'          => $value['product_key'],
        'basic_authentication' => $value['basic_authentication'],
        'codigo_produto'       => $value['codigo_produto'],
        'plataforma_id'        => $value['plataforma'],
        'product_id'           => $product->id,
    ]);
}

return redirect()->route('products.index');

Checking the comments inside my code its basically doing this:

Validate $request for name and url

Grab the user->id

Create a new product

(this is what I can't get to work) RUN THE UNIQUE RULE JUST AGAINST A SPECIFIC PRODUCT_ID AND CHECK IF IT HAS UNIQUE PLATAFORMA_ID ENTRIES!


问:
BERT as a service for classification?
I have fine-tuned BERT on a classification task.

bert-as-a-service allows getting word embeddings but I would like to get the class of an input text.

The problem is best described here:
https://github.com/hanxiao/bert-as-service/issues/213

Any ideas on how to do that?

答:
The purpose of Bert-as-a-Service is to produce the sentence embeddings similar to ELMo, not serve as a classifier.

To use BERT for classification after fine-tuning one can use the implementation given in the following link:

https://github.com/google-research/bert/blob/master/predicting_movie_reviews_with_bert_on_tf_hub.ipynb

Title: BERT as a service for classification?


问:
Why does a user-provided default constructor lead to an uninitialized member?
Please consider the following code:

```<code>#include <iostream>

struct A{ // with implicit default constructor
       int number;
};

struct B{
       int number;
       B(){}; // user-provided default constructor
};

int main()
{
    A aa = {};
    B bb = {};

    std::cout << "aa.number: " << aa.number << std::endl;
    std::cout << "bb.number: " << bb.number << std::endl;
}
</code>```

Running the code online
results in the following output:

```<code>aa.number: 0
bb.number: 19715
</code>```

Why is bb.number uninitialized?
I thought that zero initialisation is guaranteed by using ={} ?

答:
I thought that zero initialisation is guaranteed by using ={} ?

That is only true if the type is "correct", which B is not.  B bb = {}; will default construct a B and your default constructor, B(){};, doesn't initialize number so no matter what, number will never be initialized because that is how your default constructor works.  If you had a "correct" constructor like

```<code>B() : number(0) {};
// or use
int number = 0;
B(){};
</code>```

Then you'd get zero initialization of number when it is default constructed.

This isn't the case with A because A is an aggregate and those come with certain guarantees like zero initialization if an empty braced-init-list, technical name for the {}, is used.

Body:
Please consider the following code:

#include <iostream>

struct A{ // with implicit default constructor
       int number;
};

struct B{
       int number;
       B(){}; // user-provided default constructor
};

int main()
{
    A aa = {};
    B bb = {};

    std::cout << "aa.number: " << aa.number << std::endl;
    std::cout << "bb.number: " << bb.number << std::endl;
}

Running the code online
results in the following output:

aa.number: 0
bb.number: 19715

Why is bb.number uninitialized?
I thought that zero initialisation is guaranteed by using ={} ?

Body:
I thought that zero initialisation is guaranteed by using ={} ?

That is only true if the type is "correct", which B is not.  B bb = {}; will default construct a B and your default constructor, B(){};, doesn't initialize number so no matter what, number will never be initialized because that is how your default constructor works.  If you had a "correct" constructor like

B() : number(0) {};
// or use
int number = 0;
B(){};

Then you'd get zero initialization of number when it is default constructed.

This isn't the case with A because A is an aggregate and those come with certain guarantees like zero initialization if an empty braced-init-list, technical name for the {}, is used.


问:
Check API response data with interface in Typescript Angular
I have an app that when the user logs in he received some data as a response, but if the response is not what I expect, the app crashes.

Let me show you the following:

I created an interface to tell Typescript the data I expect.

export interface AuthResponseData {
  token: string;
  expires: string;
  role: number;
}
```

<p>Then I created a method to send the login data to the server.</p>

<pre class="lang-js prettyprint-override"><code>login(user: string, password: string){
  return this.http.post<AuthResponseData>(
    'https://localhost:44344/api/auth', { user: user, pwd: password }
  ).pipe(
    catchError(this.handleError),
    tap(resData => { this.handleAuthentication(resData.token, resData.expires, resData.role)})
  );
}
</code>```

I was expecting that if the response from the server didn't match the interface then the Angular would redirect to catchError. But doesn't happen.

Now my question is: Is there any way to check if an API response is equal to the interface and throw an error if is not. Or what I'm asking isn't possible?

UPDATE:

After searching I discover that the interfaces disappear on run time, so there is no way to compare the api response with the interface (to the best of my knowledge). But I keep searching for a way to check the api response in a dynamic way. I think it is not really secure depending on api response to be always right. So I should check the API response. How can I do that?

Hope you can help me, thanks :)

答:
There are 3 questions in your issue plus one additional question by me (at the end) for a better understanding :

I'm asking this because if I have an endpoint that returns 100
  attributes I'll have to check the 100 by hand, right?

This is the right way to write interfaces based on returned models from API responses. if one endpoint returns a model containing 100 properties, the right way is writing relevant Typescript interface with the same properties perhaps by a tool like json2ts. This enables type-checking and prevents unwanted programming mistakes without any cost since interfaces do not exist in runtime.

Is there any way to check if an API response is equal to the interface
  and throw an error if is not. Or what I'm asking isn't possible?

You can check a key property value inside tap to detect condition (null).

I was expecting that if the response from the server didn't match the
  interface then the Angular would redirect to catchError. But doesn't
  happen.

interface mismatch wont be considered as RxJS's catchError. It fires when a request error occurs like 400 (bad request). Note that Type Checking means Once you declare a variable to be a certain type, it’s the compiler job to ensure that it is only ever assigned values of that type (or values that are sub-types of that type).

Is there a way to have dynamic model for all endpoints?

Some people employ bracket notation to extract the response values. Bracket notation and dot notation are functionally equivalent in JavaScript but are not the same thing in TypeScript. TypeScript is less strict with the bracket notation and this behavior is intentional to offer some kind of backdoor. I don't propose this way which makes the code dirty and fallible.

Body:
I have an app that when the user logs in he received some data as a response, but if the response is not what I expect, the app crashes.

Let me show you the following:

I created an interface to tell Typescript the data I expect.

export interface AuthResponseData {
  token: string;
  expires: string;
  role: number;
}

Then I created a method to send the login data to the server.

login(user: string, password: string){
  return this.http.post<AuthResponseData>(
    'https://localhost:44344/api/auth', { user: user, pwd: password }
  ).pipe(
    catchError(this.handleError),
    tap(resData => { this.handleAuthentication(resData.token, resData.expires, resData.role)})
  );
}

I was expecting that if the response from the server didn't match the interface then the Angular would redirect to catchError. But doesn't happen.

Now my question is: Is there any way to check if an API response is equal to the interface and throw an error if is not. Or what I'm asking isn't possible?

UPDATE:

After searching I discover that the interfaces disappear on run time, so there is no way to compare the api response with the interface (to the best of my knowledge). But I keep searching for a way to check the api response in a dynamic way. I think it is not really secure depending on api response to be always right. So I should check the API response. How can I do that?

Hope you can help me, thanks :)


问:
Where is '_DataLoaderIter' in pytorch 1.3.1?
When I use pytorch 1.3.1 with python3.7.4, like this

import torch

from torch.utils.data.dataloader import _DataLoaderIter
```

<p>Here is an errer : <code>cannot import name '_DataLoaderIter' from 'torch.utils.data.dataloader'</code></p>

<p>How should I solve that?</p>

<p>Should I uninstall 1.3.1?</p>

<p>I found <code>_DataLoaderIter</code> is in <code>dataloader.pyi</code> :</p>

<pre class="lang-py prettyprint-override"><code>class _DataLoaderIter:
    def __init__(self, loader: DataLoader) -> None:...
    def __len__(self) -> int: ...
    def __iter__(self) -> _DataLoaderIter: ...
    def __next__(self) -> Any: ...
</code>```

But I can't find it in dataloader.py.

答: _DataLoaderIter does not exist any more. This code is the latest one that contains _DataLoaderIter. You can use _SingleProcessDataLoaderIter or _MultiProcessingDataLoaderIter. I don't think the .pyi file you mentioned is in version 1.3.1.

Body:
When I use pytorch 1.3.1 with python3.7.4, like this

import torch

from torch.utils.data.dataloader import _DataLoaderIter

Here is an errer : cannot import name '_DataLoaderIter' from 'torch.utils.data.dataloader'

How should I solve that?

Should I uninstall 1.3.1?

I found _DataLoaderIter is in dataloader.pyi :

class _DataLoaderIter:
    def __init__(self, loader: DataLoader) -> None:...
    def __len__(self) -> int: ...
    def __iter__(self) -> _DataLoaderIter: ...
    def __next__(self) -> Any: ...

But I can't find it in dataloader.py.


问:
Can I extract all matches with functions like aregexec?
I've been enjoying the powerful function aregexec that allows me to mine strings in a fuzzy way.

For that I can search for a string of nucleotide "ATGGCTTCGTC" within a DNA section with defined allowance of insertion, deletion and substitute.

However, it only show me the first match without finishing the whole string. For example,

If I run

```<code>aregexec("a","adfasdfasdfaa")
</code>```

only the first "a" will show up from the result. I'd like to see all the matches.

I wonder if there are other more powerful functions or a argument to be added to this one.

Thank you very much.

P.S. I explained the fuzzy search poorly. I mean, the match doesn't have to be perfect. Say if I allow an substitution of one character, and search AATTGG in  ctagtactaAATGGGatctgct, the capital part will be considered a match. I can similarly allow insertions and deletions of certain characters.

答:
gregexpr will show every time there is the pattern in the string, like in this example.

```<code>gregexpr("as","adfasdfasdfaa")
</code>```

There are many more information if you use ?grep in R, it will explain every aspect of using regex.

Body:
I've been enjoying the powerful function aregexec that allows me to mine strings in a fuzzy way.

For that I can search for a string of nucleotide "ATGGCTTCGTC" within a DNA section with defined allowance of insertion, deletion and substitute.

However, it only show me the first match without finishing the whole string. For example,

If I run

aregexec("a","adfasdfasdfaa")

only the first "a" will show up from the result. I'd like to see all the matches.

I wonder if there are other more powerful functions or a argument to be added to this one.

Thank you very much.

P.S. I explained the fuzzy search poorly. I mean, the match doesn't have to be perfect. Say if I allow an substitution of one character, and search AATTGG in  ctagtactaAATGGGatctgct, the capital part will be considered a match. I can similarly allow insertions and deletions of certain characters.

Body:
gregexpr will show every time there is the pattern in the string, like in this example.

gregexpr("as","adfasdfasdfaa")

There are many more information if you use ?grep in R, it will explain every aspect of using regex.


问:
How to sum numbers considered as strings?
I have a column in my dataset like this:

```<code>col1
1
1, 1, 1, 1
1, 1
1, 1, 1, 1, 1
1
</code>```

I am trying to sum each row in a new column like this output:

```<code>col2
1
4
2
5
1
</code>```

I have tried doing:

```<code>rowSums(as.numeric(as.character(df$col1)))
Error in rowSums(as.numeric(as.character(df$col1))) :
  'x' must be an array of at least two dimensions
In addition: Warning message:
In is.data.frame(x) : NAs introduced by coercion
</code>```

I am new to R and likely missing something obvious, but I can't find any similar problems online also in R to adapt to my data, any help or advice on what functions to use would be appreciated.

Data:

```<code>structure(list(col1 = c("1", "1, 1, 1, 1", "1, 1", "1, 1, 1, 1, 1", "1"),
row.names = c(NA, -5L), class = "data.frame")

</code>```

答:
One dplyr and tidyr option could be:

```<code>df %>%
 rowid_to_column() %>%
 separate_rows(col1, sep = ", ", convert = TRUE) %>%
 group_by(rowid) %>%
 summarise_all(sum)

  rowid  col1
  <int> <int>
1     1     1
2     2     4
3     3     2
4     4     5
5     5     1
</code>```

Or a quite handy option involving splitstackshape:

```<code>rowSums(cSplit(df, "col1"), na.rm = TRUE)
</code>```

Body:
I have a column in my dataset like this:

col1
1
1, 1, 1, 1
1, 1
1, 1, 1, 1, 1
1

I am trying to sum each row in a new column like this output:

col2
1
4
2
5
1

I have tried doing:

rowSums(as.numeric(as.character(df$col1)))
Error in rowSums(as.numeric(as.character(df$col1))) :
  'x' must be an array of at least two dimensions
In addition: Warning message:
In is.data.frame(x) : NAs introduced by coercion

I am new to R and likely missing something obvious, but I can't find any similar problems online also in R to adapt to my data, any help or advice on what functions to use would be appreciated.

Data:

structure(list(col1 = c("1", "1, 1, 1, 1", "1, 1", "1, 1, 1, 1, 1", "1"),
row.names = c(NA, -5L), class = "data.frame")

Body:
One dplyr and tidyr option could be:

df %>%
 rowid_to_column() %>%
 separate_rows(col1, sep = ", ", convert = TRUE) %>%
 group_by(rowid) %>%
 summarise_all(sum)

  rowid  col1
  <int> <int>
1     1     1
2     2     4
3     3     2
4     4     5
5     5     1

Or a quite handy option involving splitstackshape:

rowSums(cSplit(df, "col1"), na.rm = TRUE)


问:
Android: put two lists into a ScrollView
I know that ListView objects shouldn't be put into a ScrollView. However, I can't come up with a proper approach to this situation: I have two layouts, both including a ListView, one directly below the other. I want all elements of both lists to be output; naturally, that should take more than the screen can offer, so I want to make the result scrollable, so, as I thought, I should put both into a ScrollView, but this doesn't work well with ListView (they only display one item each) and is considered a bad practice. How do I go about this?

Here's a mock up of what I mean:

Two lists, and the entirety of the second list can't fit into the screen, so I'd like to scroll it, and when I do, the second header ('Example2') scrolls up and doesn't stay in place, as opposed to the default behaviour of having the second list content scrolled.

What I have now is:

```<code>    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/example1_header"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <ListView
                android:id="@+id/example1_list_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/example1_header" />

        </RelativeLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/example2_header />

            <ListView
                android:id="@+id/example2_list_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>

    </LinearLayout>
</code>```

答:
```<code>If you put inside ScrollView then all content inside this will scroll.
</code>```

If I understood your problem correctly then you can try this. This divides your screen by 50/50 for 2 2 linear layouts

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_weight="2"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/example1_header"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Example1" />

        <ListView
            android:id="@+id/example1_list_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/example1_header"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:text="example2_header" />

        <ListView
            android:id="@+id/example2_list_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp" />

    </LinearLayout>

</LinearLayout>
</code>```

Body:
I know that ListView objects shouldn't be put into a ScrollView. However, I can't come up with a proper approach to this situation: I have two layouts, both including a ListView, one directly below the other. I want all elements of both lists to be output; naturally, that should take more than the screen can offer, so I want to make the result scrollable, so, as I thought, I should put both into a ScrollView, but this doesn't work well with ListView (they only display one item each) and is considered a bad practice. How do I go about this?

Here's a mock up of what I mean:

Two lists, and the entirety of the second list can't fit into the screen, so I'd like to scroll it, and when I do, the second header ('Example2') scrolls up and doesn't stay in place, as opposed to the default behaviour of having the second list content scrolled.

What I have now is:

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/example1_header"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <ListView
                android:id="@+id/example1_list_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/example1_header" />

        </RelativeLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/example2_header />

            <ListView
                android:id="@+id/example2_list_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>

    </LinearLayout>

Body:
If you put inside ScrollView then all content inside this will scroll.

If I understood your problem correctly then you can try this. This divides your screen by 50/50 for 2 2 linear layouts

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_weight="2"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/example1_header"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Example1" />

        <ListView
            android:id="@+id/example1_list_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/example1_header"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:text="example2_header" />

        <ListView
            android:id="@+id/example2_list_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp" />

    </LinearLayout>

</LinearLayout>


问:
Maven: assembly-plugin is not run at all
I am pretty new to Maven, tried to learn a couple of times before and figured I was better off without Maven. Now, (un)fortunately I have to use Maven in a project I'd like to contribute to. My problem at this point is regarding the packaging. I'd like to produce a self-contained (aka "fat") jar with all dependencies included, and a colleague who's played around with Maven helped me out with the pom file.

I have checked his pom files, as well as samples here on SO. The xml looks legit but the plugin is not run at all. Note that I get no errors, everything goes fine except I get no "fatjar". Any ideas what might be the cause of this problem?

Below is the relevant portion of the pom.xml. I have seen contradicting code samples with regards to positioning of <configuration> and <executions> tags, tried pretty much every variation I have found, still no joy.

```<code><plugin>
  <artifactId>maven-assembly-plugin</artifactId>
  <version>2.3</version>
  <executions>
    <execution>
        <id>make-jar-with-dependencies</id> <!-- this is used for inheritance merges -->
        <phase>package</phase> <!-- bind to the packaging phase -->
        <goals>
            <goal>single</goal>
        </goals>
    </execution>
  </executions>
  <configuration>
    <finalName>ProjectName</finalName>
    <appendAssemblyId>true</appendAssemblyId>
    <descriptorRefs>
      <descriptorRef>jar-with-dependencies</descriptorRef>
    </descriptorRefs>
    <archive>
      <manifest>
        <mainClass>org.mydomain.ProjectName</mainClass>
        <addClasspath>true</addClasspath>
      </manifest>
    </archive>
  </configuration>
</plugin>
</code>```

Edit_1 the console output from mvn clean package as asked by @khmarbaise

```<code>[INFO]
[INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) @ myproject ---
[INFO] Deleting /home/user/workspace/project/target
[INFO]
[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ myproject ---
[debug] execute contextualize
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 41 resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ myproject ---
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 292 source files to /home/user/workspace/project/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.5:testResources (default-testResources) @ myproject ---
[debug] execute contextualize
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/user/workspace/project/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ myproject ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.10:test (default-test) @ myproject ---
[INFO] No tests to run.
[INFO] Surefire report directory: /home/user/workspace/project/target/surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Results :
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] --- maven-jar-plugin:2.3.2:jar (default-jar) @ myproject ---
[INFO] Building jar: /home/user/workspace/project/target/myproject-2.0.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 12.210s
[INFO] Finished at: Thu Jun 07 11:45:14 CEST 2012
[INFO] Final Memory: 18M/184M
[INFO] ------------------------------------------------------------------------
</code>```

答:
I had one other view on this problem, that helped me to resolve the %subj%. If you dig the articles about how to make executable jar and jar with dependencies, they usually  provide code snippets, that a newbie tries to copy paste to their pom.xml. Those, that do not know much about the actual structure of pom.xml file (aka me) it is quite difficult task. I ended with this (not working) solution:

```<code> <project>
  ......

 <build>
   <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>3.2.0</version>
          <configuration>
            ............
          </configuration>

          <executions>
            ..............
          </executions>
        </plugin>
      </plugins>
   </pluginManagement>
  </build>
</project>
</code>```

If you know what pluginManagement does, you would not do the same mistake. But for me it was a big unknown and if you never used parent projects, make sure you do not fall into the same trap. With some adjustments here is a working maven-assembly-plugin setup (with the right context in pom.xml)

```<code><?xml version="1.0" encoding="UTF-8"?>

<project>
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.blah.blah</groupId>
  <artifactId>some-artifact</artifactId>
  <version>1.0-SNAPSHOT</version>

  <dependencies>
   ...
  </dependencies>

  <build>
      <plugins>
        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>3.2.0</version>
          <configuration>
            <appendAssemblyId>false</appendAssemblyId> <!-- nicer looking jar name -->
            <archive>
              <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>com.blah.blah.YourMainClass</mainClass>
              </manifest>
            </archive>
            <descriptorRefs>
              <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
          </configuration>

          <executions>
            <execution>
              <id>make-assembly</id>
              <phase>package</phase>
              <goals>
                <goal>single</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
      </plugins>
  </build>
</project>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am pretty new to Maven, tried to learn a couple of times before and figured I was better off without Maven. Now, (un)fortunately I have to use Maven in a project I'd like to contribute to. My problem at this point is regarding the packaging. I'd like to produce a self-contained (aka "fat") jar with all dependencies included, and a colleague who's played around with Maven helped me out with the pom file.

I have checked his pom files, as well as samples here on SO. The xml looks legit but the plugin is not run at all. Note that I get no errors, everything goes fine except I get no "fatjar". Any ideas what might be the cause of this problem?

Below is the relevant portion of the pom.xml. I have seen contradicting code samples with regards to positioning of <configuration> and <executions> tags, tried pretty much every variation I have found, still no joy.

<plugin>
  <artifactId>maven-assembly-plugin</artifactId>
  <version>2.3</version>
  <executions>
    <execution>
        <id>make-jar-with-dependencies</id>
        <phase>package</phase>
        <goals>
            <goal>single</goal>
        </goals>
    </execution>
  </executions>
  <configuration>
    <finalName>ProjectName</finalName>
    <appendAssemblyId>true</appendAssemblyId>
    <descriptorRefs>
      <descriptorRef>jar-with-dependencies</descriptorRef>
    </descriptorRefs>
    <archive>
      <manifest>
        <mainClass>org.mydomain.ProjectName</mainClass>
        <addClasspath>true</addClasspath>
      </manifest>
    </archive>
  </configuration>
</plugin>

Edit_1 the console output from mvn clean package as asked by @khmarbaise

[INFO]
[INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) @ myproject ---
[INFO] Deleting /home/user/workspace/project/target
[INFO]
[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ myproject ---
[debug] execute contextualize
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 41 resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ myproject ---
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 292 source files to /home/user/workspace/project/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.5:testResources (default-testResources) @ myproject ---
[debug] execute contextualize
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/user/workspace/project/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ myproject ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.10:test (default-test) @ myproject ---
[INFO] No tests to run.
[INFO] Surefire report directory: /home/user/workspace/project/target/surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Results :
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] --- maven-jar-plugin:2.3.2:jar (default-jar) @ myproject ---
[INFO] Building jar: /home/user/workspace/project/target/myproject-2.0.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 12.210s
[INFO] Finished at: Thu Jun 07 11:45:14 CEST 2012
[INFO] Final Memory: 18M/184M
[INFO] ------------------------------------------------------------------------

Body:
I had one other view on this problem, that helped me to resolve the %subj%. If you dig the articles about how to make executable jar and jar with dependencies, they usually  provide code snippets, that a newbie tries to copy paste to their pom.xml. Those, that do not know much about the actual structure of pom.xml file (aka me) it is quite difficult task. I ended with this (not working) solution:

 <project>
  ......

 <build>
   <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>3.2.0</version>
          <configuration>
            ............
          </configuration>

          <executions>
            ..............
          </executions>
        </plugin>
      </plugins>
   </pluginManagement>
  </build>
</project>

If you know what pluginManagement does, you would not do the same mistake. But for me it was a big unknown and if you never used parent projects, make sure you do not fall into the same trap. With some adjustments here is a working maven-assembly-plugin setup (with the right context in pom.xml)

<?xml version="1.0" encoding="UTF-8"?>

<project>
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.blah.blah</groupId>
  <artifactId>some-artifact</artifactId>
  <version>1.0-SNAPSHOT</version>

  <dependencies>
   ...
  </dependencies>

  <build>
      <plugins>
        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>3.2.0</version>
          <configuration>
            <appendAssemblyId>false</appendAssemblyId> <!-- nicer looking jar name -->
            <archive>
              <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>com.blah.blah.YourMainClass</mainClass>
              </manifest>
            </archive>
            <descriptorRefs>
              <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
          </configuration>

          <executions>
            <execution>
              <id>make-assembly</id>
              <phase>package</phase>
              <goals>
                <goal>single</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
      </plugins>
  </build>
</project>


问:
ASP.NET MVC ActionLink and post method
Can anyone tell me how can I submit values to Controller using ActionLink and POST method?

I don't want to use buttons.

I guess it has something with jquery.

答: ActionLink will never fire post. It always trigger GET request.</p>

Title: ASP.NET MVC ActionLink and post method


问:
Insert multiple images randomly into different table cells using Javascript
I'm pretty new in Javascript/Jquery, currently still learning and so here I am seeking help. I would like to insert different images randomly (the location changes everytime i refresh the page) into table cells using Javascript/Jquery and not touching HTML/CSS.

I have tried using append to insert the images, however every image appears in all table cells which weren't what I wanted. I have also tried backgroundrepeat: no repeat but it doesn't work. It would be good if there's some simple coding that would work, so it will be easier for me to understand.

I can't use getElementById cause my separated js file can't detect the ID from the HTML file

HTML:

```<code><table id="Image">
<tr>
<td><div class="ImageHere" value=1></div></td>
<td><div class="ImageHere" value=2></div></td>
<td><div class="ImageHere" value=3></div></td>
<td><div class="ImageHere" value=4></div></td>
<td><div class="ImageHere" value=5></div></td>
</tr>
<tr>
<td><div class="ImageHere" value=6></div></td>
<td><div class="ImageHere" value=7></div></td>
<td><div class="ImageHere" value=8></div></td>
<td><div class="ImageHere" value=9></div></td>
<td><div class="ImageHere" value=10></div></td>
</tr>
</table>
</code>```

my jQuery best try:

```<code>$(document).ready(function(){
    $(".ImageHere").append("<img src='images/card.jpg' width='100%' height='100%' />" ) });
});
</code>```

答:
One solution could be to generate a random index from all the image containers that you have created in your table cells. You could then insert a programmatically created image element in the image container located at the generated index.

Example:

// Returns a random index, from 0..max
const randomIndex = (max) => Math.floor(Math.random() * Math.floor(max));

// Returns an image element with a random image
const createImage = () => {
  const el = document.createElement('img');
  el.src = 'https://picsum.photos/100';
  return el;
};

// List of all image containers
const containers = document.querySelectorAll('.ImageHere');

// Generate random index and add an image to the container at that index
const index = randomIndex(containers.length);
containers[index].appendChild(createImage());```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  border-collapse: collapse;
}

td {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  padding: 0;
}

img {
  display: block;
}</code>```

```

Body:
I'm pretty new in Javascript/Jquery, currently still learning and so here I am seeking help. I would like to insert different images randomly (the location changes everytime i refresh the page) into table cells using Javascript/Jquery and not touching HTML/CSS.

I have tried using append to insert the images, however every image appears in all table cells which weren't what I wanted. I have also tried backgroundrepeat: no repeat but it doesn't work. It would be good if there's some simple coding that would work, so it will be easier for me to understand.

I can't use getElementById cause my separated js file can't detect the ID from the HTML file

HTML:

my jQuery best try:

$(document).ready(function(){
    $(".ImageHere").append("" ) });
});

Body:
One solution could be to generate a random index from all the image containers that you have created in your table cells. You could then insert a programmatically created image element in the image container located at the generated index.

Example:

// Returns a random index, from 0..max
const randomIndex = (max) => Math.floor(Math.random() * Math.floor(max));

// Returns an image element with a random image
const createImage = () => {
  const el = document.createElement('img');
  el.src = 'https://picsum.photos/100';
  return el;
};

// List of all image containers
const containers = document.querySelectorAll('.ImageHere');

// Generate random index and add an image to the container at that index
const index = randomIndex(containers.length);
containers[index].appendChild(createImage());

table {
  border-collapse: collapse;
}

td {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  padding: 0;
}

img {
  display: block;
}

<table id="Image">
  <tbody>
    <tr>
      <td>
        <div class="ImageHere"></div>
      </td>
      <td>
        <div class="ImageHere"></div>
      </td>
      <td>
        <div class="ImageHere"></div>
      </td>
      <td>
        <div class="ImageHere"></div>
      </td>
      <td>
        <div class="ImageHere"></div>
      </td>
    </tr>
    <tr>
      <td>
        <div class="ImageHere"></div>
      </td>
      <td>
        <div class="ImageHere"></div>
      </td>
      <td>
        <div class="ImageHere"></div>
      </td>
      <td>
        <div class="ImageHere"></div>
      </td>
      <td>
        <div class="ImageHere"></div>
      </td>
    </tr>
  </tbody>
</table>


问:
WPF Combobox - changed Datasource results in empty ItemsSource
I'm doing a simple binding of a Combobox in Page:

XAML:

```<code> <ComboBox x:Name="Cmb_test"  Grid.Column="2" Grid.Row="2" HorizontalAlignment="Left"  ItemsSource="{Binding}" />
</code>```

CODE behind:

```<code>private void Page_Loaded(object sender, RoutedEventArgs e)
{
     //Binding of label works fine everytime
     My_label.Content = dt.Rows[0]["Column1"];

     Cmb_test.DataContext = dt.DefaultView;
     Cmb_test.SelectedValuePath = dt.Columns[3].ToString();
     Cmb_test.DisplayMemberPath = dt.Columns[4].ToString();

     //Just a check to see whether DataTable really has changed
     Console.WriteLine(dt.Rows.Count.ToString());
 }
</code>```

But whenever my DataTable "dt" get's changed, my Combobox doesn't display Items anymore. I know there were a lot of questions allready asked regarding this issue, but all I could found were problems associating with refreshing during run-time. In my case I close a Page and re-open It when DataTable is changed, but result is empty Combobox.

Code for closing my Page, for addition:

CODE in same Page as Combobox:

```<code>private void BtnClose_Click(object sender, RoutedEventArgs e)
{
      Cmb_test.ItemsSource = null;
      Cmb_test.DataContext = null;

      var main_window = Application.Current.MainWindow;
      var frame = (main_window as MainWindow).My_Frame;
      frame.Content = null;

}
</code>```

Code in MainWindow:

```<code>private void My_Frame_Navigated(object sender, NavigationEventArgs e)
{
     if (My_Frame.Content == null)
     {
        My_Frame.RemoveBackEntry();
     }
}
</code>```

EDIT - another attempt:

XAML:

```<code>  <Page.Resources>
        <CollectionViewSource x:Key="My_source"/>
    </Page.Resources>

  <ComboBox x:Name="Cmb_test" ItemsSource="{Binding Source={StaticResource My_source}}" DisplayMemberPath="Column1"/>
</code>```

CODE behind:

```<code> private void Page_Loaded(object sender, RoutedEventArgs e)
        {

            var combo_datasource = new CollectionViewSource();
            combo_datasource = (CollectionViewSource)this.FindResource("seznamVrstEvidenc");
            combo_datasource.Source = Tabele.dt_Sifrant.DefaultView;

        }
</code>```

What is going on here, how can I fix combobox to show It's Items everytime ?

答:
I found a solution. I must say a very frustrating thing to learn before you come fammiliar with WPF and binding controls...

I followed numerious amount of articles in order to understand that in WPF you should use MVVM pattern in order to correctly bind your controls. However, there are so many different approaches doing this, so I ended up in something that is at least little understandable to me at this point:

1.) Create Model class. Here you define your DataTable columns and expose them as properties. This class needs to be inherited from INotifyPropertyChanged:

```<code> class Test_Model : INotifyPropertyChanged
 {
        private string col1;
        private string col2;

        public string Col1
        {
            get
            {
                return col1;
            }
            set
            {
                col1 = value;
                OnPropertyChanged("Col1");
            }
        }
        public string Col2
        {
            get
            {
                return col2;
            }
            set
            {
                col2 = value;
                OnPropertyChanged("Col2");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
   }
</code>```

2.) Create Viev_Model class.Here you create an IList (of Test_Model type) and fill It with DataTable, I used LINQ for that - that was also a challenge. Next, you again expose a property of IList type, in order to use that as your Datasource:

```<code> class Test_ViewModel
 {
        private IList<Test_Model> _comboData;

        public Test_ViewModel()
        {
            _comboData = dt.AsEnumerable().
                Select(row => new Test_Model
                {
                    Col1 = row.Field<string>(0),
                    Col2 = row.Field<string>(1)
                }).ToList();
        }

        public IList<Test_Model> ComboData
        {
            get { return _comboData; }
            set { _comboData = value; }
        }
  }
</code>```

3.) In your Window or Page assign DataContext to View_Model class. That is done in constructor, like this:

```<code> public partial class My_Page: Page
 {
        public My_Page()
        {
            InitializeComponent();
            this.DataContext = new Test_ViewModel(); //assign ViewModel class
        }

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

4.) Bind combobox to View_Model class:

```<code>  <ComboBox x:Name="Cmb_Test" ItemsSource="{Binding Path= ComboData}"
  DisplayMemberPath="Col1" SelectedValuePath="Col1" SelectedIndex="0"/>
</code>```

And then It worked, finally. Although I'm not happy with solution, so I have to figure out more simple way of doing proper binding. I ussually have many controls to bind & If I would do this for every DataTable I need, I would end up with tons of code in classes.

Body:
I'm doing a simple binding of a Combobox in Page:

XAML:

 <ComboBox x:Name="Cmb_test"  Grid.Column="2" Grid.Row="2" HorizontalAlignment="Left"  ItemsSource="{Binding}" />

CODE behind:

private void Page_Loaded(object sender, RoutedEventArgs e)
{
     //Binding of label works fine everytime
     My_label.Content = dt.Rows[0]["Column1"];

     Cmb_test.DataContext = dt.DefaultView;
     Cmb_test.SelectedValuePath = dt.Columns[3].ToString();
     Cmb_test.DisplayMemberPath = dt.Columns[4].ToString();

     //Just a check to see whether DataTable really has changed
     Console.WriteLine(dt.Rows.Count.ToString());
 }

But whenever my DataTable "dt" get's changed, my Combobox doesn't display Items anymore. I know there were a lot of questions allready asked regarding this issue, but all I could found were problems associating with refreshing during run-time. In my case I close a Page and re-open It when DataTable is changed, but result is empty Combobox.

Code for closing my Page, for addition:

CODE in same Page as Combobox:

private void BtnClose_Click(object sender, RoutedEventArgs e)
{
      Cmb_test.ItemsSource = null;
      Cmb_test.DataContext = null;

      var main_window = Application.Current.MainWindow;
      var frame = (main_window as MainWindow).My_Frame;
      frame.Content = null;

}

Code in MainWindow:

private void My_Frame_Navigated(object sender, NavigationEventArgs e)
{
     if (My_Frame.Content == null)
     {
        My_Frame.RemoveBackEntry();
     }
}

EDIT - another attempt:

XAML:

  <Page.Resources>
        <CollectionViewSource x:Key="My_source"/>
    </Page.Resources>

  <ComboBox x:Name="Cmb_test" ItemsSource="{Binding Source={StaticResource My_source}}" DisplayMemberPath="Column1"/>

CODE behind:

 private void Page_Loaded(object sender, RoutedEventArgs e)
        {

            var combo_datasource = new CollectionViewSource();
            combo_datasource = (CollectionViewSource)this.FindResource("seznamVrstEvidenc");
            combo_datasource.Source = Tabele.dt_Sifrant.DefaultView;

        }

What is going on here, how can I fix combobox to show It's Items everytime ?

Body:
I found a solution. I must say a very frustrating thing to learn before you come fammiliar with WPF and binding controls...

I followed numerious amount of articles in order to understand that in WPF you should use MVVM pattern in order to correctly bind your controls. However, there are so many different approaches doing this, so I ended up in something that is at least little understandable to me at this point:

1.) Create Model class. Here you define your DataTable columns and expose them as properties. This class needs to be inherited from INotifyPropertyChanged:

 class Test_Model : INotifyPropertyChanged
 {
        private string col1;
        private string col2;

        public string Col1
        {
            get
            {
                return col1;
            }
            set
            {
                col1 = value;
                OnPropertyChanged("Col1");
            }
        }
        public string Col2
        {
            get
            {
                return col2;
            }
            set
            {
                col2 = value;
                OnPropertyChanged("Col2");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
   }

2.) Create Viev_Model class.Here you create an IList (of Test_Model type) and fill It with DataTable, I used LINQ for that - that was also a challenge. Next, you again expose a property of IList type, in order to use that as your Datasource:

 class Test_ViewModel
 {
        private IList<Test_Model> _comboData;

        public Test_ViewModel()
        {
            _comboData = dt.AsEnumerable().
                Select(row => new Test_Model
                {
                    Col1 = row.Field<string>(0),
                    Col2 = row.Field<string>(1)
                }).ToList();
        }

        public IList<Test_Model> ComboData
        {
            get { return _comboData; }
            set { _comboData = value; }
        }
  }

3.) In your Window or Page assign DataContext to View_Model class. That is done in constructor, like this:

 public partial class My_Page: Page
 {
        public My_Page()
        {
            InitializeComponent();
            this.DataContext = new Test_ViewModel(); //assign ViewModel class
        }

        //...
  }

4.) Bind combobox to View_Model class:

  <ComboBox x:Name="Cmb_Test" ItemsSource="{Binding Path= ComboData}"
  DisplayMemberPath="Col1" SelectedValuePath="Col1" SelectedIndex="0"/>

And then It worked, finally. Although I'm not happy with solution, so I have to figure out more simple way of doing proper binding. I ussually have many controls to bind & If I would do this for every DataTable I need, I would end up with tons of code in classes.


问:
Django CKeditor using richTextField but when text is long it wont do paragraph
Iam using the RichTextUploadingField from CKeditor and when the text is long and need to do the paragraph it wont do it, in spite of using safe in the template

models.py

```<code>class Manuais(models.Model):
    descrição = RichTextUploadingField(blank=False)
</code>```

template
manual.html

```<code>{{ manual.descrição | safe }}
</code>```

答: turns out i was copying a lorem that had one single line, i dindt know that it copys literally what is on the block, but thnx for feedback!</p>

Body:
Iam using the RichTextUploadingField from CKeditor and when the text is long and need to do the paragraph it wont do it, in spite of using safe in the template

models.py

class Manuais(models.Model):
    descrição = RichTextUploadingField(blank=False)

template
manual.html

{{ manual.descrição | safe }}


问:
Helm - Spark operator examples/spark-pi.yaml does not exist
I've deployed Spark Operator to GKE using the Helm Chart to a custom namespace:

```<code>helm install --name sparkoperator incubator/sparkoperator --namespace custom-ns --set sparkJobNamespace=custom-ns
</code>```

and confirmed the operator running in the cluster with helm status sparkoperator.

However when I'm trying to run the Spark Pi example kubectl apply -f examples/spark-pi.yaml I'm getting the following error:

```<code>the path "examples/spark-pi.yaml" does not exist
</code>```

There are few things that I probably still don't get:

Where is actually examples/spark-pi.yaml located after deploying the operator?

What else should I check and what other steps should I take to make the example work?

答: kubectl apply needs a yaml file either locally on the system where you are running kubectl command or it can be a http/https endpoint hosting the file.

Body:
I've deployed Spark Operator to GKE using the Helm Chart to a custom namespace:

helm install --name sparkoperator incubator/sparkoperator --namespace custom-ns --set sparkJobNamespace=custom-ns

and confirmed the operator running in the cluster with helm status sparkoperator.

However when I'm trying to run the Spark Pi example kubectl apply -f examples/spark-pi.yaml I'm getting the following error:

the path "examples/spark-pi.yaml" does not exist

There are few things that I probably still don't get:

Where is actually examples/spark-pi.yaml located after deploying the operator?

What else should I check and what other steps should I take to make the example work?


问:
Ruby tests with spec and capybara xml post
I am trying to figure out how to send a xml http request (validated by request.xhr?) using page.driver.post() method.

Have you any suggestions? Running out of ideas :(.

Thanks a lot

答:
I got it, it is possible to pass it like this.

page.driver.post("/",{"HTTP_X_REQUESTED_WITH" => "XMLHttpRequest"})