问:
pandas: write empty DataFrame to HDF file
Is there a way to force pandas to write an empty DataFrame to an HDF file?

import pandas as pd
df = pd.DataFrame(columns=['x','y'])
df.to_hdf('temp.h5', 'xxx')
df2 = pd.read_hdf('temp.h5', 'xxx')
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 389, in read_hdf
    return store.select(key, auto_close=auto_close, **kwargs)
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 740, in select
    return it.get_result()
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 1518, in get_result
    results = self.func(self.start, self.stop, where)
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 733, in func
    columns=columns)
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 2986, in read
    idx=i), start=_start, stop=_stop)
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 2575, in read_index
    _, index = self.read_index_node(getattr(self.group, key), **kwargs)
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 2676, in read_index_node
    data = node[start:stop]
  File ".../Python-3.6.3/lib/python3.6/site-packages/tables/vlarray.py", line 675, in __getitem__
    return self.read(start, stop, step)
  File ".../Python-3.6.3/lib/python3.6/site-packages/tables/vlarray.py", line 811, in read
    listarr = self._read_array(start, stop, step)
  File "tables/hdf5extension.pyx", line 2106, in tables.hdf5extension.VLArray._read_array (tables/hdf5extension.c:24649)
ValueError: cannot set WRITEABLE flag to True of this array
</code>```

Writing with format='table':

import pandas as pd
df = pd.DataFrame(columns=['x','y'])
df.to_hdf('temp.h5', 'xxx', format='table')
df2 = pd.read_hdf('temp.h5', 'xxx')
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 389, in read_hdf
    return store.select(key, auto_close=auto_close, **kwargs)
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 722, in select
    raise KeyError('No object named {key} in the file'.format(key=key))
KeyError: 'No object named xxx in the file'
</code>```

Pandas version: 0.24.2

Thank you for your help!

答:
Putting empty DataFrame into HDFStore in fixed format should work (maybe you need to check versions of other packages, e.g. tables):

# Versions
pd.__version__
tables.__version__

# DF
df = pd.DataFrame(columns=['x','y'])
df

# Dump in fixed format
with pd.HDFStore('temp.h5') as store:
    store.put('df', df, format='f')
    print('Read:')
    store.select('df')

>>> '0.24.2'
>>> '3.5.1'
>>>   x     y
>>>
>>> Read:
>>>   x     y
```

Pytable really forbids to do so (at least it was), but for fixed pandas has its workaround.

But as discussed in same github issue there are made some efforts to fix this behavior for table as well. But looks like solution is still 'hangs in the air' because it was so at the end of march.

Body:
Is there a way to force pandas to write an empty DataFrame to an HDF file?

import pandas as pd
df = pd.DataFrame(columns=['x','y'])
df.to_hdf('temp.h5', 'xxx')
df2 = pd.read_hdf('temp.h5', 'xxx')

Output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 389, in read_hdf
    return store.select(key, auto_close=auto_close, **kwargs)
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 740, in select
    return it.get_result()
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 1518, in get_result
    results = self.func(self.start, self.stop, where)
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 733, in func
    columns=columns)
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 2986, in read
    idx=i), start=_start, stop=_stop)
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 2575, in read_index
    _, index = self.read_index_node(getattr(self.group, key), **kwargs)
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 2676, in read_index_node
    data = node[start:stop]
  File ".../Python-3.6.3/lib/python3.6/site-packages/tables/vlarray.py", line 675, in __getitem__
    return self.read(start, stop, step)
  File ".../Python-3.6.3/lib/python3.6/site-packages/tables/vlarray.py", line 811, in read
    listarr = self._read_array(start, stop, step)
  File "tables/hdf5extension.pyx", line 2106, in tables.hdf5extension.VLArray._read_array (tables/hdf5extension.c:24649)
ValueError: cannot set WRITEABLE flag to True of this array

Writing with format='table':

import pandas as pd
df = pd.DataFrame(columns=['x','y'])
df.to_hdf('temp.h5', 'xxx', format='table')
df2 = pd.read_hdf('temp.h5', 'xxx')

Output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 389, in read_hdf
    return store.select(key, auto_close=auto_close, **kwargs)
  File ".../Python-3.6.3/lib/python3.6/site-packages/pandas/io/pytables.py", line 722, in select
    raise KeyError('No object named {key} in the file'.format(key=key))
KeyError: 'No object named xxx in the file'

Pandas version: 0.24.2

Thank you for your help!

Body:
Putting empty DataFrame into HDFStore in fixed format should work (maybe you need to check versions of other packages, e.g. tables):

# Versions
pd.__version__
tables.__version__

# DF
df = pd.DataFrame(columns=['x','y'])
df

# Dump in fixed format
with pd.HDFStore('temp.h5') as store:
    store.put('df', df, format='f')
    print('Read:')
    store.select('df')

>>> '0.24.2'
>>> '3.5.1'
>>>   x     y
>>>
>>> Read:
>>>   x     y

Pytable really forbids to do so (at least it was), but for fixed pandas has its workaround.

But as discussed in same github issue there are made some efforts to fix this behavior for table as well. But looks like solution is still 'hangs in the air' because it was so at the end of march.


来源: stackexchange

问:
Is it possible to mount a remote filesystem and open/mmap /dev/mem?
I'm wondering if it's possible to write c code to open and mmap a memory pointer to /dev/mem of a remote file system. I've mounted this system under /mnt/ of the system that I'm planning to run the code from. I mounted /dev using sshfs, so the full path would just look like /mnt/mem from the system where the c code is run.

In my experience, I could open/mmap /dev/mem if I was ssh'ed into the remote system directly and access the components I wanted. That is, if I change the string used to open the file descriptor from /mnt/mem to /dev/mem, and compile and run that locally instead that works and fetches the register data I expect.

It seems like I can successfully open and mmap to /home/whatever on the remote system as well. Is there some reason why a remotely mounted /dev/mem just can't be opened the same way?

Some extra info for my case:
-Linux distros on both systems
-ssh installed on both
-sshfs installed where I did the mounting from
-I have root access to both systems

properties of /dev/mem as observed from the host system:

crw-rw-rw- 1 root root 0, 0 Dec  8  2105 /mnt/mem

The errno returns permission denied as if even with root privilege I still cannot open memory this way, but I'm not sure why this should not work if r/w permission is set in all the paths and mem itself.

I also performed the sshfs mount using the remote system's root and root pw.

```<code>//Mmap a target to a pointer variable/fd
struct reg_ptrs mmap_target(struct access_method_info mthd_info)
{
  struct reg_ptrs mapped_ptrs;
  mapped_ptrs.iic_bar = NULL;
  char   mem_path1[100];

  strcpy(mem_path1,"/mnt/mem");

  int mem_fd1;
  mem_fd1 = open(mem_path1, O_RDWR);
  if(mem_fd1 == -1) {
    printf("Couldn't open()! %s\n", strerror(errno));
  }

  mapped_ptrs.iic_bar = mmap(NULL, 0x1000, PROT_READ | PROT_WRITE, MAP_SHARED, mem_fd1, 0xff0e0000);

  //With pointers mapped to appropriate memory, we should be able to close these now
  close(mem_fd1);

  return mapped_ptrs;
} /* mmap_target */
</code>```

The expected results would be for the open() and mmap() c functions to succeed at opening and mapping the remotely mounted /dev/mem file

答: Device files are not really files that get opened -- when you open one, it uses the device number from the inode as an index in the kernel's device table to know which one to open.  So if you could open /mnt/mem (the device from the remote machine, it would look up the index of the remote kernel's memory device in the local kernel.  So you'd get some random device on your local kernel, whatever happened to be in that slot.  Even if it was the memory device (and it might be, if the kernels were configured similarly), you would get the local kernel's memory, not the remote kernel's memory.  For this reason, remote file systems are (almost) invariably mounted with the -nodev option (its the default), which means device files cannot be opened.

ContentLicense: CC BY-SA 4.0

Body:
I'm wondering if it's possible to write c code to open and mmap a memory pointer to /dev/mem of a remote file system. I've mounted this system under /mnt/ of the system that I'm planning to run the code from. I mounted /dev using sshfs, so the full path would just look like /mnt/mem from the system where the c code is run.

In my experience, I could open/mmap /dev/mem if I was ssh'ed into the remote system directly and access the components I wanted. That is, if I change the string used to open the file descriptor from /mnt/mem to /dev/mem, and compile and run that locally instead that works and fetches the register data I expect.

It seems like I can successfully open and mmap to /home/whatever on the remote system as well. Is there some reason why a remotely mounted /dev/mem just can't be opened the same way?

Some extra info for my case:
-Linux distros on both systems
-ssh installed on both
-sshfs installed where I did the mounting from
-I have root access to both systems

properties of /dev/mem as observed from the host system:

crw-rw-rw- 1 root root 0, 0 Dec  8  2105 /mnt/mem

The errno returns permission denied as if even with root privilege I still cannot open memory this way, but I'm not sure why this should not work if r/w permission is set in all the paths and mem itself.

I also performed the sshfs mount using the remote system's root and root pw.

//Mmap a target to a pointer variable/fd
struct reg_ptrs mmap_target(struct access_method_info mthd_info)
{
  struct reg_ptrs mapped_ptrs;
  mapped_ptrs.iic_bar = NULL;
  char   mem_path1[100];

  strcpy(mem_path1,"/mnt/mem");

  int mem_fd1;
  mem_fd1 = open(mem_path1, O_RDWR);
  if(mem_fd1 == -1) {
    printf("Couldn't open()! %s\n", strerror(errno));
  }

  mapped_ptrs.iic_bar = mmap(NULL, 0x1000, PROT_READ | PROT_WRITE, MAP_SHARED, mem_fd1, 0xff0e0000);

  //With pointers mapped to appropriate memory, we should be able to close these now
  close(mem_fd1);

  return mapped_ptrs;
} /* mmap_target */

The expected results would be for the open() and mmap() c functions to succeed at opening and mapping the remotely mounted /dev/mem file


问:
How to know if a window is maximized using pywin32?
I need to check if a window is maximized using pywin32. I'm on a windows 10 machine.

I have looked through the documentation but can't find a straight solution, any leads?

答:
Use GetWindowPlacement API.

In pywin32, win32gui.GetWindowPlacement will return a tuple which can be tested as follows:

```<code>window = win32gui.FindWindow("Notepad", None)
if window:
    tup = win32gui.GetWindowPlacement(window)
    if tup[1] == win32con.SW_SHOWMAXIMIZED:
        print("maximized")
    elif tup[1] == win32con.SW_SHOWMINIMIZED:
        print("minimized")
    elif tup[1] == win32con.SW_SHOWNORMAL:
        print("normal")
</code>```

Body:
Use GetWindowPlacement API.

In pywin32, win32gui.GetWindowPlacement will return a tuple which can be tested as follows:

window = win32gui.FindWindow("Notepad", None)
if window:
    tup = win32gui.GetWindowPlacement(window)
    if tup[1] == win32con.SW_SHOWMAXIMIZED:
        print("maximized")
    elif tup[1] == win32con.SW_SHOWMINIMIZED:
        print("minimized")
    elif tup[1] == win32con.SW_SHOWNORMAL:
        print("normal")


问:
Is there any way to add an iVar that's not in the header file (not using LLVM 2.0 or later) in Objective-C?
I recently learned that you can add ivar in a class extension with LLVM2.0. (gcc can't do this)
This is somehow really private iVar because other users don't it's existence since it's not in the header file.
like:

```<code>//SomeClass.h
@interface SomeClass : NSObject {

}
@end

//SomeClass.m
@interface SomeClass ()
{
    NSString *reallyPrivateString;
}
@end

@implementation SomeClass

@end
</code>```

But this does rely on the compiler. Is there any other way to declare an ivar that's not in the header file?

答:
If you're just going to be using the ivar internally, and you're using the modern runtime (Snow Leopard 64 bit and iOS 3.0+, I think) then you can just declare properties in a class extension and synthesize them inside the class. No ivars are exposed in your header, no messy id _internal objects, and you get around fragile ivars, too.

```<code>// public header
@interface MyClass : NSObject {
// no ivars
}
- (void)someMethod;
@end

// MyClass.m
@interface MyClass ()
@property (nonatomic, retain) NSString *privateString;
@end

@implementation MyClass
@synthesize privateString;

- (void)someMethod {
    self.privateString = @"Hello";
    NSLog(@"self.privateString = %@", self.privateString);
    NSLog(@"privateString (direct variable access) = %@", privateString); // The compiler has synthesized not only the property methods, but also actually created this ivar for you. If you wanted to change the name of the ivar, do @synthesize privateString = m_privateString; or whatever your naming convention is
}
@end
</code>```

This works with Apple's gcc, in addition to LLVM. (I'm not sure if this works on other platforms, ie not Apple's gcc, but it will certainly work for both iOS and Snow Leopard+).

ContentLicense: CC BY-SA 3.0

Body:
I recently learned that you can add ivar in a class extension with LLVM2.0. (gcc can't do this)
This is somehow really private iVar because other users don't it's existence since it's not in the header file.
like:

//SomeClass.h
@interface SomeClass : NSObject {

}
@end

//SomeClass.m
@interface SomeClass ()
{
    NSString *reallyPrivateString;
}
@end

@implementation SomeClass

@end

But this does rely on the compiler. Is there any other way to declare an ivar that's not in the header file?

Body:
If you're just going to be using the ivar internally, and you're using the modern runtime (Snow Leopard 64 bit and iOS 3.0+, I think) then you can just declare properties in a class extension and synthesize them inside the class. No ivars are exposed in your header, no messy id _internal objects, and you get around fragile ivars, too.

// public header
@interface MyClass : NSObject {
// no ivars
}
- (void)someMethod;
@end

// MyClass.m
@interface MyClass ()
@property (nonatomic, retain) NSString *privateString;
@end

@implementation MyClass
@synthesize privateString;

- (void)someMethod {
    self.privateString = @"Hello";
    NSLog(@"self.privateString = %@", self.privateString);
    NSLog(@"privateString (direct variable access) = %@", privateString); // The compiler has synthesized not only the property methods, but also actually created this ivar for you. If you wanted to change the name of the ivar, do @synthesize privateString = m_privateString; or whatever your naming convention is
}
@end

This works with Apple's gcc, in addition to LLVM. (I'm not sure if this works on other platforms, ie not Apple's gcc, but it will certainly work for both iOS and Snow Leopard+).


问:
I have created a custom post type. single page for that custom post showing blank page
I have created a custom post type. Single posts for that custom post type is not working. showing white page but html are loading properly. Here is the url https://bestswiss.ch/vendorpartner/formforum</p>

```<code>   ////code

 $labels = array(
            'name'               => __( 'Partner' ),
            'singular_name'      => __( 'vendorpartner' ),
            'add_new'            => __( 'Add New vendorpartner' ),
            'add_new_item'       => __( 'Add New vendorpartner' ),
            'edit_item'          => __( 'Edit vendorpartner' ),
            'new_item'           => __( 'Add New vendorpartner' ),
            'view_item'          => __( 'View vendorpartner' ),
            'search_items'       => __( 'Search vendorpartner' ),
            'not_found'          => __( 'No events found' ),
            'not_found_in_trash' => __( 'No events found in trash' )
        );
        $supports = array(
            'title',
            'editor',
            'thumbnail',
            'comments',
            'revisions',
            'page-attributes'
        );
        $args = array(
            'labels'               => $labels,
            'supports'             => $supports,
            'public'               => true,
            'capability_type'      => 'post',
            'rewrite'              => array( 'slug' => 'vendorpartner' ),
            'has_archive'          => true,
            'menu_position'        => 30,
            'menu_icon'            => 'dashicons-calendar-alt',
            'register_meta_box_cb' => 'wpt_add_event_metaboxes',
        );
        register_post_type( 'vendorpartner', $args );
</code>```

答:
The important thing to be aware of here is WordPress's template hierarchy. Many views are rendered with a certain template file based on naming logic.

Single posts use a single- prefix. Just add the id of your custom post type and you get the file name you need to create. Create a template with this name and your single view of that CPT will use it:

```<code>single-vendorpartner.php
</code>```

Interesting thing is that the hierarchy will point to the next template name up the chain if the default file name file is not there. basically index.php is the fallback for nearly everything and that template is likely only setup to handle your blog.

Here is the documentation: https://developer.wordpress.org/themes/basics/template-hierarchy/. Print out the chart on that page and put it up on your wall.

Body:
I have created a custom post type. Single posts for that custom post type is not working. showing white page but html are loading properly. Here is the url https://bestswiss.ch/vendorpartner/formforum

   ////code

 $labels = array(
            'name'               => __( 'Partner' ),
            'singular_name'      => __( 'vendorpartner' ),
            'add_new'            => __( 'Add New vendorpartner' ),
            'add_new_item'       => __( 'Add New vendorpartner' ),
            'edit_item'          => __( 'Edit vendorpartner' ),
            'new_item'           => __( 'Add New vendorpartner' ),
            'view_item'          => __( 'View vendorpartner' ),
            'search_items'       => __( 'Search vendorpartner' ),
            'not_found'          => __( 'No events found' ),
            'not_found_in_trash' => __( 'No events found in trash' )
        );
        $supports = array(
            'title',
            'editor',
            'thumbnail',
            'comments',
            'revisions',
            'page-attributes'
        );
        $args = array(
            'labels'               => $labels,
            'supports'             => $supports,
            'public'               => true,
            'capability_type'      => 'post',
            'rewrite'              => array( 'slug' => 'vendorpartner' ),
            'has_archive'          => true,
            'menu_position'        => 30,
            'menu_icon'            => 'dashicons-calendar-alt',
            'register_meta_box_cb' => 'wpt_add_event_metaboxes',
        );
        register_post_type( 'vendorpartner', $args );

Body:
The important thing to be aware of here is WordPress's template hierarchy. Many views are rendered with a certain template file based on naming logic.

Single posts use a single- prefix. Just add the id of your custom post type and you get the file name you need to create. Create a template with this name and your single view of that CPT will use it:

single-vendorpartner.php

Interesting thing is that the hierarchy will point to the next template name up the chain if the default file name file is not there. basically index.php is the fallback for nearly everything and that template is likely only setup to handle your blog.

Here is the documentation: https://developer.wordpress.org/themes/basics/template-hierarchy/. Print out the chart on that page and put it up on your wall.


问:
What Is the behavior of forkJoin when it is not In a SwitchMap/MergeMap in Epics
I want to understand what happens when I directly pipe to an action$ and try to use forkJoin operator

const action1 = { type: "ACTION_1" };
const action2 = { type: "ACTION_2" };
```

<p>in a switchMap forkJoin works fine.</p>

<pre class="lang-js prettyprint-override"><code>

export const testForkJoinSwitchMap: Epic<Action> = action$ =>
  action$.pipe(
    ofType(action1),
    switchMap(() =>
      forkJoin(
        from(fetch("https://api.github.com/users")).pipe(
          map((res: any) => {
            return res;
          })
        )
      )
    ),
    map((data: any) => {
      // do something with data
      return action2;
    })
  );
</code>```

If I took it out of the switchMap then:

export const testForkJoin: Epic<Action> = action$ =>
  action$.pipe(
    ofType(action1),
    forkJoin(from(fetch("https://api.github.com/users"))).pipe(
      map((response: any) => {
        return action2;
      })
    )
  );
```

<p>I get the typing error:</p>

<pre class="lang-js prettyprint-override"><code>Argument of type 'Observable<{ type: string; }>' is not assignable to parameter of type 'OperatorFunction<{}, Action<any>>'.
</code>```

I want to know why it does not compile? and the reason of the type mismatch, what makes the epics without the forkJoin invalid in this case?

edit: I know that forkJoin is not meaningful for a single observable, but I put 1 to keep the example smaller

答:
observable.pipe() only takes operators inside it.

forkJoin is an operator which returns an observable that's why you get that error. Argument of type 'Observable' is not assignable to parameter of type 'OperatorFunction' i.e forkJoin which returns an observable is not assignable to type of operator function.

switchMap, on the other hand, is an operator which returns an OperatorFunction and operates on an observable that's why your first approach worked. switchMap(() => someObservable) and someObservable in this case is forkJoin()

It's also evident from your imports. You might have imported forkJoin from rxjs library whereas switchMap from rxjs/operators library.

Body:
I want to understand what happens when I directly pipe to an action$ and try to use forkJoin operator

const action1 = { type: "ACTION_1" };
const action2 = { type: "ACTION_2" };

in a switchMap forkJoin works fine.

export const testForkJoinSwitchMap: Epic<Action> = action$ =>
  action$.pipe(
    ofType(action1),
    switchMap(() =>
      forkJoin(
        from(fetch("https://api.github.com/users")).pipe(
          map((res: any) => {
            return res;
          })
        )
      )
    ),
    map((data: any) => {
      // do something with data
      return action2;
    })
  );

If I took it out of the switchMap then:

export const testForkJoin: Epic<Action> = action$ =>
  action$.pipe(
    ofType(action1),
    forkJoin(from(fetch("https://api.github.com/users"))).pipe(
      map((response: any) => {
        return action2;
      })
    )
  );

I get the typing error:

Argument of type 'Observable<{ type: string; }>' is not assignable to parameter of type 'OperatorFunction<{}, Action<any>>'.

I want to know why it does not compile? and the reason of the type mismatch, what makes the epics without the forkJoin invalid in this case?

edit: I know that forkJoin is not meaningful for a single observable, but I put 1 to keep the example smaller


问:
Deleted migration files- how to makemigrations without losing data
I changed a field on a model class (which has no classes point to it, only one foreign key pointing out of it). Somehow, this stuffed up my migrations and it keeps saying "django.db.migrations.graph.NodeNotFoundError:" looking for migration files that do not exist.

I accidentally deleted several files in my 'migrations' folder.

My database contains a lot of data, and I do not want to break it.

Will I lose any data if I:

Remove the table that caused the problem in the first place (psql, \d, DROP TABLE tablename)

delete all my migration files

Re run the migration from the start?

./manage.py makemigrations

./manage.py migrate

Can anyone recommend another way of fixing this?

Here is the traceback:
http://dpaste.com/0Y1YDXS

答:
Empty the django_migrations table:

```<code>delete from django_migrations;
</code>```

Remove all the files in migrations folders in each and every app of your project.

Reset the migrations for the "built-in" apps:

```<code>python manage.py migrate --fake
</code>```

Create initial migrations for each and every app:

```<code>python manage.py makemigrations your_app_name
</code>```

Final step is to create fake initial migrations:

```<code>python manage.py migrate --fake-initial
</code>```

See here https://micropyramid.com/blog/how-to-create-initial-django-migrations-for-existing-schema/

Body:
Empty the django_migrations table:

delete from django_migrations;

Remove all the files in migrations folders in each and every app of your project.

Reset the migrations for the "built-in" apps:

python manage.py migrate --fake

Create initial migrations for each and every app:

python manage.py makemigrations your_app_name

Final step is to create fake initial migrations:

python manage.py migrate --fake-initial

See here https://micropyramid.com/blog/how-to-create-initial-django-migrations-for-existing-schema/


问:
Viewing a particular html + django
I am trying to learn django by reading the tutorial and Django book on the net.

I am trying to display a web page on a url.

For the same I wrote in the url pattern function the statement (r'^home/$' , home ) where I have imported the home function.

Also in the home function I wrote

```<code>def home( request ):

      return render_to_response("home.html",None) // home.html is placed in the templates folder along with its .css
</code>```

This must be wrong as I don't intend to pass any response ... so please tell what i should write here...

However the issue I am facing is that when I go to the url the html comes in plain without the css styling without the color etc.....

When I check my html template however that is fine ...

So what do I need to do to display the html as it is in the url ???

Thanks..

答:
I assume you are using the development server.
Make sure that your URLconf is correct:

```<code>from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
</code>```

See: http://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-in-development

Then your css files can be included like this:

```<code>{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
<head>
<link rel="stylesheet" href="{{ STATIC_PREFIX }}/yourpath/your.css" />
</head>
</code>```

Off course the css files have to be located in your static_media dir.

This means, as stated in the docs, that you should set STATIC_ROOT to the appropriate folder, for example a folder named 'static_media' in your project directory.

Title: Viewing a particular html + django

Body:
I am trying to learn django by reading the tutorial and Django book on the net.

I am trying to display a web page on a url.

For the same I wrote in the url pattern function the statement (r'^home/$' , home ) where I have imported the home function.

Also in the home function I wrote

def home( request ):

      return render_to_response("home.html",None) // home.html is placed in the templates folder along with its .css

This must be wrong as I don't intend to pass any response ... so please tell what i should write here...

However the issue I am facing is that when I go to the url the html comes in plain without the css styling without the color etc.....

When I check my html template however that is fine ...

So what do I need to do to display the html as it is in the url ???

Thanks..

Body:
I assume you are using the development server.
Make sure that your URLconf is correct:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()

See: http://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-in-development

Then your css files can be included like this:

{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
<head>
<link rel="stylesheet" href="{{ STATIC_PREFIX }}/yourpath/your.css" />
</head>

Off course the css files have to be located in your static_media dir.

This means, as stated in the docs, that you should set STATIC_ROOT to the appropriate folder, for example a folder named 'static_media' in your project directory.


问:
Recursive Partial<T> in TypeScript
I have this interface:

```<code>export interface UserSettings
{
    one: {
        three: number;
        four: number;
    };
    two: {
        five: number;
        six: number;
    };
}
</code>```

...and want to turn it into this:

```<code>export interface UserSettingsForUpdate
{
    one?: {
        three?: number;
        four?: number;
    };
    two?: {
        five?: number;
        six?: number;
    };
}
</code>```

...but Partial<UserSettings> produces this:

```<code>{
    one?: {
        three: number;
        four: number;
    };
    two?: {
        five: number;
        six: number;
    };
}
</code>```

Is it possible to use mapped types to make all the properties on all depths optional, or do I have to create an interface manually for that?

答:
I've made a library, tsdef that has many common patterns / snippets like this.

For this case, you can use it like the following:

import { DeepPartial } from 'tsdef';

let o: DeepPartial<{a: number}> = {};
```

Title: Recursive Partial<T> in TypeScript

Body:
I have this interface:

export interface UserSettings
{
    one: {
        three: number;
        four: number;
    };
    two: {
        five: number;
        six: number;
    };
}

...and want to turn it into this:

export interface UserSettingsForUpdate
{
    one?: {
        three?: number;
        four?: number;
    };
    two?: {
        five?: number;
        six?: number;
    };
}

...but Partial<UserSettings> produces this:

{
    one?: {
        three: number;
        four: number;
    };
    two?: {
        five: number;
        six: number;
    };
}

Is it possible to use mapped types to make all the properties on all depths optional, or do I have to create an interface manually for that?


问:
Nested For loop Iteration
I am new to python and trying to open a file and print a line that is matching two values (one value from a list and second value being a static value). I get the expected output for first iteration but it looks like the for loop is not running any other iterations.

Below is the code:

text_file = open(Path, 'r')
list_1 = ['One', 'Two', 'Three']
static_value = 'Test'

for term in list_1:
    for line in text_file:
        if term in line and static_value in line:
            print(line)
```

Example contents of file:

One

One Test

Two

Two Test

Three

Three Test

答:
It's possible if you swap your for loops. A more elegant way is to use any() to check for the match like so:

```<code>for line in text_file:
    if any(term in line for term in list_1) and static_value in line:
        print(line)
</code>```

Title: Nested For loop Iteration

Body:
I am new to python and trying to open a file and print a line that is matching two values (one value from a list and second value being a static value). I get the expected output for first iteration but it looks like the for loop is not running any other iterations.

Below is the code:

text_file = open(Path, 'r')
list_1 = ['One', 'Two', 'Three']
static_value = 'Test'

for term in list_1:
    for line in text_file:
        if term in line and static_value in line:
            print(line)

Example contents of file:

One

One Test

Two

Two Test

Three

Three Test

Body:
It's possible if you swap your for loops. A more elegant way is to use any() to check for the match like so:

for line in text_file:
    if any(term in line for term in list_1) and static_value in line:
        print(line)


问:
How to construct a SoQL where clause on a text column using <= operation?
I get an Unrecognized arguments error when trying to apply a <= operation on a SoQL text field. Any help is very much appreciated.

I have tried to apply several different filters on this text field but only the = operation works. When I try any other I get an Unrecognized arguments error.

For example:
https://data.sfgov.org/resource/bbb8-hzi6.json?start24=10:00 (works fine)
but
https://data.sfgov.org/resource/bbb8-hzi6.json?start24<=10:00 (fails)

According to the documentation here https://dev.socrata.com/docs/datatypes/text.html#, <= evaluates strings that are alphanumerically before or equal. I would expect these operations to work on text strings as stated.

答:
The Socrata API uses regular GET parameters. In your example, you're performing simple filtering, which allows you to just perform exact matches.

```<code>https://data.sfgov.org/resource/bbb8-hzi6.json?start24=10:00
</code>```

start24=10:00 has the GET parameter start24 with a value of 10:00

However, in your example with <=. That means something entirely different in the URL world; this means:

start24<=10:00 has the GET parameter start24< with a value of 10:00.

Since you can't use any other operators such as <=, Socrata uses SoQL queries where special keywords start with $; e.g. $where.

```<code>https://data.sfgov.org/resource/bbb8-hzi6.json?$where=start24<="10:00"
</code>```

Now this gets translated to:

$where=start24<="10:00" has the GET parameter $where with a value of start24<="10:00"

Now, this Socrata can handle and will return your results.

Body:
The Socrata API uses regular GET parameters. In your example, you're performing simple filtering, which allows you to just perform exact matches.

https://data.sfgov.org/resource/bbb8-hzi6.json?start24=10:00

start24=10:00 has the GET parameter start24 with a value of 10:00

However, in your example with <=. That means something entirely different in the URL world; this means:

start24<=10:00 has the GET parameter start24< with a value of 10:00.

Since you can't use any other operators such as <=, Socrata uses SoQL queries where special keywords start with $; e.g. $where.

https://data.sfgov.org/resource/bbb8-hzi6.json?$where=start24<="10:00"

Now this gets translated to:

$where=start24<="10:00" has the GET parameter $where with a value of start24<="10:00"

Now, this Socrata can handle and will return your results.


问:
parallelLevel doesn't take effect in replay function
I'm trying function replay in dolphindb to replay my data in order to do some backtesting. But the parameter parallelLevel doesn't effect how fast it replays.

```<code>n = 30000000
quotes = table(100:0, `date`time`sym, [DATE,MINUTE,INT])
tableInsert(quotes, take(2018.12.01,n),09:30m + 1..n, 1..n)
sch = select name,typeString as type from  quotes.schema().colDefs
share streamTable(100:0, sch.name,sch.type) as outQuotes
timer replay([quotes],[`outQuotes], ,`time , ,1)
</code>```

No matter how parallelLevel is set, it always take about 2.2 seconds to replay, why is that?

答:
To replay historical data in a database, we need two steps conceptually: (1) retrieve and prepare the data, and (2) stream the prepared data.

DolphinDB splits the input data to many parts so that even if the input data is huge, the system will not throw OOM. There are two pipelines behind the replay function. One retrieves small parts of data from database. The second pipeline stream the retrieved data. The parameter parallelLevel you mentioned is for the first pipeline only. That is, tell DolphinDB to retrieve small parts of data in parallel. This parameter will not effect the replay speed unless the bottleneck lies in data retrieval and preparation.

Body:
I'm trying function replay in dolphindb to replay my data in order to do some backtesting. But the parameter parallelLevel doesn't effect how fast it replays.

n = 30000000
quotes = table(100:0, `date`time`sym, [DATE,MINUTE,INT])
tableInsert(quotes, take(2018.12.01,n),09:30m + 1..n, 1..n)
sch = select name,typeString as type from  quotes.schema().colDefs
share streamTable(100:0, sch.name,sch.type) as outQuotes
timer replay([quotes],[`outQuotes], ,`time , ,1)

No matter how parallelLevel is set, it always take about 2.2 seconds to replay, why is that?


问:
How to play without "loading" screen in CAF custom player. (HLS with QueueData)
I want seamless playback multiple video contents. (HLS/using queueData)

preloading is works! but when the video changes, "loading" screen is displayed.

How i can playback without "loading" screen in CAF custom player?

答:
Even though a PRELOAD request starts buffering the next item of your queue to reduce the loading time for the next clip, playback is never 'seamless'.

Every time the actual LOAD request comes in, the player will (by default) switch to the BUFFERING state and display the associated UI until it's back to PLAYING

Google's UX guidelines for autoplay are quite clear how the UI should behave on the playback of queues - and you might want to consider adhering to that if you want to publish your app. That being said:

Take a look at your HTML - are you using the <cast-media-player></cast-media-player> custom tags? You can use CSS to set the appearance of all states of the application - check the documentation for details.

--buffering-image and --spinner-image are the customizable elements that you can change here. Again: Those will always pop up when the player enters buffering state, so you will have to come up with something less disturbing than the spinner and default image: A black screen, maybe?

Also, you can not simply use CSS to get rid of those: When the playback is initialized and the queue is built, you most likely still want to show them - so totally disabling them is not an option.
The tricky part is finding appropriate events to dis- and re-enable them:

Consider the MediaFinishedEvent to disable them, and maybe the PLAYER_LOAD_COMPLETE event to restore them to their default value.
(The BUFFERING event might also work but was very unreliable when I tried to use it.)


问:
Move object relative to a point it is always facing causes spiraling orbit
I'm developing a simulation where player should be able to move around inside a 2D circle (referred to as sphere in my code). The players movement must be relative to the center of the circle.

My first step was to make sure the player always faces the center. I got the working fine. However when I tried to do the relative movement it doesn't give my quite the result I'm looking for.

When I move the player close to the center of circle and move sideways (which is relative to the player's facing vector), the player spins around the center but then slowly starts spiraling outwards. The outwards spiral is much more prominent near the center and takes about 8 orbits to reach the inner edge of the circle. Instead the player should be spinning around the center at a constant distance from the center. Why does the player spiral outwards?

Here is the code I use:

```<code>// center of the sphere
Vector3 center = sphereComponent.transform.position - player.transform.position;

// always rotate towards the center so that transform.up is
float angle = Vector3.Angle(center, Vector3.up);
float sign = (center.x < rigidbody.transform.position.x) ? 1.0f : -1.0f;
rigidbody.MoveRotation(angle * sign);

// use the input vector to calculate a vector relative to the objects right and up vectors
Vector2 relativeInputVector =
        (rigidbody.transform.right * player.InputVector.x) +
        (rigidbody.transform.up * player.InputVector.y);

// below is same as doing: rigidbody += relativeInputVector.normalized * 20 * Time.deltaTime;
rigidbody.MovePosition(rigidbody.position + (relativeInputVector.normalized * 20 * Time.deltaTime));
</code>```

So I've tried a few things already:

I thought it was maybe a rounding issue. So I rounded the relativeInputVector's X and Y to the 2nd decimal place. Didn't help.

I normalized the relativeInputVector vector. Didn't seem to do much...

I also thought maybe I should move and then rotate instead of rotate then move. Didn't work.

Now I'm thinking the issue is somewhere in the math (probably where I define relativeInputVector) but I can't find simular use cases regarding this so that I can compare and troubleshoot.

(this is a rather saturated topic when it comes to the keywords I'm search with)

答:
Your intuition would make sense if you were moving to the side then adjusting the direction of your forward vector simultaneously and continuously, but it's being done alternating and discretely.

Consider what happens if Time.deltaTime was absolutely enormous for one frame. You would sidestep a huge amount, maybe even going off the screen in one direction, and then you would adjust your angle to face the center of the circle. That's an exaggerated example but its exactly what's happenening on a small scale.

Here's a diagram showing why your code spirals out:

The way you're doing it, The angle between the circle's radius to the player's position at the beginning of the frame (A in the diagram) and the direction the rigidbody moves (1->2 in the diagram) is a right angle.  At position 1, the radius A might be the correct distance, but the hypotenuse of a right triangle is always longer than each leg, so the new radius at position 2 (B) must be larger, and likewise, C must be larger than B.

The result of that is a spiral motion as you continue to accumulate length to your radius by switching from legs to hypotenuses of these right triangles.

Basically, in order for your code to work, you would need to be making infinitely small triangles--Time.deltaTime would need to be infinitely small--as a right triangle with one infinitely small leg is just a line, its other leg and its hypotenuse are the same length.

Of course if Time.deltaTime were infinitely small, the player would never move. ;)  So, a different approach is needed:

Instead, we can calculate the player's angular velocity and then move the player according to that.

So, dirst determine the player's new distance from the center first, then how many degrees the player would travel around the circle at that radius:

```<code>Vector3 sphereCenterPoint = sphereComponent.transform.position

Vector3 playerToCenter = sphereCenterPoint  - player.transform.position;

float playerVerticalSpeed = 20f * player.InputVector.normalized.y;

newVerticalPosition = rigidbody.position + playerToCenter.normalized
                                         * playerVerticalSpeed * Time.deltaTime;

playerToCenter = sphereComponent.transform.position - newVerticalPosition;

float circumferenceOfPlayerPath = 2f * playerToCenter.magnitude * Mathf.PI;

float playerHorizontalSpeed = 20f * player.InputVector.normalized.x;

float degreesTraveled = ( playerHorizontalSpeed * Time.deltaTime / circumferenceOfPlayerPath ) * 360f;
</code>```

Then, rotate the player's new vertical position around the center point and set the player's rotation and position accordingly. You can use Quaternion.LookRotation to determine the rotation needed to make the rigidbody point forward/up in desired directions:

```<code>// rotates newVerticalPosition around sphereCenterPoint by degreesTraveled around z axis
Vector3 newPosition = Quaternion.Euler(0f,0f, degreesTraveled)
                     * (newVerticalPosition - sphereCenterPoint ) + sphereCenterPoint;

rigidbody.MovePosition(newPosition);

rigidbody.MoveRotation(
        Quaternion.LookRotation(Vector3.forward, sphereCenterPoint - newPosition));
</code>```

To remove a few calculations, you can include the part where you divide by 2 pi and multiply by 360f into the 20f factor:

```<code>Vector3 sphereCenterPoint = sphereComponent.transform.position

Vector3 playerToCenter = sphereCenterPoint  - player.transform.position;

float playerVerticalSpeed = 20f * player.InputVector.normalized.y;

newVerticalPosition = rigidbody.position + playerToCenter.normalized
                                         * playerVerticalSpeed * Time.deltaTime;

playerToCenter = sphereComponent.transform.position - newVerticalPosition;

float playerHorizontalSpeed = 1146f * player.InputVector.normalized.x;

float degreesTraveled = playerHorizontalSpeed * Time.deltaTime / playerToCenter.magnitude;

// rotates newVerticalPosition around sphereCenterPoint by degreesTraveled around z axis
Vector3 newPosition = Quaternion.Euler(0f,0f, degreesTraveled)
                     * (newVerticalPosition - sphereCenterPoint ) + sphereCenterPoint;

rigidbody.MovePosition(newPosition);

rigidbody.MoveRotation(
        Quaternion.LookRotation(Vector3.forward, sphereCenterPoint - newPosition));
</code>```

Body:
I'm developing a simulation where player should be able to move around inside a 2D circle (referred to as sphere in my code). The players movement must be relative to the center of the circle.

My first step was to make sure the player always faces the center. I got the working fine. However when I tried to do the relative movement it doesn't give my quite the result I'm looking for.

When I move the player close to the center of circle and move sideways (which is relative to the player's facing vector), the player spins around the center but then slowly starts spiraling outwards. The outwards spiral is much more prominent near the center and takes about 8 orbits to reach the inner edge of the circle. Instead the player should be spinning around the center at a constant distance from the center. Why does the player spiral outwards?

Here is the code I use:

// center of the sphere
Vector3 center = sphereComponent.transform.position - player.transform.position;

// always rotate towards the center so that transform.up is
float angle = Vector3.Angle(center, Vector3.up);
float sign = (center.x < rigidbody.transform.position.x) ? 1.0f : -1.0f;
rigidbody.MoveRotation(angle * sign);

// use the input vector to calculate a vector relative to the objects right and up vectors
Vector2 relativeInputVector =
        (rigidbody.transform.right * player.InputVector.x) +
        (rigidbody.transform.up * player.InputVector.y);

// below is same as doing: rigidbody += relativeInputVector.normalized * 20 * Time.deltaTime;
rigidbody.MovePosition(rigidbody.position + (relativeInputVector.normalized * 20 * Time.deltaTime));

So I've tried a few things already:

I thought it was maybe a rounding issue. So I rounded the relativeInputVector's X and Y to the 2nd decimal place. Didn't help.

I normalized the relativeInputVector vector. Didn't seem to do much...

I also thought maybe I should move and then rotate instead of rotate then move. Didn't work.

Now I'm thinking the issue is somewhere in the math (probably where I define relativeInputVector) but I can't find simular use cases regarding this so that I can compare and troubleshoot.

(this is a rather saturated topic when it comes to the keywords I'm search with)

Body:
Your intuition would make sense if you were moving to the side then adjusting the direction of your forward vector simultaneously and continuously, but it's being done alternating and discretely.

Consider what happens if Time.deltaTime was absolutely enormous for one frame. You would sidestep a huge amount, maybe even going off the screen in one direction, and then you would adjust your angle to face the center of the circle. That's an exaggerated example but its exactly what's happenening on a small scale.

Here's a diagram showing why your code spirals out:

The way you're doing it, The angle between the circle's radius to the player's position at the beginning of the frame (A in the diagram) and the direction the rigidbody moves (1->2 in the diagram) is a right angle.  At position 1, the radius A might be the correct distance, but the hypotenuse of a right triangle is always longer than each leg, so the new radius at position 2 (B) must be larger, and likewise, C must be larger than B.

The result of that is a spiral motion as you continue to accumulate length to your radius by switching from legs to hypotenuses of these right triangles.

Basically, in order for your code to work, you would need to be making infinitely small triangles--Time.deltaTime would need to be infinitely small--as a right triangle with one infinitely small leg is just a line, its other leg and its hypotenuse are the same length.

Of course if Time.deltaTime were infinitely small, the player would never move. ;)  So, a different approach is needed:

Instead, we can calculate the player's angular velocity and then move the player according to that.

So, dirst determine the player's new distance from the center first, then how many degrees the player would travel around the circle at that radius:

Vector3 sphereCenterPoint = sphereComponent.transform.position

Vector3 playerToCenter = sphereCenterPoint  - player.transform.position;

float playerVerticalSpeed = 20f * player.InputVector.normalized.y;

newVerticalPosition = rigidbody.position + playerToCenter.normalized
                                         * playerVerticalSpeed * Time.deltaTime;

playerToCenter = sphereComponent.transform.position - newVerticalPosition;

float circumferenceOfPlayerPath = 2f * playerToCenter.magnitude * Mathf.PI;

float playerHorizontalSpeed = 20f * player.InputVector.normalized.x;

float degreesTraveled = ( playerHorizontalSpeed * Time.deltaTime / circumferenceOfPlayerPath ) * 360f;

Then, rotate the player's new vertical position around the center point and set the player's rotation and position accordingly. You can use Quaternion.LookRotation to determine the rotation needed to make the rigidbody point forward/up in desired directions:

// rotates newVerticalPosition around sphereCenterPoint by degreesTraveled around z axis
Vector3 newPosition = Quaternion.Euler(0f,0f, degreesTraveled)
                     * (newVerticalPosition - sphereCenterPoint ) + sphereCenterPoint;

rigidbody.MovePosition(newPosition);

rigidbody.MoveRotation(
        Quaternion.LookRotation(Vector3.forward, sphereCenterPoint - newPosition));

To remove a few calculations, you can include the part where you divide by 2 pi and multiply by 360f into the 20f factor:

Vector3 sphereCenterPoint = sphereComponent.transform.position

Vector3 playerToCenter = sphereCenterPoint  - player.transform.position;

float playerVerticalSpeed = 20f * player.InputVector.normalized.y;

newVerticalPosition = rigidbody.position + playerToCenter.normalized
                                         * playerVerticalSpeed * Time.deltaTime;

playerToCenter = sphereComponent.transform.position - newVerticalPosition;

float playerHorizontalSpeed = 1146f * player.InputVector.normalized.x;

float degreesTraveled = playerHorizontalSpeed * Time.deltaTime / playerToCenter.magnitude;

// rotates newVerticalPosition around sphereCenterPoint by degreesTraveled around z axis
Vector3 newPosition = Quaternion.Euler(0f,0f, degreesTraveled)
                     * (newVerticalPosition - sphereCenterPoint ) + sphereCenterPoint;

rigidbody.MovePosition(newPosition);

rigidbody.MoveRotation(
        Quaternion.LookRotation(Vector3.forward, sphereCenterPoint - newPosition));


问:
What is a good design pattern for tracking issues in a class?
I have a class that has a custom equals() method. When I compare two objects using this equals method, not only am I interested in whether or not they are equal, but if they are not equal, what was different about them. Finally, I want to be able to retrieve the differences arising from an unequal situation.

I currently use logging to display where my objects are unequal. This works, but I have a new requirement of being able to extract the actual results of the equals check for display later. I suspect there is an object-oriented design pattern for handling this type of situation.

public class MyClass {
  int x;
  public boolean equals(Object obj) {
    // make sure obj is instance of MyClass
    MyClass that = (MyClass)obj;

    if(this.x != that.x) {
      // issue that I would like to store and reference later, after I call equals
      System.out.println("this.x = " + this.x);
      System.out.println("that.x = " + that.x);
      return false;
    } else {
      // assume equality
      return true
    }
  }
}
```

Are there any good design pattern suggestions where some sort of work is being done, but a secondary object collects information about how well that work was done which can later be retrieved and displayed?

答:
Your problem is that you are trying to use the boolean equals(Object) API for something it was not designed for.  I don't think there is any design pattern that will allow you to do this.

Instead, you should be doing something like this:

```<code>public class Difference {
    private Object thisObject;
    private Object otherObject;
    String difference;
    ...
}

public interface Differenceable {
    /** Report the differences between 'this' and 'other'. ... **/
    public List<Difference> differences(Object other);
}
</code>```

Then implement this for all classes where you want "differenceable" functionality.  For example:

```<code>public class MyClass implements Differenceable {
    int x;
    ...

    public List<Difference> differences(Object obj) {
        List<Difference> diffs = new ArrayList<>();
        if (!(obj instanceof MyClass)) {
             diffs.add(new Difference<>(this, obj, "types differ");
        } else {
             MyClass other = (MyClass) obj;
             if (this.x != other.x) {
                 diffs.add(new Difference<>(this, obj, "field 'x' differs");
             }
             // If fields of 'this' are themselves differenceable, you could
             // recurse and then merge the result lists into 'diffs'.
        }
        return diffs;
    }
}
</code>```

Body:
I have a class that has a custom equals() method. When I compare two objects using this equals method, not only am I interested in whether or not they are equal, but if they are not equal, what was different about them. Finally, I want to be able to retrieve the differences arising from an unequal situation.

I currently use logging to display where my objects are unequal. This works, but I have a new requirement of being able to extract the actual results of the equals check for display later. I suspect there is an object-oriented design pattern for handling this type of situation.

public class MyClass {
  int x;
  public boolean equals(Object obj) {
    // make sure obj is instance of MyClass
    MyClass that = (MyClass)obj;

    if(this.x != that.x) {
      // issue that I would like to store and reference later, after I call equals
      System.out.println("this.x = " + this.x);
      System.out.println("that.x = " + that.x);
      return false;
    } else {
      // assume equality
      return true
    }
  }
}

Are there any good design pattern suggestions where some sort of work is being done, but a secondary object collects information about how well that work was done which can later be retrieved and displayed?

Body:
Your problem is that you are trying to use the boolean equals(Object) API for something it was not designed for.  I don't think there is any design pattern that will allow you to do this.

Instead, you should be doing something like this:

public class Difference {
    private Object thisObject;
    private Object otherObject;
    String difference;
    ...
}

public interface Differenceable {
    /** Report the differences between 'this' and 'other'. ... **/
    public List<Difference> differences(Object other);
}

Then implement this for all classes where you want "differenceable" functionality.  For example:

public class MyClass implements Differenceable {
    int x;
    ...

    public List<Difference> differences(Object obj) {
        List<Difference> diffs = new ArrayList<>();
        if (!(obj instanceof MyClass)) {
             diffs.add(new Difference<>(this, obj, "types differ");
        } else {
             MyClass other = (MyClass) obj;
             if (this.x != other.x) {
                 diffs.add(new Difference<>(this, obj, "field 'x' differs");
             }
             // If fields of 'this' are themselves differenceable, you could
             // recurse and then merge the result lists into 'diffs'.
        }
        return diffs;
    }
}


答:
I am unaware of a particular design pattern for this. One problem with this requirement is that to find out all differences between two unequal objects you would need to continue additional comparisons after the first false result (which is typically not necessary).

If I were doing this I might consider doing a normal equality test and if not equal, kick off a thread to determine why and log the results rather than incorporate such logic in the equals method itself.  This might be done in a special method outside of the equals method.

Title: What is a good design pattern for tracking issues in a class?


问:
Adding member to MailChimp with API not showing in the web gui before i add more
I using the API v3 and createing a list and then adding a member to it, then i going to the web gui https://usxx.admin.mailchimp.com/lists/ and there i dont see the member.

When i then createing a list with a new member the first member shows up in the first list and the new list shows up but no member in the web gui.

I have tried adding two members at the same time but still not showing up any of them, looks like when i adding list number 2 its shows up, some ideas?

Edit: Now after left it and waiting for answer here i reloaded the page with lists and then i got the member for the last list. Is there some delay?

答:
I can confirm that as of this writing MailChimp seems to have a delay. Somewhere between 2 and 5 minutes after adding people to a list - they show up on the UX.

This said I've observed in my tests that the API seems to have updates immediately. My guess is that their UX caches results for a short duration.


问:
How to inject data-model mock into spring controller?
In my unit tests, I need to mock a data-model instance in a spring @Controller, else the return value of the @RequestMapping method gets wrong.

To do this I tried the following:

Create a User mock, which calls user.login() and needs to return "true"

Inject mock object in the LoginController

Stub the login method to return true

Perform POST /Login with MockMVC from spring test

verify that mockUser.login got called

Here is the controller method:

```<code>@RequestMapping(value = "/Login", method = RequestMethod.POST)
  public String updateUI(Locale locale, Model model, @RequestParam("username") String username,
      @RequestParam("hashedPW") String hashedPW, HttpServletRequest request) {
    model.addAttribute("username", username);
    user = new User(username, username, hashedPW.getBytes(), LoginHandler.getInstance());

    boolean loginResult = user.login();
    if(loginResult == true) {
      return "profile";
    }
    String output = "Failed login (" + username + ") requested, locale = " + locale;
    log(output);
    return "home";
  }
</code>```

and my initialization of mock objects with injection:

```<code>@Mock
  private User mockUser;

  @InjectMocks
  private LoginController injectedLoginController;

  @Before
  public void setup() throws ServletException {
    MockitoAnnotations.initMocks(this);
    mvc = MockMvcBuilders.standaloneSetup(injectedLoginController).build();
    LOGFILE = new File("logs/general.log");
  }
</code>```

and finally the unit test:

```<code>@Test
  public void testLoginSuccess() throws Exception {
    String username = "Stefan";
    byte[] hashedPW = "".getBytes();
    when(mockUser.login()).thenReturn(true);
    ResultActions ra = mvc
        .perform(post("/Login").param("username", username).param("hashedPW", hashedPW.toString()))
        .andExpect(status().isOk());

    verify(mockUser).login();
  }
</code>```

All together I expected the User object that is handled by the controller to be of mockUser type instead of User, and the login() method to get called once (accordingly) and return "true".

But all I get is
"Wanted but not invoked: mockUser.login()
 Actually, there was zero interaction with this mock."

I appreciate any suggestions to solve my problem since I am working on this for quite some time now and I don't seem to get the trick.

答:
If you don't want to change your code, you can take help from PowerMockito which can help to mock construction of new objects.

```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest({User.class})
public class ControllerUnderTest {
  // here User is class for which we want to mock object creation
}
</code>```

Now, let's mock object

```<code>@Test
public void testLoginSuccess() throws Exception {
 ....
 User userMock = PowerMockito.createMock(User.class);

 PowerMockito.whenNew(User.class).withArguments(username, username, hashedPW.getBytes(), LoginHandler.getInstance()).thenReturn(userMock);

 expect(userMock.login()).andReturn(true);

 verify(mockUser).login();
 ...
}
</code>```

For more details on powermock, please check this PowerMockito

Body:
In my unit tests, I need to mock a data-model instance in a spring @Controller, else the return value of the @RequestMapping method gets wrong.

To do this I tried the following:

Create a User mock, which calls user.login() and needs to return "true"

Inject mock object in the LoginController

Stub the login method to return true

Perform POST /Login with MockMVC from spring test

verify that mockUser.login got called

Here is the controller method:

@RequestMapping(value = "/Login", method = RequestMethod.POST)
  public String updateUI(Locale locale, Model model, @RequestParam("username") String username,
      @RequestParam("hashedPW") String hashedPW, HttpServletRequest request) {
    model.addAttribute("username", username);
    user = new User(username, username, hashedPW.getBytes(), LoginHandler.getInstance());

    boolean loginResult = user.login();
    if(loginResult == true) {
      return "profile";
    }
    String output = "Failed login (" + username + ") requested, locale = " + locale;
    log(output);
    return "home";
  }

and my initialization of mock objects with injection:

@Mock
  private User mockUser;

  @InjectMocks
  private LoginController injectedLoginController;

  @Before
  public void setup() throws ServletException {
    MockitoAnnotations.initMocks(this);
    mvc = MockMvcBuilders.standaloneSetup(injectedLoginController).build();
    LOGFILE = new File("logs/general.log");
  }

and finally the unit test:

@Test
  public void testLoginSuccess() throws Exception {
    String username = "Stefan";
    byte[] hashedPW = "".getBytes();
    when(mockUser.login()).thenReturn(true);
    ResultActions ra = mvc
        .perform(post("/Login").param("username", username).param("hashedPW", hashedPW.toString()))
        .andExpect(status().isOk());

    verify(mockUser).login();
  }

All together I expected the User object that is handled by the controller to be of mockUser type instead of User, and the login() method to get called once (accordingly) and return "true".

But all I get is
"Wanted but not invoked: mockUser.login()
 Actually, there was zero interaction with this mock."

I appreciate any suggestions to solve my problem since I am working on this for quite some time now and I don't seem to get the trick.

Body:
If you don't want to change your code, you can take help from PowerMockito which can help to mock construction of new objects.

@RunWith(PowerMockRunner.class)
@PrepareForTest({User.class})
public class ControllerUnderTest {
  // here User is class for which we want to mock object creation
}

Now, let's mock object

@Test
public void testLoginSuccess() throws Exception {
 ....
 User userMock = PowerMockito.createMock(User.class);

 PowerMockito.whenNew(User.class).withArguments(username, username, hashedPW.getBytes(), LoginHandler.getInstance()).thenReturn(userMock);

 expect(userMock.login()).andReturn(true);

 verify(mockUser).login();
 ...
}

For more details on powermock, please check this PowerMockito


问:
kubectl pod fails to pull down an AWS ECR image
step 1 sudo $(aws ecr get-login --no-include-email --region xx-xxxx-x)

step 2 curl -LSs https://github.com/fermayo/ecr-k8s-secret/raw/master/gen-secret.sh | bash -

step 3 kubectl describe secret aws-ecr-credentials

```<code>Name:         aws-ecr-credentials
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  kubernetes.io/dockerconfigjson

Data

.dockerconfigjson:  32 bytes
</code>```

step 4 kubectl describe pod x

Warning  Failed     5s               kubelet, ip-10-46-250-151  Failed to pull image "my-account.dkr.ecr.us-east-1.amazonaws.com/my-image:latest": rpc error: code = Unknown desc = Error response from daemon: Get https://my-account.dkr.ecr.us-east-1.amazonaws.com/my-image/latest: no basic auth credentials

Why can't the pod pull down the image?

答:
I too was banging my head on this and realized it was a region mismatch.  I was getting my token from us-east-2 when the image is located in us-west-2.

Snippet from https://docs.aws.amazon.com/AmazonECR/latest/userguide/common-errors-docker.html#error-403

There are times when you may receive an HTTP 403 (Forbidden) error, or the error message no basic auth credentials from the docker push command, even if you have successfully authenticated to Docker using the aws ecr get-login command. The following are some known causes of this issue:

You have authenticated to a different region Authentication requests are tied to specific regions, and cannot be used across regions. For example, if you obtain an authorization token from US West (Oregon), you cannot use it to authenticate against your repositories in US East (N. Virginia). To resolve the issue, ensure that you are using the same region for both authentication and docker push command calls.

Body:
step 1 sudo $(aws ecr get-login --no-include-email --region xx-xxxx-x)

step 2 curl -LSs https://github.com/fermayo/ecr-k8s-secret/raw/master/gen-secret.sh | bash -

step 3 kubectl describe secret aws-ecr-credentials

Name:         aws-ecr-credentials
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  kubernetes.io/dockerconfigjson

Data

.dockerconfigjson:  32 bytes

step 4 kubectl describe pod x

Warning  Failed     5s               kubelet, ip-10-46-250-151  Failed to pull image "my-account.dkr.ecr.us-east-1.amazonaws.com/my-image:latest": rpc error: code = Unknown desc = Error response from daemon: Get https://my-account.dkr.ecr.us-east-1.amazonaws.com/my-image/latest: no basic auth credentials

Why can't the pod pull down the image?


问:
Getting errors not quite sure why this is my first cobol program
Im slowly learning COBOL and am doing some challenges to get better but i am having a weird problem that i cant seem to trace and i wanted to see if anyone else can help

I double and triple checked that what was supposed to be in area A and B where in their proper col numbers

```<code>IDENTIFICATION DIVISION.
    PROGRAM-ID. CIRCLES.

    ENVIRONMENT DIVISION.
    CONFIGURATION SECTION.
    SOURCE-COMPUTER.
    OBJECT-COMPUTER.

    INPUT-OUTPUT SECTION.
    FILE-CONTROL.

    DATA DIVISION.
    FILE SECTION.

    WORKING-STORAGE SECTION.
    01  WS-CONSTANTS.
        05  WS-PI              PIC 9V99999 VALUE 3.14159.
    01   WS-CIRCLE.
        05 WS-AREA              PIC 999V99 VALUE ZEROES.
        05 WS-RADIUS            PIC 9999V99 VALUE ZEROES.
        05 WS-CIRCUMFERENCE     PIC 99999V99 VALUE ZEROES.
    01   WS-DISPLAY-VALUES.
        05 WS-DISPLAY-AREA                     PIC ZZ99.99.
        05 WS-DISPLAY-CIRCUMFERENCE  PIC ZZ99.99.

    PROCEDURE DIVISION.

    0100-PROCESS-RECORDS.

        DISPLAY "Please enter radius of circle: ".
        ACCEPT WS-RADIUS.
        COMPUTE WS-CIRCUMFRENCE = 2 * WS-PI * WS-RADIUS.
        MOVE WS-CIRCUMFRENCE TO WS-DISPLAY-CIRCUMFRENCE.
        DISPLAY "Circle Circumfrence is: ", WS-DISPLAY-CIRCUMFRENCE.
        COMPUTE WS-RADIUS = WS-PI * WS-RADIUS * WS-RADIUS.
        MOVE WS-AREA TO WS-DISPLAY-AREA.
        DISPLAY "Circle area is:  ", WS-DISPLAY-AREA

        STOP RUN

</code>```

compiler messages:

```<code>Circles.cbl:28: error: PROCEDURE DIVISION header missing
Circles.cbl:28: error: syntax error, unexpected level-number
Circles.cbl:29: error: unknown statement '05'
Circles.cbl:30: error: unknown statement '05'
Circles.cbl:34: error: syntax error, unexpected PROCEDURE
Circles.cbl: in paragraph '0100-PROCESS-RECORDS':
Circles.cbl:40: error: 'WS-RADIUS' is not defined
Circles.cbl:41: error: 'WS-CIRCUMFRENCE' is not defined
Circles.cbl:41: error: 'WS-PI' is not defined
Circles.cbl:41: error: 'WS-RADIUS' is not defined
Circles.cbl:42: error: 'WS-CIRCUMFRENCE' is not defined
Circles.cbl:42: error: 'WS-DISPLAY-CIRCUMFRENCE' is not defined
Circles.cbl:43: error: 'WS-DISPLAY-CIRCUM' is not defined
Circles.cbl:44: error: 'WS-RADIUS' is not defined
Circles.cbl:44: error: 'WS-PI' is not defined
Circles.cbl:44: error: 'WS-RADIUS' is not defined
Circles.cbl:44: error: 'WS-RADIUS' is not defined
Circles.cbl:45: error: 'WS-AREA' is not defined
Circles.cbl:45: error: 'WS-DISPLAY-AREA' is not defined
Circles.cbl:46: error: 'WS-DISPLAY-AREA' is not defined
</code>```

答:
In addition to the above suggestions I'd also add change

```<code>COMPUTE WS-RADIUS = WS-PI * WS-RADIUS * WS-RADIUS.
</code>```

to

```<code>COMPUTE WS-AREA = WS-PI * WS-RADIUS * WS-RADIUS.
</code>```

or you'll always print out 0 for area

Body:
Im slowly learning COBOL and am doing some challenges to get better but i am having a weird problem that i cant seem to trace and i wanted to see if anyone else can help

I double and triple checked that what was supposed to be in area A and B where in their proper col numbers

IDENTIFICATION DIVISION.
    PROGRAM-ID. CIRCLES.

    ENVIRONMENT DIVISION.
    CONFIGURATION SECTION.
    SOURCE-COMPUTER.
    OBJECT-COMPUTER.

    INPUT-OUTPUT SECTION.
    FILE-CONTROL.

    DATA DIVISION.
    FILE SECTION.

    WORKING-STORAGE SECTION.
    01  WS-CONSTANTS.
        05  WS-PI              PIC 9V99999 VALUE 3.14159.
    01   WS-CIRCLE.
        05 WS-AREA              PIC 999V99 VALUE ZEROES.
        05 WS-RADIUS            PIC 9999V99 VALUE ZEROES.
        05 WS-CIRCUMFERENCE     PIC 99999V99 VALUE ZEROES.
    01   WS-DISPLAY-VALUES.
        05 WS-DISPLAY-AREA                     PIC ZZ99.99.
        05 WS-DISPLAY-CIRCUMFERENCE  PIC ZZ99.99.

    PROCEDURE DIVISION.

    0100-PROCESS-RECORDS.

        DISPLAY "Please enter radius of circle: ".
        ACCEPT WS-RADIUS.
        COMPUTE WS-CIRCUMFRENCE = 2 * WS-PI * WS-RADIUS.
        MOVE WS-CIRCUMFRENCE TO WS-DISPLAY-CIRCUMFRENCE.
        DISPLAY "Circle Circumfrence is: ", WS-DISPLAY-CIRCUMFRENCE.
        COMPUTE WS-RADIUS = WS-PI * WS-RADIUS * WS-RADIUS.
        MOVE WS-AREA TO WS-DISPLAY-AREA.
        DISPLAY "Circle area is:  ", WS-DISPLAY-AREA

        STOP RUN

compiler messages:

Circles.cbl:28: error: PROCEDURE DIVISION header missing
Circles.cbl:28: error: syntax error, unexpected level-number
Circles.cbl:29: error: unknown statement '05'
Circles.cbl:30: error: unknown statement '05'
Circles.cbl:34: error: syntax error, unexpected PROCEDURE
Circles.cbl: in paragraph '0100-PROCESS-RECORDS':
Circles.cbl:40: error: 'WS-RADIUS' is not defined
Circles.cbl:41: error: 'WS-CIRCUMFRENCE' is not defined
Circles.cbl:41: error: 'WS-PI' is not defined
Circles.cbl:41: error: 'WS-RADIUS' is not defined
Circles.cbl:42: error: 'WS-CIRCUMFRENCE' is not defined
Circles.cbl:42: error: 'WS-DISPLAY-CIRCUMFRENCE' is not defined
Circles.cbl:43: error: 'WS-DISPLAY-CIRCUM' is not defined
Circles.cbl:44: error: 'WS-RADIUS' is not defined
Circles.cbl:44: error: 'WS-PI' is not defined
Circles.cbl:44: error: 'WS-RADIUS' is not defined
Circles.cbl:44: error: 'WS-RADIUS' is not defined
Circles.cbl:45: error: 'WS-AREA' is not defined
Circles.cbl:45: error: 'WS-DISPLAY-AREA' is not defined
Circles.cbl:46: error: 'WS-DISPLAY-AREA' is not defined

Body:
In addition to the above suggestions I'd also add change

COMPUTE WS-RADIUS = WS-PI * WS-RADIUS * WS-RADIUS.

to

COMPUTE WS-AREA = WS-PI * WS-RADIUS * WS-RADIUS.

or you'll always print out 0 for area


问:
Find size of Git repository
What's a simple way to find the size of my Git repository?

And I don't mean du -h on the root directory of my repository. I have a lot of ignored files, so that size would be different from my total repository size. I essentially want to know how much data would be transferred upon cloning my repository.

答:
I think this gives you the total list of all files in the repo history:

```<code>git rev-list --objects --all | git cat-file --batch-check="%(objectsize) %(rest)" | cut -d" " -f1 | paste -s -d + - | bc
</code>```

You can replace --all with a treeish (HEAD, origin/master, etc.) to calculate the size of a branch.

Title: Find size of Git repository

Body:
I think this gives you the total list of all files in the repo history:

git rev-list --objects --all | git cat-file --batch-check="%(objectsize) %(rest)" | cut -d" " -f1 | paste -s -d + - | bc

You can replace --all with a treeish (HEAD, origin/master, etc.) to calculate the size of a branch.


问:
Reactive plot is mapping variable name?
I'm trying to create an reactive plot where you can select an ethnicity in a selectInput() and see the population of that ethnicity in the midwest.

This is my ui:

```<code>ethnicity_sidebar_content <- sidebarPanel(
  selectInput(
    inputId = "ethnicity",
    label = "Select Ethnicity",
    choices = list(
      "Total" = "total",
      "White" = "white",
      "Black" = "black",
      "American Indian" = "amerindian",
      "Asian" = "asian",
      "Other" = "other"
    )
  )
)
ethnicity_main_content <- mainPanel(
  plotOutput("ethnicity_plot")
)
ethnicity_panel <- tabPanel(
  "Midwest by Ethnicity",
  sidebarLayout(
    ethnicity_sidebar_content,
    ethnicity_main_content
  )
)
</code>```

This is my server:

```<code>midwest_poverty <- midwest %>%
  mutate(popbelowpoverty = floor(percbelowpoverty / 100 * poppovertyknown)) %>%
  group_by(state) %>%
  summarise(
    poppovertyknown = sum(poppovertyknown),
    popbelowpoverty = sum(popbelowpoverty)
  ) %>%
  mutate(popabovepoverty = poppovertyknown - popbelowpoverty)

server <- function(input, output) {
  output$ethnicity_plot <- renderPlot({
    p <- ggplot(data = midwest_ethnicity) +
      geom_bar(
        mapping = aes(x = state, y = input$ethnicity),
        stat = "identity"
      )
    p
  })
}
</code>```

When I run shinyApp, I keep getting a bar plot that graphs the column name rather than the data in the column.

Edit: I think this was a simple mistake where I was using aes instead of aes_string

答:
When you write aes(x = state, y = input$ethnicity) in the ggplot call, it will look for variable state in the dataset midwest_ethnicity for x-axis. Same for y, it will look for a variable named White for instance if this is the value in input$ethnicity.

I don't think there is a variable with such a name in your dataset.

If it is the case (White is a variable of your dataset), it could not work if ggplot don't consider input$ethnicity as a string, and not as a value. You can test y = get(input$ethnicity).

Another option as proposed in comments, is to use aes_string() instead of aes().

Title: Reactive plot is mapping variable name?

Body:
I'm trying to create an reactive plot where you can select an ethnicity in a selectInput() and see the population of that ethnicity in the midwest.

This is my ui:

ethnicity_sidebar_content <- sidebarPanel(
  selectInput(
    inputId = "ethnicity",
    label = "Select Ethnicity",
    choices = list(
      "Total" = "total",
      "White" = "white",
      "Black" = "black",
      "American Indian" = "amerindian",
      "Asian" = "asian",
      "Other" = "other"
    )
  )
)
ethnicity_main_content <- mainPanel(
  plotOutput("ethnicity_plot")
)
ethnicity_panel <- tabPanel(
  "Midwest by Ethnicity",
  sidebarLayout(
    ethnicity_sidebar_content,
    ethnicity_main_content
  )
)

This is my server:

midwest_poverty <- midwest %>%
  mutate(popbelowpoverty = floor(percbelowpoverty / 100 * poppovertyknown)) %>%
  group_by(state) %>%
  summarise(
    poppovertyknown = sum(poppovertyknown),
    popbelowpoverty = sum(popbelowpoverty)
  ) %>%
  mutate(popabovepoverty = poppovertyknown - popbelowpoverty)

server <- function(input, output) {
  output$ethnicity_plot <- renderPlot({
    p <- ggplot(data = midwest_ethnicity) +
      geom_bar(
        mapping = aes(x = state, y = input$ethnicity),
        stat = "identity"
      )
    p
  })
}

When I run shinyApp, I keep getting a bar plot that graphs the column name rather than the data in the column.

Edit: I think this was a simple mistake where I was using aes instead of aes_string


问:
How to include HTML file uploaded by user - Django
I'm including ads in my project's html files
i was using GIF files Upload it in the admin and use it like:

```<code>{{ ad.image.url }}
</code>```

but then the client wanted the ad to be HTML file (with js, CSS files)
i thought of:

Upload a zip file containing all files and extract it to media directory but don't know the best way to achieve this

upload each file individually and link it to the ad ID but the problem is what if there were directories not just files?

and the main problem is how to inject/include the HTML file content to my HTML page?

Please share your ideas

答:
you can create an upload page for image / css and js files.

and a single html file stored into models or file.

in your view you can load content of html file then pass it to template then render content of passed parameter

```<code>{{ file_content|safe }}
</code>```

also you can use iframe to show page content

also to create html file you can use one WYSIWYG

Body:
I'm including ads in my project's html files
i was using GIF files Upload it in the admin and use it like:

{{ ad.image.url }}

but then the client wanted the ad to be HTML file (with js, CSS files)
i thought of:

Upload a zip file containing all files and extract it to media directory but don't know the best way to achieve this

upload each file individually and link it to the ad ID but the problem is what if there were directories not just files?

and the main problem is how to inject/include the HTML file content to my HTML page?

Please share your ideas

Body:
you can create an upload page for image / css and js files.

and a single html file stored into models or file.

in your view you can load content of html file then pass it to template then render content of passed parameter

{{ file_content|safe }}

also you can use iframe to show page content

also to create html file you can use one WYSIWYG


问:
How do I interpret the signature of read_until and what is AsyncRead + BufRead in Tokio?
I'm trying to understand asynchronous I/O in Rust. The following code is based on a snippet from Katharina Fey's
Jan 2019 talk which works for me:

```<code>use futures::future::Future;
use std::io::BufReader;
use tokio::io::*;

fn main() {
    let reader = BufReader::new(tokio::io::stdin());
    let buffer = Vec::new();

    println!("Type something:");
    let fut = tokio::io::read_until(reader, b'\n', buffer)
        .and_then(move |(stdin, buffer)| {
            tokio::io::stdout()
                .write_all(&buffer)
                .map_err(|e| panic!(e))
        })
        .map_err(|e| panic!(e));

    tokio::run(fut);
}
</code>```

Before finding that code, I attempted to figure it out from the read_until documentation.

How do I interpret the signature of read_until to use it in a code sample like the one above?

```<code>pub fn read_until<A>(a: A, byte: u8, buf: Vec<u8>) -> ReadUntil<A>
where
    A: AsyncRead + BufRead,
</code>```

Specifically, how can I know from reading the documentation, what are the parameters passed into the and_then closure and the expected result?

答:
Parameters to and_then

Unfortunately the standard layout of the Rust documentation makes futures quite hard to follow.

Starting from the read_until documentation you linked, I can see that it returns ReadUntil.  I'll click on that to go to the ReadUntil documentation.

This return value is described as:

A future which can be used to easily read the contents of a stream into a vector until the delimiter is reached.

I would expect it to implement the Future trait — and I can see that it does. I would also assume that the Item that the future resolves to is some sort of vector, but I don't know exactly what, so I keep digging:

First I look under "Trait implementations" and find impl Future for ReadUntil

I click the [+] expander

Finally I see the associated type Item = (A, Vec<u8>). This means it's a Future that's going to return a pair of values: the A, so it is presumably giving me back the original reader that I passed in, plus a vector of bytes.

When the future resolves to this tuple, I want to attach some additional processing with and_then. This is part of the Future trait, so I can scroll down further to find that function.

fn and_then<F, B>(self, f: F) -> AndThen<Self, B, F>
where
    F: FnOnce(Self::Item) -> B,
    B: IntoFuture<Error = Self::Error>,
    Self: Sized,
```

The function and_then is documented as taking two parameters, but self is passed implicitly by the compiler when using dot syntax to chain functions, which tells us that we can write read_until(A, '\n', buffer).and_then(...).  The second parameter in the documentation, f: F, becomes the first argument passed to and_then in our code.

I can see that f is a closure because the type F is shown as FnOnce(Self::Item) -> B (which if I click through links to the Rust book closure chapter.

The closure f that is passed in takes Self::Item as the parameter. I just found out that Item is (A, Vec<u8>), so I expect to write something like .and_then(|(reader, buffer)| { /* ... /* })

AsyncRead + BufRead

This is putting constraints on what type of reader can be read from. The created BufReader implements BufRead.

Helpfully, Tokio provides an implementation of AsyncRead for BufReader so we don't have to worry about it, we can just go ahead and use the BufReader.

Body:
I'm trying to understand asynchronous I/O in Rust. The following code is based on a snippet from Katharina Fey's
Jan 2019 talk which works for me:

use futures::future::Future;
use std::io::BufReader;
use tokio::io::*;

fn main() {
    let reader = BufReader::new(tokio::io::stdin());
    let buffer = Vec::new();

    println!("Type something:");
    let fut = tokio::io::read_until(reader, b'\n', buffer)
        .and_then(move |(stdin, buffer)| {
            tokio::io::stdout()
                .write_all(&buffer)
                .map_err(|e| panic!(e))
        })
        .map_err(|e| panic!(e));

    tokio::run(fut);
}

Before finding that code, I attempted to figure it out from the read_until documentation.

How do I interpret the signature of read_until to use it in a code sample like the one above?

pub fn read_until(a: A, byte: u8, buf: Vec<u8>) -> ReadUntil
where
    A: AsyncRead + BufRead,

Specifically, how can I know from reading the documentation, what are the parameters passed into the and_then closure and the expected result?

Body:
Parameters to and_then

Unfortunately the standard layout of the Rust documentation makes futures quite hard to follow.

Starting from the read_until documentation you linked, I can see that it returns ReadUntil<A>.  I'll click on that to go to the ReadUntil documentation.

This return value is described as:

A future which can be used to easily read the contents of a stream into a vector until the delimiter is reached.

I would expect it to implement the Future trait — and I can see that it does. I would also assume that the Item that the future resolves to is some sort of vector, but I don't know exactly what, so I keep digging:

First I look under "Trait implementations" and find impl<A> Future for ReadUntil<A>

I click the [+] expander

Finally I see the associated type Item = (A, Vec<u8>). This means it's a Future that's going to return a pair of values: the A, so it is presumably giving me back the original reader that I passed in, plus a vector of bytes.

When the future resolves to this tuple, I want to attach some additional processing with and_then. This is part of the Future trait, so I can scroll down further to find that function.

fn and_then<F, B>(self, f: F) -> AndThen<Self, B, F>
where
    F: FnOnce(Self::Item) -> B,
    B: IntoFuture<Error = Self::Error>,
    Self: Sized,

The function and_then is documented as taking two parameters, but self is passed implicitly by the compiler when using dot syntax to chain functions, which tells us that we can write read_until(A, '\n', buffer).and_then(...).  The second parameter in the documentation, f: F, becomes the first argument passed to and_then in our code.

I can see that f is a closure because the type F is shown as FnOnce(Self::Item) -> B (which if I click through links to the Rust book closure chapter.

The closure f that is passed in takes Self::Item as the parameter. I just found out that Item is (A, Vec<u8>), so I expect to write something like .and_then(|(reader, buffer)| { /* ... /* })

AsyncRead + BufRead

This is putting constraints on what type of reader can be read from. The created BufReader implements BufRead.

Helpfully, Tokio provides an implementation of AsyncRead for BufReader so we don't have to worry about it, we can just go ahead and use the BufReader.


问:
Use CSS To Cause Hover On One Object to Affect Another
Using pure CSS I want an image to appear when hovering over text:

HTML

```<code><h1 id="hover">Hover over me</h1>
<div id="squash">
  <img src="http://askflorine.com/wp-content/uploads/2013/10/temp_quash.jpg" width="100%">
</div>
</code>```

CSS

```<code>#squash {
  display: none;
}

#hover:hover + #squash {
  display: block;
}
</code>```

This works fine unless I put something in between the
 and the
. I know this is because of the CSS selector I am using (+). How could I use an event on one tag to cause a change in CSS on another?

JSFiddle

答:
Depends on what you put in between the 2 parts.  If text encase squash inside the

```<code><p> text here
    <div id="squash"...>
    </div>
</p>
</code>```

Then css changes to

```<code>#hover:hover + p #squash {
</code>```

Body:
Using pure CSS I want an image to appear when hovering over text:

HTML

Hover over me

CSS

#squash {
  display: none;
}

#hover:hover + #squash {
  display: block;
}

This works fine unless I put something in between the
 and the
. I know this is because of the CSS selector I am using (+). How could I use an event on one tag to cause a change in CSS on another?

JSFiddle

Body:
Depends on what you put in between the 2 parts.  If text encase squash inside the

<p> text here
    <div id="squash"...>
    </div>
</p>

Then css changes to

#hover:hover + p #squash {


问:
Flutter Spacer vs Expanded
What is the difference between Expanded and Spacer in Flutter? Why Flutter team added Spacer when we already have Expanded?

答:
Both Spacer and Expanded does the same job that is they fill up the remaining space in a widget like Row or Column. Before Spacer, we had to use

```<code>Expanded(child: Container())
</code>```

And which is not very good. With Spacer we only have to use

```<code>Spacer()
</code>```

So, using Spacer, we prevent us from writing more code and it also gives clear indication that we are just using it to fill up the remaining space. Both of them have same property of flex which defaults to 1. The only difference is we don't have child property which makes sense. In fact Spacer is

```<code>Expanded(child: SizedBox.shrink());
</code>```

TL;DR

```<code>Spacer()
</code>```

is equivalent to

```<code>Expanded(child: Container())
</code>```

Title: Flutter Spacer vs Expanded

Body:
Both Spacer and Expanded does the same job that is they fill up the remaining space in a widget like Row or Column. Before Spacer, we had to use

Expanded(child: Container())

And which is not very good. With Spacer we only have to use

Spacer()

So, using Spacer, we prevent us from writing more code and it also gives clear indication that we are just using it to fill up the remaining space. Both of them have same property of flex which defaults to 1. The only difference is we don't have child property which makes sense. In fact Spacer is

Expanded(child: SizedBox.shrink());

TL;DR

Spacer()

is equivalent to

Expanded(child: Container())


问:
Latest preact and typescript modules passing incorrect type
When trying to react preact + typescript together I am able to pass incorrect types without raising an error.

I am trying to convert our code base from plain JS into preact and add type scripting. Everything installs via NPM fine and I can get the site itself actually running but when running a basic sanity test I notice that inputs reserved solely for numeric entrees accept strings.

I cloned a git with a "working" example of preact + typescript and even in the basic "Hello World" example, I am able to pass a string as an attribute despite there being a string only requirement.

I am probably misunderstanding something basic but this has taken like 3 hours and I am a bit at a dead end.

I have the latest preact, typescript and babel. I could just turn one of these at a time off and see where the breakdown happens but was hoping someone else had an issue similar?

答:
I believe you have a misunderstanding of the purpose of TypeScript.

TypeScript turns the development experience in JavaScript into something closer to a statically typed language like C#.

TypeScript will do nothing to sanitise user input.

If your question is "How can I protect against inputs of the wrong type?", then I believe what you are actually searching for is form validation.


问:
Change color InputLabel Material UI
I have the following input label:

```<code><InputLabel>NAME</InputLabel>
</code>```

My problem is that the text is in White (I don't get why is white, maybe I am doing something wrong), and I can't see white on white. How do I change the color to black?

答:
Please try this: </p>

```<code>const divStyle = {
  color: 'blue',
};
<InputLabel style={divStyle} >NAME</InputLabel>
</code>```

Title: Change color InputLabel Material UI

Body:
I have the following input label:

<InputLabel>NAME</InputLabel>

My problem is that the text is in White (I don't get why is white, maybe I am doing something wrong), and I can't see white on white. How do I change the color to black?

Body:
Please try this:

const divStyle = {
  color: 'blue',
};
<InputLabel style={divStyle} >NAME</InputLabel>


问:
Tabs in eclipse becoming invisible
When using Eclipse (Kepler, on Windows 7 64 bit) from time to time some of the open tabs... disappear. The tab bar is still there, but some tabs just go blank. When I mouse over them tho, they come back and become fully visible.

So this is not a functional problem, just an aesthetic one, but it's really disturbing not to be able to see what tabs are open. Does anyone know how to stop this behavior?

It happens often, but is not prompted by anyhing I do, so I cannot recreate it at will. To further clarify what it looks like, I put together this image in Paint.net:

Thank you in advance.

//LJ

Edit:

I found out what's prompting this behavior. When I build and run the project, the console pops up, then after closing the window, the console automatically hides again, but the tabs it was covering are blank. However, as stated earlier, they do come back if I hover over them. However, I still do not know how to fix this. Here is a gif composed of screenshots showing this behavior in-action:

答:
I had the same issue with my Eclipse Jee 2018-09 on Windows 10.
To fix this issue try the following steps:
right click on eclipse icon -> Compatibility -> Change High DPI settings

Restart eclipse.

Title: Tabs in eclipse becoming invisible


问:
Turn extraction list to csv file
I have uploaded a raster file and polyline shapefile into R and use the extract function to to extract the data from every pixel along the polyline. How do I turn the list output by extract into a CSV file?

答:
If I understand what it is you're asking, I think you could resolve your situation by using unlist().</p>

```<code>d <- c(1:10)      # creates a sample data frame to use

d <- as.list(d)   # converts the data frame into a list

d <- unlist(d)    # converts the list into a vector
</code>```

Title: Turn extraction list to csv file

Body:
If I understand what it is you're asking, I think you could resolve your situation by using unlist().

d <- c(1:10)      # creates a sample data frame to use

d <- as.list(d)   # converts the data frame into a list

d <- unlist(d)    # converts the list into a vector


问:
Unattended/automated Linux device key management (certs for accessing update servers)
I am currently working on a customized media center/box product for my employer. It's basically a Raspberry Pi 3b+ running Raspian, configured to auto-update periodically via apt. The device accesses binaries for proprietary applications via a private, secured apt repo, using a pre-installed certificate on the device.

Right now, the certificate on the device is set to never expire, but going forward, we'd like to configure the certificate to expire every 4 months. We also plan to deploy a unique certificate per device we ship, so the certs can be revoked (i.e. in case the customer reports the device as stolen).

Is there a way, via apt or OpenStack/Barbican KMS to:

Update the certs for apt-repo access on the device periodically.

Setup key-encryption-keys (KEK) on the device, if we need the device to be able to download sensitive data, such as an in-memory cached copy of customer info.

Provide a mechanism for a new key to be deployed on the device if the currently-used key has expired (i.e. the user hasn't connected the device to the internet for more than 4 months). Trying to wrap my head around this one, since the device now (in this state) has an expired certificate, and I can't determine how to let it be trusted to pull a new one.

Allow keys to be tracked, revoked, and de-commissioned.

Thank you.

答:
Is there a way I could use Barbican to:
  * Update the certs for apt-repo access on the device periodically.

Barbican used to have an interface to issue certs, but this was
removed.  Therefore barbican is simply a service to generate and store
secrets.

You could use something like certmonger.  certmonger is a client side
daemon that generates cert requests and submits them to a CA.  It then
tracks those certs and requests new ones when the certs are going to
expire.

Setup key-encryption-keys (KEK) on the device, if we need the
  device to be able to download sensitive data, such as an in-memory
  cached copy of customer info.

To use barbican, you need to be able to authenticate and retrieve
something like a keystone token.  Once you have that, you can use
barbican to generate key encryption keys (which would be stored in the
barbican database) and download them to the device using the secret
retrieval API.

Do you need/want the KEK's escrowed like this though?

Provide a mechanism for a new key to be deployed on the device if
  the currently-used key has expired (i.e. the user hasn't connected
  the device to the internet for more than 4 months).

Barbican has no mechanism for this.  This is client side tooling that
would need to be written.  You'd need to think about authentication.

Allow keys to be tracked, revoked, and de-commissioned.

Same as above.  Barbican has no mechanism for this.