问:
imutils.resize will not get the right shape: expected conv2d_1_input to have shape (64, 64, 3) but got array with shape (91, 64, 3)
In my model file I have already set the inputshape to (64,64,3) width=64, height=64, and 3 channels but when I executed the file I got an error expected conv2d_1_input to have shape (64, 64, 3) but got array with shape (91, 64, 3) as shown below. What does (91, 64, 3) means and why did I get that error? How can I fix it? Please help

the error I got

```<code>ValueError: Error when checking input: expected conv2d_1_input to have shape (64, 64, 3) but got array with shape (91, 64, 3)
</code>```

lenet.py

```<code>from keras.models import Sequential
from keras.layers.convolutional import MaxPooling2D, Conv2D
from keras.layers.core import Activation, Dense, Flatten
from keras import backend as K

class LeNet:
    @staticmethod
    def build(width, height, depth, classes):
        #initialize the model
        model = Sequential()
        inputShpage = (height, width, depth)

        # if we are using "channel first" update the input shape
        if K.image_data_format() == "channels_first":
            inputShpage = (depth, height, width)

        # first set of CONV => RELU => MaxPooling
        model.add(Conv2D(32, (3, 3), padding="same", input_shape=inputShpage))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))

        # second set of CONV => RELU => MaxPooling
        model.add(Conv2D(32, (3, 3), padding="same"))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))

        # FC => RELU layer
        model.add(Flatten())
        model.add(Dense(500))
        model.add(Activation("relu"))

        # softmax classifier for probability
        model.add(Dense(classes))
        model.add(Activation("softmax"))

        # return the constructed network architecture
        return model
</code>```

model.py

```<code>from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from keras.preprocessing.image import img_to_array
from keras.utils import np_utils
from lenet import LeNet
from imutils import paths
import matplotlib.pyplot as plt
import numpy as np
import argparse
import imutils
import cv2
import os

# construct the argument parse and parse the argument
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True, help="path to the dataset")
ap.add_argument("-m", "--model", required=True, help="path to the output model or saved model")
args = vars(ap.parse_args())

# initialize the list of data and label
data = []
labels = []

for imagePath in sorted(list(paths.list_images(args["dataset"]))):
    # load the image, preprocessing it and store it in the data list
    image = cv2.imread(imagePath)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = imutils.resize(image, width=64)
    image = img_to_array(image)
    data.append(image)

    # extract the class label from the image path and update the labels list
    label = imagePath.split(os.path.sep)[-3]
    label = "Hong" if label == "hong" else "Not Hong"
    labels.append(label)

    # scale the raw pixel intensities to the range [0,1]
    data = np.array(data, dtype="float") / 255.0
    label = np.array(labels)

    # convert labels from integers to vectors
    le = LabelEncoder().fit(labels)
    labels = np_utils.to_categorical(le.transform(labels), 2)

    # account for skew in the labeled data
    classTotals = labels.sum(axis=0)
    classWeight = classTotals.max() / classTotals

    # split the data into training_set and test_set
    (trainX, testX, trainY, testY) = train_test_split(data, labels,
                                                    test_size=0.33,
                                                    random_state=42)

    # initialize the model
    print("[ WORKING ON MODEL ] compiling model.....")
    model = LeNet.build(width=64, height=64, depth=3, classes=2)
    model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])

    # train the network
    print("[ WORKING ON NETWORK ] traning the network.....")
    H = model.fit(trainX, trainY, validation_data=(testX, testY),
                class_weight=classWeight, batch_size=32, epochs=25, verbose=1)

    # evaluate the network
    print("[ WORKING ON NETWORK ] evaluating the network.....")
    predictions = model.predict(testX, batch_size=32)
    print(classification_report(testY.argmax(axis=1), predictions.argmax(axis=1),
                                target_names=le.classes_))

    # saving the model
    print("[ WORKING ON NETWORK ] serializing network.....")
    model.save(args["model"])
</code>```

答:
imutils.resize() keeps the aspect ratio of a picture, so you will only be able to specify either width or height, but not both. Since you may need to change the aspect ratio to make it fit into your neural network, I suggest you use cv2.resize().

```<code>image = cv2.resize(image, (64, 64))
</code>```

instead of this:

```<code>image = imutils.resize(image, width=64)
</code>```

Body:
In my model file I have already set the inputshape to (64,64,3) width=64, height=64, and 3 channels but when I executed the file I got an error expected conv2d_1_input to have shape (64, 64, 3) but got array with shape (91, 64, 3) as shown below. What does (91, 64, 3) means and why did I get that error? How can I fix it? Please help

the error I got

ValueError: Error when checking input: expected conv2d_1_input to have shape (64, 64, 3) but got array with shape (91, 64, 3)

lenet.py

from keras.models import Sequential
from keras.layers.convolutional import MaxPooling2D, Conv2D
from keras.layers.core import Activation, Dense, Flatten
from keras import backend as K

class LeNet:
    @staticmethod
    def build(width, height, depth, classes):
        #initialize the model
        model = Sequential()
        inputShpage = (height, width, depth)

        # if we are using "channel first" update the input shape
        if K.image_data_format() == "channels_first":
            inputShpage = (depth, height, width)

        # first set of CONV => RELU => MaxPooling
        model.add(Conv2D(32, (3, 3), padding="same", input_shape=inputShpage))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))

        # second set of CONV => RELU => MaxPooling
        model.add(Conv2D(32, (3, 3), padding="same"))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))

        # FC => RELU layer
        model.add(Flatten())
        model.add(Dense(500))
        model.add(Activation("relu"))

        # softmax classifier for probability
        model.add(Dense(classes))
        model.add(Activation("softmax"))

        # return the constructed network architecture
        return model

model.py

from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from keras.preprocessing.image import img_to_array
from keras.utils import np_utils
from lenet import LeNet
from imutils import paths
import matplotlib.pyplot as plt
import numpy as np
import argparse
import imutils
import cv2
import os

# construct the argument parse and parse the argument
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True, help="path to the dataset")
ap.add_argument("-m", "--model", required=True, help="path to the output model or saved model")
args = vars(ap.parse_args())

# initialize the list of data and label
data = []
labels = []

for imagePath in sorted(list(paths.list_images(args["dataset"]))):
    # load the image, preprocessing it and store it in the data list
    image = cv2.imread(imagePath)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = imutils.resize(image, width=64)
    image = img_to_array(image)
    data.append(image)

    # extract the class label from the image path and update the labels list
    label = imagePath.split(os.path.sep)[-3]
    label = "Hong" if label == "hong" else "Not Hong"
    labels.append(label)

    # scale the raw pixel intensities to the range [0,1]
    data = np.array(data, dtype="float") / 255.0
    label = np.array(labels)

    # convert labels from integers to vectors
    le = LabelEncoder().fit(labels)
    labels = np_utils.to_categorical(le.transform(labels), 2)

    # account for skew in the labeled data
    classTotals = labels.sum(axis=0)
    classWeight = classTotals.max() / classTotals

    # split the data into training_set and test_set
    (trainX, testX, trainY, testY) = train_test_split(data, labels,
                                                    test_size=0.33,
                                                    random_state=42)

    # initialize the model
    print("[ WORKING ON MODEL ] compiling model.....")
    model = LeNet.build(width=64, height=64, depth=3, classes=2)
    model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])

    # train the network
    print("[ WORKING ON NETWORK ] traning the network.....")
    H = model.fit(trainX, trainY, validation_data=(testX, testY),
                class_weight=classWeight, batch_size=32, epochs=25, verbose=1)

    # evaluate the network
    print("[ WORKING ON NETWORK ] evaluating the network.....")
    predictions = model.predict(testX, batch_size=32)
    print(classification_report(testY.argmax(axis=1), predictions.argmax(axis=1),
                                target_names=le.classes_))

    # saving the model
    print("[ WORKING ON NETWORK ] serializing network.....")
    model.save(args["model"])

Body:
imutils.resize() keeps the aspect ratio of a picture, so you will only be able to specify either width or height, but not both. Since you may need to change the aspect ratio to make it fit into your neural network, I suggest you use cv2.resize().

image = cv2.resize(image, (64, 64))

instead of this:

image = imutils.resize(image, width=64)


来源: stackexchange

问:
Entity Framework exception: No suitable constructor found for entity type 'CultureInfo'
I have this:

model class

```<code>public class BusinessSelectList
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsBusinessGroup { get; set; }
    [NotMapped]
    public bool IsSelected { get; set; } = false;
}
</code>```

DbContext

```<code>public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    }

    public virtual DbQuery<BusinessSelectList> BusinessSelectList { get; set;

    /** other virtual DbQuery properties **/
}
</code>```

Repository

```<code>public class BusinessRepository :IBusinessRepository
{
    private readonly IHttpContextAccessor _httpAccessor;
    private readonly AppDbContext _context;

    public BusinessRepository(AppDbContext context, IHttpContextAccessor httpAccessor)
    {
        _context = context;
        _httpAccessor = httpAccessor;
    }

    public IEnumerable<BusinessSelectList> GetAsSelectList()
    {
        var query = @"exec webApp.usp_Business_GetAsSelectList @user";
        var p1 = new SqlParameter("user", _httpAccessor.HttpContext.User.Identity.Name);
        return _context.BusinessSelectList.FromSql(query, p1).ToList();
    }
}
</code>```

Error

Entity Framework exception: No suitable constructor found for entity
  type 'CultureInfo'

I tried to search for a solution, but I did not find any. What can be wrong here? :/

The full exception is:

```<code>{System.InvalidOperationException: No suitable constructor found for entity type 'CultureInfo'. The following parameters could not be bound to properties of the entity: 'name', 'name', 'useUserOverride', 'cultureData', 'isReadOnly', 'culture', 'culture', 'useUserOverride', 'cultureName', 'textAndCompareCultureName'.
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConstructorBindingConvention.Apply(InternalModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelBuilt(InternalModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelBuilt(InternalModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.Validate()
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.<>c__DisplayClass5_0.<GetModel>b__1()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy`1.CreateValue()
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
   at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_1(IServiceProvider p)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_Model()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbQuery`1.get_EntityType()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbQuery`1.get_EntityQueryable()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbQuery`1.System.Linq.IQueryable.get_Provider()
   at Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSql[TEntity](IQueryable`1 source, RawSqlString sql, Object[] parameters)
   at MBPT.CoreWeb.Repository.BusinessRepository.GetAsSelectList() in C:\Users\czurbanlu\Source\Workspaces\Workspace\MBPT\MBPT.CoreWeb\MBPT.CoreWeb\Repository\BusinessRepository.cs:line 32}
</code>```

答:
I had this same problem as well. In my case I had a near empty data access layer project. The problem came and went as I created a navigation link to an entity type that is not available in the DbContext as a DbSet.

for example the code underneath gave the same problem OP had:

```<code>    public class Organization
    {
        [Key]
        public Guid OrganizationId { get; set; }
        public string Name { get; set; }

        // Navigation properties
        public virtual ICollection<Pipeline> Pipelines { get; set; }
    }

    public class MyContext : DbContext
    {
        public MyContext()
        {
        }

        public MyContext(DbContextOptions<MyContext> dbContextOptions) : base(dbContextOptions)
        {

        }

        public DbSet<Organization> Organizations { get; set; }
}
</code>```

While this code didn't:

```<code>    public class Organization
    {
        [Key]
        public Guid OrganizationId { get; set; }
        public string Name { get; set; }

        // Navigation properties
 // COMMENTED OUT       public virtual ICollection<Pipeline> Pipelines { get; set; }
    }

    public class MyContext : DbContext
    {
        public MyContext()
        {
        }

        public MyContext(DbContextOptions<MyContext> dbContextOptions) : base(dbContextOptions)
        {

        }

        public DbSet<Organization> Organizations { get; set; }
}
</code>```

The problem could be solved in two ways:

out commenting the navigation link

adding property DbSet<Pipeline> to the DbContext.

ContentLicense: CC BY-SA 4.0

Body:
I have this:

model class

public class BusinessSelectList
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsBusinessGroup { get; set; }
    [NotMapped]
    public bool IsSelected { get; set; } = false;
}

DbContext

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    }

    public virtual DbQuery<BusinessSelectList> BusinessSelectList { get; set;

    /** other virtual DbQuery properties **/
}

Repository

public class BusinessRepository :IBusinessRepository
{
    private readonly IHttpContextAccessor _httpAccessor;
    private readonly AppDbContext _context;

    public BusinessRepository(AppDbContext context, IHttpContextAccessor httpAccessor)
    {
        _context = context;
        _httpAccessor = httpAccessor;
    }

    public IEnumerable<BusinessSelectList> GetAsSelectList()
    {
        var query = @"exec webApp.usp_Business_GetAsSelectList @user";
        var p1 = new SqlParameter("user", _httpAccessor.HttpContext.User.Identity.Name);
        return _context.BusinessSelectList.FromSql(query, p1).ToList();
    }
}

Error

Entity Framework exception: No suitable constructor found for entity
  type 'CultureInfo'

I tried to search for a solution, but I did not find any. What can be wrong here? :/

The full exception is:

{System.InvalidOperationException: No suitable constructor found for entity type 'CultureInfo'. The following parameters could not be bound to properties of the entity: 'name', 'name', 'useUserOverride', 'cultureData', 'isReadOnly', 'culture', 'culture', 'useUserOverride', 'cultureName', 'textAndCompareCultureName'.
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConstructorBindingConvention.Apply(InternalModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelBuilt(InternalModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelBuilt(InternalModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.Validate()
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.<>c__DisplayClass5_0.<GetModel>b__1()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy`1.CreateValue()
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
   at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_1(IServiceProvider p)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_Model()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbQuery`1.get_EntityType()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbQuery`1.get_EntityQueryable()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbQuery`1.System.Linq.IQueryable.get_Provider()
   at Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSql[TEntity](IQueryable`1 source, RawSqlString sql, Object[] parameters)
   at MBPT.CoreWeb.Repository.BusinessRepository.GetAsSelectList() in C:\Users\czurbanlu\Source\Workspaces\Workspace\MBPT\MBPT.CoreWeb\MBPT.CoreWeb\Repository\BusinessRepository.cs:line 32}

Body:
I had this same problem as well. In my case I had a near empty data access layer project. The problem came and went as I created a navigation link to an entity type that is not available in the DbContext as a DbSet.

for example the code underneath gave the same problem OP had:

    public class Organization
    {
        [Key]
        public Guid OrganizationId { get; set; }
        public string Name { get; set; }

        // Navigation properties
        public virtual ICollection<Pipeline> Pipelines { get; set; }
    }

    public class MyContext : DbContext
    {
        public MyContext()
        {
        }

        public MyContext(DbContextOptions<MyContext> dbContextOptions) : base(dbContextOptions)
        {

        }

        public DbSet<Organization> Organizations { get; set; }
}

While this code didn't:

    public class Organization
    {
        [Key]
        public Guid OrganizationId { get; set; }
        public string Name { get; set; }

        // Navigation properties
 // COMMENTED OUT       public virtual ICollection<Pipeline> Pipelines { get; set; }
    }

    public class MyContext : DbContext
    {
        public MyContext()
        {
        }

        public MyContext(DbContextOptions<MyContext> dbContextOptions) : base(dbContextOptions)
        {

        }

        public DbSet<Organization> Organizations { get; set; }
}

The problem could be solved in two ways:

out commenting the navigation link

adding property DbSet<Pipeline> to the DbContext.


问:
Create a column to indicate the presence of a value in other columns
I have a dataset with symptoms (20+), the symptoms are categorized as Yes/No/Unknown. I would like to create a new column which indicates if the subject (ID) has no symptoms (I'm defining this as they have no symptoms with 'Yes').

I've got a sample dataset below and I can create a column as desired but it feels like there must be a better/cleaner way just using dplyr::mutate() rather than the filtering and joining that I'm doing?

library(dplyr)

test <- tibble(
  ID = c(1:10),
  col1 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE),
  col2 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE),
  col3 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE)
)

left_join(test, test %>%
  filter_at(vars(col1:col3), any_vars(. == "Yes")) %>%
  mutate(any_symptoms = "Yes") %>%
  select(ID, any_symptoms),
by = "ID"
) %>%
  mutate(any_symptoms = recode(any_symptoms, .missing = "No"))
#> # A tibble: 10 x 5
#>       ID col1    col2    col3    any_symptoms
#>    <int> <chr>   <chr>   <chr>   <chr>
#>  1     1 Unknown Unknown Unknown No
#>  2     2 Unknown No      No      No
#>  3     3 Yes     Yes     Unknown Yes
#>  4     4 No      Unknown Unknown No
#>  5     5 No      No      Unknown No
#>  6     6 Unknown Yes     Unknown Yes
#>  7     7 Yes     Unknown Unknown Yes
#>  8     8 No      No      No      No
#>  9     9 No      Unknown Unknown No
#> 10    10 No      No      No      No
```

Created on 2020-05-29 by the reprex package (v0.3.0)

答:
This works, but might be a bit annoying if you have 20 columns: </p>

```<code>test %>% mutate(any_symptoms = case_when(grepl("Yes", paste(col1, col2, col3), fixed = TRUE) ~ "Yes", TRUE ~ "No"))
</code>```

Body:
I have a dataset with symptoms (20+), the symptoms are categorized as Yes/No/Unknown. I would like to create a new column which indicates if the subject (ID) has no symptoms (I'm defining this as they have no symptoms with 'Yes').

I've got a sample dataset below and I can create a column as desired but it feels like there must be a better/cleaner way just using dplyr::mutate() rather than the filtering and joining that I'm doing?

library(dplyr)

test <- tibble(
  ID = c(1:10),
  col1 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE),
  col2 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE),
  col3 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE)
)

left_join(test, test %>%
  filter_at(vars(col1:col3), any_vars(. == "Yes")) %>%
  mutate(any_symptoms = "Yes") %>%
  select(ID, any_symptoms),
by = "ID"
) %>%
  mutate(any_symptoms = recode(any_symptoms, .missing = "No"))
#> # A tibble: 10 x 5
#>       ID col1    col2    col3    any_symptoms
#>    <int> <chr>   <chr>   <chr>   <chr>
#>  1     1 Unknown Unknown Unknown No
#>  2     2 Unknown No      No      No
#>  3     3 Yes     Yes     Unknown Yes
#>  4     4 No      Unknown Unknown No
#>  5     5 No      No      Unknown No
#>  6     6 Unknown Yes     Unknown Yes
#>  7     7 Yes     Unknown Unknown Yes
#>  8     8 No      No      No      No
#>  9     9 No      Unknown Unknown No
#> 10    10 No      No      No      No

Created on 2020-05-29 by the reprex package (v0.3.0)

Body:
This works, but might be a bit annoying if you have 20 columns:

test %>% mutate(any_symptoms = case_when(grepl("Yes", paste(col1, col2, col3), fixed = TRUE) ~ "Yes", TRUE ~ "No"))


问:
Empty Square Brackets in Javascript?
I came across this code in https://upmostly.com/tutorials/setinterval-in-react-components-using-hooks:

```<code>useEffect(() => {
  const interval = setInterval(() => {
    console.log('This will run every second!');
  }, 1000);
  return () => clearInterval(interval);
}, []);
</code>```

I am curious what the square brackets [] at the end do? According to this site https://reactjs.org/docs/hooks-effect.html, we can use useEffect() without them.

答:
This code is used to mimic the properties of componentDidMount() in class based components. That is, it will only get invoked when the component is mounted.

If we don't specify an empty array ([]) as the second argument of the useEffect hook, the hook will exhibit the behaviour of an componentDidUpdate. It means every time some prop's value changes, the useEffect hook will be triggered.

The second array argument allows you to specify which prop trigger the userEffect() callback when their value changes

Title: Empty Square Brackets in Javascript?

Body:
I came across this code in https://upmostly.com/tutorials/setinterval-in-react-components-using-hooks:

useEffect(() => {
  const interval = setInterval(() => {
    console.log('This will run every second!');
  }, 1000);
  return () => clearInterval(interval);
}, []);

I am curious what the square brackets [] at the end do? According to this site https://reactjs.org/docs/hooks-effect.html, we can use useEffect() without them.


问:
Create JSX tree from flat Array with recursive function in react
I really need your help to create a JSX tree from a flat array in react using recursive function.

For the moment only the items 1 to 6 are correctly displayed and the recursion is stopped after

1) my flat JSON data is : (but it could have more than 1000 items)

```<code>const itemsData = [
{
  "Level": 1,
  "Type of activity": "Consolidated task",
  "ID": 118027222233,
  "Name": "Name 1"
},
{
  "Level": 2,
  "Type of activity": "Consolidated task",
  "ID": 118636886633,
  "Name": "Name 2"
},
{
  "Level": 3,
  "Type of activity": "Consolidated task",
  "ID": 118637048333,
  "Name": "Name 3"
},
{
  "Level": 4,
  "Type of activity": "task",
  "ID": 118637035433,
  "Name": "Name 4"
},
{
  "Level": 4,
  "Type of activity": "task",
  "ID": 118841127933,
  "Name": "Name 5"
},
{
  "Level": 4,
  "Type of activity": "task",
  "ID": 118841156833,
  "Name": "Name 6"
},
{
  "Level": 3,
  "Type of activity": "Consolidated task",
  "ID": 118637046733,
  "Name": "Name 9"
},
{
  "Level": 4,
  "Type of activity": "Consolidated task",
  "ID": 118744514633,
  "Name": "Name 10"
},
{
  "Level": 5,
  "Type of activity": "task",
  "ID": 118637033033,
  "Name": "Name 11"
},
{
  "Level": 5,
  "Type of activity": "task",
  "ID": 118637031033,
  "Name": "Name 13"
},
{
  "Level": 2,
  "Type of activity": "Consolidated task",
  "ID": 118636886633,
  "Name": "Name 19"
},
{
  "Level": 3,
  "Type of activity": "task",
  "ID": 118637048333,
  "Name": "Name 20"
},
{
  "Level": 3,
  "Type of activity": "task",
  "ID": 118637048333,
  "Name": "Name 21"
}]
</code>```

2) My current recursive function looks like that :
But only Item 1 to 6 are correctly displayed.

```<code>const RecursiveFunction = ({currentItem, currentLevel}) => {

//LOOP  AS LONG AS CURRENTITEM < ITEMS DATA LENGTH
while(currentItem < itemsData.length){

    //IF CONSOLODATED TASK CREATE CONTAINER
    if(itemsData[currentItem]["Type of activity"] === "Consolidated task"){

        //TEST IF CHILD RELATED TO LEVEL
        if(currentLevel < itemsData[currentItem].Level ){

            //LINE COUNTER
            currentItem++;

            //RETURN
            return (
                <div className="conso-container">
                    <div className="conso-title">
                        {itemsData[currentItem - 1].Name}
                    </div>
                    <RecursiveFunction currentItem={currentItem} currentLevel={itemsData[currentItem-1].Level} />
                </div>
            )
        }

    }else{

        //CURRENT TASK LIST ON A BLOCK
        let taskList = [];

        //WHILE IS A TASK
        while(currentItem < itemsData.length && itemsData[currentItem]["Type of activity"] !== "Consolidated task"){

            //LIST ALL THE TASK
            taskList.push(<div className="task-title">{itemsData[currentItem].Name}</div>)
            currentItem++;

        }

        // RETURN
        return (
            <div className="task-container">
                {taskList}
            </div>
        )
    }
}}
</code>```

3)My render is

```<code>class RoadMapItems extends React.Component {

render(){
    return(
        <div className="tree">
            <RecursiveFunction currentItem={0} currentLevel={0} />
        </div>
    )
}}export default RoadMapItems;
</code>```

答:
This should work. It was a bit harder than I initially thought, haha.

You do need to convert to a nested data structure and then to map that recursively to give the desired output:

Full demo below and here: https://codepen.io/Alexander9111/pen/pojXBWX

function MyTable(props) {
  const initState = [
    {
      Level: 1,
      "Type of activity": "Consolidated task",
      ID: 118027222233,
      Name: "Name 1"
    },
    {
      Level: 2,
      "Type of activity": "Consolidated task",
      ID: 118636886633,
      Name: "Name 2"
    },
    {
      Level: 3,
      "Type of activity": "Consolidated task",
      ID: 118637048333,
      Name: "Name 3"
    },
    {
      Level: 4,
      "Type of activity": "task",
      ID: 118637035433,
      Name: "Name 4"
    },
    {
      Level: 4,
      "Type of activity": "task",
      ID: 118841127933,
      Name: "Name 5"
    },
    {
      Level: 4,
      "Type of activity": "task",
      ID: 118841156833,
      Name: "Name 6"
    },
    {
      Level: 3,
      "Type of activity": "Consolidated task",
      ID: 118637046733,
      Name: "Name 9"
    },
    {
      Level: 4,
      "Type of activity": "Consolidated task",
      ID: 118744514633,
      Name: "Name 10"
    },
    {
      Level: 5,
      "Type of activity": "task",
      ID: 118637033033,
      Name: "Name 11"
    },
    {
      Level: 5,
      "Type of activity": "task",
      ID: 118637031033,
      Name: "Name 13"
    },
    {
      Level: 2,
      "Type of activity": "Consolidated task",
      ID: 118636886633,
      Name: "Name 19"
    },
    {
      Level: 3,
      "Type of activity": "task",
      ID: 118637048333,
      Name: "Name 20"
    },
    {
      Level: 3,
      "Type of activity": "task",
      ID: 118637048333,
      Name: "Name 21"
    },
    {
      Level: 2,
      "Type of activity": "Consolidated task",
      ID: 128637048333,
      Name: "Name 22"
    },
    {
      Level: 3,
      "Type of activity": "task",
      ID: 138637048333,
      Name: "Name 23"
    },
    {
      Level: 1,
      "Type of activity": "Consolidated task",
      ID: 148637048333,
      Name: "Name 24"
    },
    {
      Level: 2,
      "Type of activity": "task",
      ID: 158637048333,
      Name: "Name 25"
    }
  ];
  const [state, setState] = React.useState(initState);

  const table = (

        {Object.keys(state[0]).map((key) => (
          {key}
        ))}

      {state.map((item) => (

          {Object.values(item).map((val) => (
            {val}
          ))}

      ))}

  );

  let currPointer = null;
  const listOfPointers = [];
  const nestedArrs = state.reduce((aggArr, item) => {
    //console.log(listOfPointers)
    if (item.Level == 1) {
      aggArr.push(item);
    }
    else if (item.Level > currPointer.Level) {
      currPointer.children.push(item);
    }
    else if (item.Level <= currPointer.Level) {
      while (item.Level <= currPointer.Level) {
        listOfPointers.pop();
        currPointer = listOfPointers[listOfPointers.length - 1];
      }
      currPointer.children.push(item);
    }

    item.children = [];
    currPointer = item;
    listOfPointers.push(currPointer);

    return aggArr;
  }, []);

  //console.log(nestedArrs);

  const nestedDivs = (

      {(function mapChildren(data) {
        return data.map((d, i) => {
          if (d["Type of activity"] != "task") {
            return (

                {d.Level + " : " + d.Name}
                {mapChildren(d.children)}

            );
          } else {
            return (

                {d.Level + " : " + d.Name}

            );
          }
        });
      })(nestedArrs)}

  );
  //console.log(nestedDivs);

  return (

      {table}
      {nestedDivs}

  );
}

ReactDOM.render(<MyTable />, document.getElementById("target"));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>th,
td {
  border: 1px solid black;
  margin: 0px 0px;
  padding: 5px 5px;
}
div {
  padding: 10px;
  margin: 10px;
}
.level_1 {
  background-color: blue;
}
.level_2 {
  background-color: orange;
}
.level_3 {
  background-color: green;
}
.level_4 {
  background-color: yellow;
}
.task {
  background-color: white !important;
}</code>```

```

Input:

Output:

Body:
I really need your help to create a JSX tree from a flat array in react using recursive function.

For the moment only the items 1 to 6 are correctly displayed and the recursion is stopped after

1) my flat JSON data is : (but it could have more than 1000 items)

const itemsData = [
{
  "Level": 1,
  "Type of activity": "Consolidated task",
  "ID": 118027222233,
  "Name": "Name 1"
},
{
  "Level": 2,
  "Type of activity": "Consolidated task",
  "ID": 118636886633,
  "Name": "Name 2"
},
{
  "Level": 3,
  "Type of activity": "Consolidated task",
  "ID": 118637048333,
  "Name": "Name 3"
},
{
  "Level": 4,
  "Type of activity": "task",
  "ID": 118637035433,
  "Name": "Name 4"
},
{
  "Level": 4,
  "Type of activity": "task",
  "ID": 118841127933,
  "Name": "Name 5"
},
{
  "Level": 4,
  "Type of activity": "task",
  "ID": 118841156833,
  "Name": "Name 6"
},
{
  "Level": 3,
  "Type of activity": "Consolidated task",
  "ID": 118637046733,
  "Name": "Name 9"
},
{
  "Level": 4,
  "Type of activity": "Consolidated task",
  "ID": 118744514633,
  "Name": "Name 10"
},
{
  "Level": 5,
  "Type of activity": "task",
  "ID": 118637033033,
  "Name": "Name 11"
},
{
  "Level": 5,
  "Type of activity": "task",
  "ID": 118637031033,
  "Name": "Name 13"
},
{
  "Level": 2,
  "Type of activity": "Consolidated task",
  "ID": 118636886633,
  "Name": "Name 19"
},
{
  "Level": 3,
  "Type of activity": "task",
  "ID": 118637048333,
  "Name": "Name 20"
},
{
  "Level": 3,
  "Type of activity": "task",
  "ID": 118637048333,
  "Name": "Name 21"
}]

2) My current recursive function looks like that :
But only Item 1 to 6 are correctly displayed.

const RecursiveFunction = ({currentItem, currentLevel}) => {

//LOOP  AS LONG AS CURRENTITEM < ITEMS DATA LENGTH
while(currentItem < itemsData.length){

    //IF CONSOLODATED TASK CREATE CONTAINER
    if(itemsData[currentItem]["Type of activity"] === "Consolidated task"){

        //TEST IF CHILD RELATED TO LEVEL
        if(currentLevel < itemsData[currentItem].Level ){

            //LINE COUNTER
            currentItem++;

            //RETURN
            return (

                        {itemsData[currentItem - 1].Name}

                    <RecursiveFunction currentItem={currentItem} currentLevel={itemsData[currentItem-1].Level} />

            )
        }

    }else{

        //CURRENT TASK LIST ON A BLOCK
        let taskList = [];

        //WHILE IS A TASK
        while(currentItem < itemsData.length && itemsData[currentItem]["Type of activity"] !== "Consolidated task"){

            //LIST ALL THE TASK
            taskList.push(
{itemsData[currentItem].Name}
)
            currentItem++;

        }

        // RETURN
        return (

                {taskList}

        )
    }
}}

3)My render is

class RoadMapItems extends React.Component {

render(){
    return(

            <RecursiveFunction currentItem={0} currentLevel={0} />

    )
}}export default RoadMapItems;

Body:
This should work. It was a bit harder than I initially thought, haha.

You do need to convert to a nested data structure and then to map that recursively to give the desired output:

Full demo below and here: https://codepen.io/Alexander9111/pen/pojXBWX

function MyTable(props) {
  const initState = [
    {
      Level: 1,
      "Type of activity": "Consolidated task",
      ID: 118027222233,
      Name: "Name 1"
    },
    {
      Level: 2,
      "Type of activity": "Consolidated task",
      ID: 118636886633,
      Name: "Name 2"
    },
    {
      Level: 3,
      "Type of activity": "Consolidated task",
      ID: 118637048333,
      Name: "Name 3"
    },
    {
      Level: 4,
      "Type of activity": "task",
      ID: 118637035433,
      Name: "Name 4"
    },
    {
      Level: 4,
      "Type of activity": "task",
      ID: 118841127933,
      Name: "Name 5"
    },
    {
      Level: 4,
      "Type of activity": "task",
      ID: 118841156833,
      Name: "Name 6"
    },
    {
      Level: 3,
      "Type of activity": "Consolidated task",
      ID: 118637046733,
      Name: "Name 9"
    },
    {
      Level: 4,
      "Type of activity": "Consolidated task",
      ID: 118744514633,
      Name: "Name 10"
    },
    {
      Level: 5,
      "Type of activity": "task",
      ID: 118637033033,
      Name: "Name 11"
    },
    {
      Level: 5,
      "Type of activity": "task",
      ID: 118637031033,
      Name: "Name 13"
    },
    {
      Level: 2,
      "Type of activity": "Consolidated task",
      ID: 118636886633,
      Name: "Name 19"
    },
    {
      Level: 3,
      "Type of activity": "task",
      ID: 118637048333,
      Name: "Name 20"
    },
    {
      Level: 3,
      "Type of activity": "task",
      ID: 118637048333,
      Name: "Name 21"
    },
    {
      Level: 2,
      "Type of activity": "Consolidated task",
      ID: 128637048333,
      Name: "Name 22"
    },
    {
      Level: 3,
      "Type of activity": "task",
      ID: 138637048333,
      Name: "Name 23"
    },
    {
      Level: 1,
      "Type of activity": "Consolidated task",
      ID: 148637048333,
      Name: "Name 24"
    },
    {
      Level: 2,
      "Type of activity": "task",
      ID: 158637048333,
      Name: "Name 25"
    }
  ];
  const [state, setState] = React.useState(initState);

  const table = (
    <table>
      <tr key={"header"}>
        {Object.keys(state[0]).map((key) => (
          <th>{key}</th>
        ))}
      </tr>
      {state.map((item) => (
        <tr key={item.id}>
          {Object.values(item).map((val) => (
            <td>{val}</td>
          ))}
        </tr>
      ))}
    </table>
  );

  let currPointer = null;
  const listOfPointers = [];
  const nestedArrs = state.reduce((aggArr, item) => {
    //console.log(listOfPointers)
    if (item.Level == 1) {
      aggArr.push(item);
    }
    else if (item.Level > currPointer.Level) {
      currPointer.children.push(item);
    }
    else if (item.Level <= currPointer.Level) {
      while (item.Level <= currPointer.Level) {
        listOfPointers.pop();
        currPointer = listOfPointers[listOfPointers.length - 1];
      }
      currPointer.children.push(item);
    }

    item.children = [];
    currPointer = item;
    listOfPointers.push(currPointer);

    return aggArr;
  }, []);

  //console.log(nestedArrs);

  const nestedDivs = (
    <div>
      {(function mapChildren(data) {
        return data.map((d, i) => {
          if (d["Type of activity"] != "task") {
            return (
              <div className={"level_" + d.Level}>
                <span>{d.Level + " : " + d.Name}</span>
                {mapChildren(d.children)}
              </div>
            );
          } else {
            return (
              <div className={"level_" + d.Level + " task"}>
                <span>{d.Level + " : " + d.Name}</span>
              </div>
            );
          }
        });
      })(nestedArrs)}
    </div>
  );
  //console.log(nestedDivs);

  return (
    <div>
      {table}
      {nestedDivs}
    </div>
  );
}

ReactDOM.render(<MyTable />, document.getElementById("target"));

th,
td {
  border: 1px solid black;
  margin: 0px 0px;
  padding: 5px 5px;
}
div {
  padding: 10px;
  margin: 10px;
}
.level_1 {
  background-color: blue;
}
.level_2 {
  background-color: orange;
}
.level_3 {
  background-color: green;
}
.level_4 {
  background-color: yellow;
}
.task {
  background-color: white !important;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="target"></div>

Input:

Output:


问:
Docker is not exposing application outside container when used host network mode however it works well within container
I have a spring boot application which calls redis internally .
I have redis running on 6379 inside docker container (also be accessed outside container through redis client)
But When I expose the application as below it complains that redis connection failure .
Running on 8086

docker run -d --name containerName -p 8086:8086 containerName:version
But Application is accessible from browser as http://localhost:8086
However when run like below with --net=host it works perfectly fine with warning as
WARNING: Published ports are discarded when using host network mode

docker run --rm -it -d --net=host --publish-all=true --name containerName containerName:version

But application is not accessible from browser http://localhost:8086

Exception stack trace

Exception in thread "pool-2-thread-1" org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
        at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:282)
        at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:476)
        at org.springframework.data.redis.core.RedisConnectionUtils.doGetConnection(RedisConnectionUtils.java:134)

Caused by: java.net.ConnectException: Connection refused (Connection refused)
        at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)

Note: I am Running docker container on windows machine

答:
I have redis and application container running seperately
so here is the solution

1: redis is running on 6379
docker run --rm -it --name redis -p 6379:6379 redis

2: My service which is using redis under the hood needs to configure redis host as spring.redis.host=redis Here
redis is nothing but the name of redis container

docker run --rm -d --link redis --name reader -p 8086:8086 imageName:version

I can access the application from browser http://localhost:8086
here --link redis does mapping of redis host.


问:
How to import and read large binary file data in c#?
i have a large binary file that contains different data types, i can access single records in the file but i am not sure how to loop over the binary values and load it in the memory stream byte by byte

i have been using binary reader

```<code>BinaryReader binReader = new BinaryReader(File.Open(fileName, FileMode.Open));
            Encoding ascii = Encoding.ASCII;
            string authorName = binReader.ReadString();
            Console.WriteLine(authorName);
            Console.ReadLine();
</code>```

but this won't work since i have a large file with different data types
simply, i need to convert the file to read byte by byte and then read these data either if it's a string or whatsoever.

would appreciate any thought that can help

答:
This will very much depend on what format the file is in. Each byte in the file might represent different things, or it might just represent values from a large array, or some mix of the two.

You need to know what the format looks like to be able to read it, since binary files are not self-descriptive. Reading a simple object might look like

```<code>var authorName = binReader.ReadString();
var publishDate = DateTime.FromBinary(binReader.ReadInt64());
...
</code>```

If you have a list of items it is common to use a length prefix. Something like

```<code>var numItems = binReader.ReadInt32();
for(int i = 0; i < numItems; i++){
    var title = binReader.ReadString();
    ...
}
</code>```

You would then typically create one or more objects from the data that can be used in the rest of the application. I.e.

```<code>new Bibliography(authorName, publishDate , books);
</code>```

If this is a format you do not control I hope you have a detailed specification. Otherwise this is kind of a lost cause for anything but the cludgiest solutions.

If there is more data than can fit in memory you need some kind of streaming mechanism. I.e. read one item, do some processing of the item, save the result, read the next item, etc.

If you do control the format I would suggest alternatives that are easier to manage. I have used protobuf.Net, and I find it quite easy to use, but there are other alternatives. The common way to use these kinds of libraries is to create a class for the data, and add attributes for the fields that should be stored. The library can manage serialization/deserialization automatically, and usually handle things like inheritance and changes to the format in an easy way.

Body:
i have a large binary file that contains different data types, i can access single records in the file but i am not sure how to loop over the binary values and load it in the memory stream byte by byte

i have been using binary reader

BinaryReader binReader = new BinaryReader(File.Open(fileName, FileMode.Open));
            Encoding ascii = Encoding.ASCII;
            string authorName = binReader.ReadString();
            Console.WriteLine(authorName);
            Console.ReadLine();

but this won't work since i have a large file with different data types
simply, i need to convert the file to read byte by byte and then read these data either if it's a string or whatsoever.

would appreciate any thought that can help

Body:
This will very much depend on what format the file is in. Each byte in the file might represent different things, or it might just represent values from a large array, or some mix of the two.

You need to know what the format looks like to be able to read it, since binary files are not self-descriptive. Reading a simple object might look like

var authorName = binReader.ReadString();
var publishDate = DateTime.FromBinary(binReader.ReadInt64());
...

If you have a list of items it is common to use a length prefix. Something like

var numItems = binReader.ReadInt32();
for(int i = 0; i < numItems; i++){
    var title = binReader.ReadString();
    ...
}

You would then typically create one or more objects from the data that can be used in the rest of the application. I.e.

new Bibliography(authorName, publishDate , books);

If this is a format you do not control I hope you have a detailed specification. Otherwise this is kind of a lost cause for anything but the cludgiest solutions.

If there is more data than can fit in memory you need some kind of streaming mechanism. I.e. read one item, do some processing of the item, save the result, read the next item, etc.

If you do control the format I would suggest alternatives that are easier to manage. I have used protobuf.Net, and I find it quite easy to use, but there are other alternatives. The common way to use these kinds of libraries is to create a class for the data, and add attributes for the fields that should be stored. The library can manage serialization/deserialization automatically, and usually handle things like inheritance and changes to the format in an easy way.


问:
Problems with Routing Resources
I am setting up a Rails site using map.resources and map.resource, and I am encountering a limitation (as far as I know at least).

Here is my current routing.

```<code>map.with_options :conditions => { :subdomain => true } do |sub|
  sub.root :controller => 'company'

  sub.resource :company do |company|
    company.resources :clients, :path_prefix => nil, :name_prefix => nil, :collection => { :sort => :post } do |clients|
      clients.resources :projects, :path_prefix => ":client/:project"
    end
  end

  sub.resource :user, :collection => { :logout => :get }
end
</code>```

In a general sense this is my wanted outcome:

/client-name/action
Calls the Clients controller, and passes the client-name as some sort of hash that is the same.

/client-name/project-name/action
Calls the Projects controller, but passes the client-name as a hash that stays the same. It wants to pass that as an id.

I am hoping to keep my URL structure very basic, so:

client-name = yahoo

project-name = login-page

/client-name/ - This should use the Clients.show method.

/client-name/edit - This should use the Clients.edit method.

/client-name/project-name - This should use the Projects.show method.

/client-name/project-name/edit - This should use the Projects.edit method.

Although with my current routing it is being interpreted as such:

/client-name/projects - This is using the Projects.index method.

/clients/client-name - This is using the Clients.show method.

I really appreciate any help that is given.

答:
Resource mapping isn't that powerful. Besides, it adds the name of the resource (company, project, etc.) in the URI. There may still be a way to achieve what you're trying to do using resource mapping, but I think it's easier to use regular mapping:</p>

```<code>map.connect ':client',      :controller => 'clients', :action => 'show'
map.connect ':client/edit', :controller => 'clients', :action => 'edit'

map.connect ':client/:project',      :controller => 'projects', :action => 'show'
map.connect ':client/:project/edit', :controller => 'projects', :action => 'edit'
</code>```

OwnerDisplayName: Garrett

ContentLicense: CC BY-SA 2.5

Title: Problems with Routing Resources

Body:
I am setting up a Rails site using map.resources and map.resource, and I am encountering a limitation (as far as I know at least).

Here is my current routing.

map.with_options :conditions => { :subdomain => true } do |sub|
  sub.root :controller => 'company'

  sub.resource :company do |company|
    company.resources :clients, :path_prefix => nil, :name_prefix => nil, :collection => { :sort => :post } do |clients|
      clients.resources :projects, :path_prefix => ":client/:project"
    end
  end

  sub.resource :user, :collection => { :logout => :get }
end

In a general sense this is my wanted outcome:

/client-name/action
Calls the Clients controller, and passes the client-name as some sort of hash that is the same.

/client-name/project-name/action
Calls the Projects controller, but passes the client-name as a hash that stays the same. It wants to pass that as an id.

I am hoping to keep my URL structure very basic, so:

client-name = yahoo

project-name = login-page

/client-name/ - This should use the Clients.show method.

/client-name/edit - This should use the Clients.edit method.

/client-name/project-name - This should use the Projects.show method.

/client-name/project-name/edit - This should use the Projects.edit method.

Although with my current routing it is being interpreted as such:

/client-name/projects - This is using the Projects.index method.

/clients/client-name - This is using the Clients.show method.

I really appreciate any help that is given.

Body:
Resource mapping isn't that powerful. Besides, it adds the name of the resource (company, project, etc.) in the URI. There may still be a way to achieve what you're trying to do using resource mapping, but I think it's easier to use regular mapping:

map.connect ':client',      :controller => 'clients', :action => 'show'
map.connect ':client/edit', :controller => 'clients', :action => 'edit'

map.connect ':client/:project',      :controller => 'projects', :action => 'show'
map.connect ':client/:project/edit', :controller => 'projects', :action => 'edit'

OwnerDisplayName: Can Berk Güder


问:
Remove current view from superview
Let's say I have a viewcontroller "ViewBViewController". In that viewcontroller I create an instance of the "ViewAViewController" and use the addSubView: method to display this ViewAViewController. It then processes a bunch of information, and is now done. I want it to automatically get removed as a subview when it's done.

I was looking at the removeFromSuperview method, but can't seem to call that from within the viewcontroller whose view I'm trying to remove (my first instinct was [self.view removeFromSuperview], but that gets rid of the entire view, not just the subview I'm after).

The only way I can think of is setting up a delegate protocol, and have View B take care of the unloading of View A on behalf of View A as its delegate. However this approach seems a bit overkill. Am I missing an easier solution?

Thanks in advance!

答:
UIViewController does not respond to removeFromSuperview, because a UIViewController is not a UIView but a UIViewController. No surprises there. You can call removeSuperview on any view, such as the view associated to a view controller (here self):

```<code>[self.view removeFromSuperview];
</code>```

or if you just want to remove one subview:

```<code>[mySubview removeFromSuperview];
</code>```

or if your subview is a member of self (i.e. declared in the interface say):

```<code>[self.mySubview removeFromSuperview];
</code>```

ContentLicense: CC BY-SA 3.0

Title: Remove current view from superview

Body:
UIViewController does not respond to removeFromSuperview, because a UIViewController is not a UIView but a UIViewController. No surprises there. You can call removeSuperview on any view, such as the view associated to a view controller (here self):

[self.view removeFromSuperview];

or if you just want to remove one subview:

[mySubview removeFromSuperview];

or if your subview is a member of self (i.e. declared in the interface say):

[self.mySubview removeFromSuperview];


问:
Wordpress return Plugin could not be activated because it triggered a fatal error
I have strange error on activate my own plugin for WordPress.

On activate plugin I get only message "Plugin could not be activated because it triggered a fatal error." And that's all (see http://prntscr.com/snxdkw ). I don't get more errors, after enable debug mode I get only errors with level E_NOTICE, that's no critical.

That error showing only on live server, locally all ok. Googling has no effects

Local:

PHP: 7.3.16

WordPress: 5.4.1

Server:

PHP: 7.3.16

WordPress: 5.4.1

I tried:

Enabled debug log on local and server (result: no critical errors)

Fixed all errors

Reactivate plugin on my local WordPress (result: locally no same error)

Looked in PHP log on server (result: no critical errors)

Tryed follow from error message to error handler in WP core for understanding error initiator (result: not found error initiator)

Wrote debug messages to debug.log in register_activation_hook and register_deactivation_hook (result: I don't get my debug messages, I think WordPress doesn't reach to register_activation_hook() )

答:
Problem was resolved.

json_decode() gave null as result, but this data put on function with array type variable. I don't know why PHP didn't give any errors.

Problem solved via inline checking lines step-by-step.


问:
Highchart spline Cut Off when reach to maximum scale value. How can it fixed?. I have attached may sample code on body
I'm making use if the highcharts plugin to make a chart. But I'm running into some problems.
My Highchart spline is cut off when reach to maximum scale value. How is this possible and how can it be fixed?

I have created a sample demo for this chart and also attached the screenshot to point of the cutoff spline.
Here is my demo code:

let chartdata = [];
let A = [95, 95, 95];
let B = [50, 100, 100];

var colorBand = [{
    color: "red",
    to: 0,
    from: 20
  },
  {
    color: "green",
    to: 21,
    from: 40
  },
  {
    color: "blue",
    to: 41,
    from: 60
  },
  {
    color: "orange",
    to: 61,
    from: 90
  },
  {
    color: "yellow",
    to: 91,
    from: 100
  },
];

chartdata.push({
  name: 'A',
  type: 'column',
  date: 'A',
  data: A,
  color: 'red',
});

chartdata.push({
  name: 'B',
  type: 'spline',
  date: 'B',
  data: B,
  color: 'blue'
});

Highcharts.chart('container', {
  chart: {
    height: 205,
    width: 200,
    background: '#F2F2F2'
  },
  title: {
    text: ''
  },
  credits: {
    enabled: false
  },
  legend: {
    align: "center",
    layout: "horizontal",
    verticalAlign: "bottom",
    symbolHeight: 10,
    symbolWidth: 10,
    symbolRadius: 0,
    itemStyle: {
      fontSize: "13px",
      fontWeight: 'bold',
      fontFamily: '"Arial", sans-serif'
    }
  },
  xAxis: {
    labels: {
      style: {
        fontSize: "11px",
        fontFamily: '"Arial", sans-serif',
        color: "#000"
      }
    },
    gridLineColor: "transparent",
    gridLineWidth: 0,
    minorGridLineWidth: 0,
    lineColor: "#9A9A9A",
    zIndex: 9999999,
    minorTickLength: 0,
    tickLength: 0,
    style: {
      fontSize: "11px",
      fontWeight: "bold",
      fontFamily: '"Arial", sans-serif',
      color: "#000"
    }
  },

  yAxis: [{
      gridLineWidth: 0,
      labels: {
        style: {
          fontSize: "12px",
          color: "#000",
          fontFamily: '"Arial", sans-serif'
        }
      },
      title: {
        text: ''
      },
      min: 0,
      plotBands: colorBand,
      width: 20,
      max: 100,
      tickInterval: 20
    },
    {
      linkedTo: 0,
      gridLineWidth: 0,
      lineColor: "transparent",
      title: {
        text: ""
      },
      labels: {
        enabled: false
      }
    }
  ],
  plotOptions: {
    series: {
      states: {
        hover: {
          enabled: false,
        },
        inactive: {
          opacity: 1
        }
      },
      pointPadding: 0.1,
      groupPadding: 0,
      lineWidth: 5,
      pointWidth: 25,
      enableMouseTracking: false,
      borderWidth: 1,
      borderColor: '#FFFFFF',
      threshold: 0, // let zero values have some height
      marker: {
        enabled: false,
        states: {
          hover: {
            //radius: 1
          }
        }
      },
      minPointLength: 10,
      events: {
        legendItemClick: function() {
          return false;
        }
      }
    }
  },
  series: chartdata
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container"></div></code>```

Here I pointed out the cutline

enter image description here

答:
Setting the series.clip as a false is a solution which you are looking for.

Demo: https://jsfiddle.net/BlackLabel/aph9tg78/

```<code>chartdata.push({
    clip: false,
  name: 'B',
  type: 'spline',
  date : 'B',
  data : B,
  color: 'blue'
});
</code>```

Simplified demo: https://jsfiddle.net/BlackLabel/483obfrw/

API: https://api.highcharts.com/highcharts/series.line.clip

Body:
I'm making use if the highcharts plugin to make a chart. But I'm running into some problems.
My Highchart spline is cut off when reach to maximum scale value. How is this possible and how can it be fixed?

I have created a sample demo for this chart and also attached the screenshot to point of the cutoff spline.
Here is my demo code:

let chartdata = [];
let A = [95, 95, 95];
let B = [50, 100, 100];

var colorBand = [{
    color: "red",
    to: 0,
    from: 20
  },
  {
    color: "green",
    to: 21,
    from: 40
  },
  {
    color: "blue",
    to: 41,
    from: 60
  },
  {
    color: "orange",
    to: 61,
    from: 90
  },
  {
    color: "yellow",
    to: 91,
    from: 100
  },
];

chartdata.push({
  name: 'A',
  type: 'column',
  date: 'A',
  data: A,
  color: 'red',
});

chartdata.push({
  name: 'B',
  type: 'spline',
  date: 'B',
  data: B,
  color: 'blue'
});

Highcharts.chart('container', {
  chart: {
    height: 205,
    width: 200,
    background: '#F2F2F2'
  },
  title: {
    text: ''
  },
  credits: {
    enabled: false
  },
  legend: {
    align: "center",
    layout: "horizontal",
    verticalAlign: "bottom",
    symbolHeight: 10,
    symbolWidth: 10,
    symbolRadius: 0,
    itemStyle: {
      fontSize: "13px",
      fontWeight: 'bold',
      fontFamily: '"Arial", sans-serif'
    }
  },
  xAxis: {
    labels: {
      style: {
        fontSize: "11px",
        fontFamily: '"Arial", sans-serif',
        color: "#000"
      }
    },
    gridLineColor: "transparent",
    gridLineWidth: 0,
    minorGridLineWidth: 0,
    lineColor: "#9A9A9A",
    zIndex: 9999999,
    minorTickLength: 0,
    tickLength: 0,
    style: {
      fontSize: "11px",
      fontWeight: "bold",
      fontFamily: '"Arial", sans-serif',
      color: "#000"
    }
  },

  yAxis: [{
      gridLineWidth: 0,
      labels: {
        style: {
          fontSize: "12px",
          color: "#000",
          fontFamily: '"Arial", sans-serif'
        }
      },
      title: {
        text: ''
      },
      min: 0,
      plotBands: colorBand,
      width: 20,
      max: 100,
      tickInterval: 20
    },
    {
      linkedTo: 0,
      gridLineWidth: 0,
      lineColor: "transparent",
      title: {
        text: ""
      },
      labels: {
        enabled: false
      }
    }
  ],
  plotOptions: {
    series: {
      states: {
        hover: {
          enabled: false,
        },
        inactive: {
          opacity: 1
        }
      },
      pointPadding: 0.1,
      groupPadding: 0,
      lineWidth: 5,
      pointWidth: 25,
      enableMouseTracking: false,
      borderWidth: 1,
      borderColor: '#FFFFFF',
      threshold: 0, // let zero values have some height
      marker: {
        enabled: false,
        states: {
          hover: {
            //radius: 1
          }
        }
      },
      minPointLength: 10,
      events: {
        legendItemClick: function() {
          return false;
        }
      }
    }
  },
  series: chartdata
});

Here I pointed out the cutline

enter image description here

Body:
Setting the series.clip as a false is a solution which you are looking for.

Demo: https://jsfiddle.net/BlackLabel/aph9tg78/

chartdata.push({
    clip: false,
  name: 'B',
  type: 'spline',
  date : 'B',
  data : B,
  color: 'blue'
});

Simplified demo: https://jsfiddle.net/BlackLabel/483obfrw/

API: https://api.highcharts.com/highcharts/series.line.clip


问:
Docker desktop (Windows 10 Pro) — Why is there no Advanced tab in Settings->Resources?

Why is there no Advanced tab in Settings->Resources?

答: You can add or modify image information in Docker Engine


问:
What should be the behavior if I try to load a word from an address that is not 4-aligned in Mips?
I'm building a Mips assembler and as of its state right now, It tolerates instructions such as lw $s0, 3($sp), which I find somewhat counter-intuitive for me, as I don't know whether the processor tolerates this or it cannot load for example 1 byte from a word and the other 3 bytes from another word.

In other words, should I deal with the data as it is an array of words(two-dimensional array) so I can only address words that are 4-aligned, or a one-dimensional array that has all the bytes one after the other, in which I can access any 4 consecutive bytes and cram them into a register?

答:
A MIPS processor should fault on misaligned addresses, but it is not the assembler's job to determine that.

A warning might be reasonable, but technically, at build time, you can seldom know or predict what is in the register.  An offset of 3 is legal and can work, with lw or sw, if the address in the register is also odd.

Also, the programmer might be trying to cause a fault — you never know.

The point being that the instruction has a valid encoding and the assembler should translate the text into that machine code.


问:
How to make a pattern in Lua that matches only when no number (normal or roman) is present?
I want to make a pattern that matches only when a string contains no arabic or roman numerals (note that the roman numerals can only go up to X (10))

Examples:

```<code>"Rock"                 <-- matches
"Rock IV"              <-- doesn't match
"Rock 4"               <-- doesn't match
"Rock Paper"           <-- matches
"Rock Paper Scissors"  <-- matches
"Rock Paper VIII"      <-- doesn't match
"Rock Paper 8"         <-- doesn't match
</code>```

My current code only allows for the usage of 1 word and a numeral. My goal is to make it so it only doesn't match when a numeral is present.
Code:

```<code>"^([^%s]+)$"
</code>```

As the title says, I am using Lua. I can also note that the code will be used on one of the fandom wikis, so syntax should match Scribunto syntax.

答:
There is no pattern I can think of that would match what you need in one go with any possible word.

```<code>".*%s?[^IVXLCDM0-9]+$"
</code>```

This matches any string that does not end with space and digits.

This would fail for words that with Roman digits like "RockM".

Often it is easier to match something that to not match something.

If you just want to check it might be easier to search the string for [0-9IVXLCDM]

Body:
I want to make a pattern that matches only when a string contains no arabic or roman numerals (note that the roman numerals can only go up to X (10))

Examples:

"Rock"                 <-- matches
"Rock IV"              <-- doesn't match
"Rock 4"               <-- doesn't match
"Rock Paper"           <-- matches
"Rock Paper Scissors"  <-- matches
"Rock Paper VIII"      <-- doesn't match
"Rock Paper 8"         <-- doesn't match

My current code only allows for the usage of 1 word and a numeral. My goal is to make it so it only doesn't match when a numeral is present.
Code:

"^([^%s]+)$"

As the title says, I am using Lua. I can also note that the code will be used on one of the fandom wikis, so syntax should match Scribunto syntax.

Body:
There is no pattern I can think of that would match what you need in one go with any possible word.

".*%s?[^IVXLCDM0-9]+$"

This matches any string that does not end with space and digits.

This would fail for words that with Roman digits like "RockM".

Often it is easier to match something that to not match something.

If you just want to check it might be easier to search the string for [0-9IVXLCDM]


问:
path.exists() is returning False
I'm building a basic file server and my program cannot find files.

```<code>def sendfile(sock, myfile):
    print 'Serving file:', myfile
    print 'File exists?:', os.path.exists(myfile)

    path = os.path.normpath(os.path.join(os.getcwd(), myfile))
    print 'Serving file:', path
    print 'File exists?:', os.path.exists(path)
</code>```

These always return False even though the 'myfile' and 'path' are correct [the file is in the same directory as the server program].

IDLE works fine, but without passing to functions.

```<code>>>> print os.path.exists("/user/server/foo.txt")
True
</code>```

What have I missed?

[EDIT:] Output:

```<code>Serving file: foo.txt

File exists?: False
Serving file: /user/server/foo.txt

File exists?: False
</code>```

答:
I had this same issue and found the following solution:

Using the OS's native directory separator '\' or '/'  even on Windows, using the forward slash in all occasions works just fine for me.  os.sep can help.

In addition to this, sanitizing the path string a bit similar to this:

```<code>import re
from os import path
strPath = "c:/dir1/dir2/dir3/dir4/important-file.ext"
strPath = re.escape(strPath)

bTest = os.access(strPath, os.F_OK)

# or the classic
bTest = path.exists(strPath)
print(bTest)

</code>```

Title: path.exists() is returning False

Body:
I'm building a basic file server and my program cannot find files.

def sendfile(sock, myfile):
    print 'Serving file:', myfile
    print 'File exists?:', os.path.exists(myfile)

    path = os.path.normpath(os.path.join(os.getcwd(), myfile))
    print 'Serving file:', path
    print 'File exists?:', os.path.exists(path)

These always return False even though the 'myfile' and 'path' are correct [the file is in the same directory as the server program].

IDLE works fine, but without passing to functions.

>>> print os.path.exists("/user/server/foo.txt")
True

What have I missed?

[EDIT:] Output:

Serving file: foo.txt

File exists?: False
Serving file: /user/server/foo.txt

File exists?: False

Body:
I had this same issue and found the following solution:

Using the OS's native directory separator '\' or '/'  even on Windows, using the forward slash in all occasions works just fine for me.  os.sep can help.

In addition to this, sanitizing the path string a bit similar to this:

import re
from os import path
strPath = "c:/dir1/dir2/dir3/dir4/important-file.ext"
strPath = re.escape(strPath)

bTest = os.access(strPath, os.F_OK)

# or the classic
bTest = path.exists(strPath)
print(bTest)


问:
Download Highcharts Generated Table into R
I'm trying to download a csv file of data corresponding to the chart on the below website:

http://vixcentral.com/

If I click on the menu button on the top right of the chart there's an option to download the chart data into a csv.

The issue is that that button seems to generate a download link that only works temporarily, so I'm unable to use a regular downloader such as read_csv or rio::import to pull the file into R.

It seems both the chart and the download link are generated by the Highcharts javascript.

Is there any straightforward way to download this data into R by figuring out the link?

Or does it have to be a scraping excercise?

答:
If you right-click on the screen and press 'Inspect Element', then go to the 'Network' tab, you can see xhr requests being done to obtain data (for example while clicking around the different charts).

You noted that you're interested in the result of http://vixcentral.com/ajax_update/?_=1590762673737.
The number in the end of this URL is the Unix epoch of the current time. That's why it changes.

There is a little bit of security from scraping in the sense that they try to block requests that do not come from their own site. By setting the header X-Requested-With to "XMLHttpRequest", it works. You can view the headers used for this request by clicking on it in the 'inspect element' screen of your browser. There are a bunch of headers being set, and by removing each one and testing, I found out that this is the only one that's needed for your purpose.

Below reads the data and parses it into an R object using jsonlite.

```<code>res <- httr::GET("http://vixcentral.com/ajax_update/?_=1590762673737",
                 add_headers("X-Requested-With" = "XMLHttpRequest"))

res_text <- content(res, "text")

jsonlite::fromJSON(res_text)
</code>```

Body:
If you right-click on the screen and press 'Inspect Element', then go to the 'Network' tab, you can see xhr requests being done to obtain data (for example while clicking around the different charts).

You noted that you're interested in the result of http://vixcentral.com/ajax_update/?_=1590762673737.
The number in the end of this URL is the Unix epoch of the current time. That's why it changes.

There is a little bit of security from scraping in the sense that they try to block requests that do not come from their own site. By setting the header X-Requested-With to "XMLHttpRequest", it works. You can view the headers used for this request by clicking on it in the 'inspect element' screen of your browser. There are a bunch of headers being set, and by removing each one and testing, I found out that this is the only one that's needed for your purpose.

Below reads the data and parses it into an R object using jsonlite.

res <- httr::GET("http://vixcentral.com/ajax_update/?_=1590762673737",
                 add_headers("X-Requested-With" = "XMLHttpRequest"))

res_text <- content(res, "text")

jsonlite::fromJSON(res_text)


问:
make pairwise difference of array with python
I have an array with numbers like this, in this case 5 numbers:

```<code>a = array([2.88581812, 2.8930633 , 2.85603976, 2.86739916, 2.85736707])
</code>```

I would like to create an array of 10 elements in which the pairwise difference of all the numbers of the array is present.
For now i used nested loop for like this:

```<code>diffmean = []
for i in range(len(a)-1):
    for j in range(i+1, len(a)):
        diffmean.append(a[i]-a[j])
</code>```

Obtaining a list with 10 elements of pairwise difference

```<code>    [-0.007245185215707384,
 0.029778354907735505,
 0.018418952746142025,
 0.0284510446999775,
 0.03702354012344289,
 0.02566413796184941,
 0.035696229915684885,
 -0.01135940216159348,
 -0.0013273102077580035,
 0.010032091953835476]
</code>```

there is a "pythonic" way to perform this? without loopfor or nested loop for?

答:
You can use combinations in build-in itertools library. Like:

from itertools import combinations
a = [2.88581812, 2.8930633 , 2.85603976, 2.86739916, 2.85736707]
diffmean = []
for b,c in combinations(a, 2):
    diffmean.append(b - c)
```

The second argument of the function is the number of elements you want to combine. The function is order-free and the order-based version is permutations which returns 20 values in this case.

Body:
I have an array with numbers like this, in this case 5 numbers:

a = array([2.88581812, 2.8930633 , 2.85603976, 2.86739916, 2.85736707])

I would like to create an array of 10 elements in which the pairwise difference of all the numbers of the array is present.
For now i used nested loop for like this:

diffmean = []
for i in range(len(a)-1):
    for j in range(i+1, len(a)):
        diffmean.append(a[i]-a[j])

Obtaining a list with 10 elements of pairwise difference

    [-0.007245185215707384,
 0.029778354907735505,
 0.018418952746142025,
 0.0284510446999775,
 0.03702354012344289,
 0.02566413796184941,
 0.035696229915684885,
 -0.01135940216159348,
 -0.0013273102077580035,
 0.010032091953835476]

there is a "pythonic" way to perform this? without loopfor or nested loop for?

Body:
You can use combinations in build-in itertools library. Like:

from itertools import combinations
a = [2.88581812, 2.8930633 , 2.85603976, 2.86739916, 2.85736707]
diffmean = []
for b,c in combinations(a, 2):
    diffmean.append(b - c)

The second argument of the function is the number of elements you want to combine. The function is order-free and the order-based version is permutations which returns 20 values in this case.


问:
moving UIScrollView on rotate on the ipad
I have a multiview application and i have built a custom panelview controller to display panels with limited information about a product, the problem is that there should be 3 panels in portrait aspect and 4 in landscape.

Due to the depth of view controllers (about 5) the didRotateFromInterfaceOrientation: event will not trigger on the child viewcontroller so i am using the NSNotificationCenter on the rootViewController to post a message and picking it up with the child controller.

I can move the panels (UIScrollViews) without trouble but they move into place when i want them to but they move instantly which isn't smooth or tidy, i want them to slide into their new location.

After some searching i am still having no luck finding out how to do this.

```<code>-(void) updatePanelLocations{
    int buttonWidth = 230;
    int buttonHeight = 335;
    float frameWidth = mainPanel.frame.size.width;
    int numberOfcolumns = frameWidth / buttonWidth;
    float margin = (frameWidth - (numberOfcolumns * buttonWidth)) / (numberOfcolumns +1);
    int currentRow = 0;
    int currentColumn = 0;

    CATransition *animation = [CATransition animation];
    [animation setDelegate:self];
    [animation setType:kCATransitionReveal];
    [animation setDuration:0.4];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];

    int i = 0;

    for (UIView* curView in [mainPanel subviews]) {
        //set an arbutrary tag field in generating the scrollviews so i can detect this
        if (curView.tag != 9991) continue;
        //newline detection
        if (currentColumn == numberOfcolumns){
            currentRow++;
            currentColumn = 0;
        }

        [[curView layer] addAnimation:animation forKey:@"transitionViewAnimation"];

        //XY Coordinates
        int buttonX = (margin * (currentColumn + 1)) + (buttonWidth * currentColumn);
        int buttonY = (margin * (currentRow + 1)) + (buttonHeight * currentRow);

        //make the frame
        [curView setFrame:CGRectMake(buttonX, buttonY, buttonWidth, buttonHeight)];
        [curView setAutoresizingMask: UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin];
        //put the button on the target uiscrollview
        [[curView layer] removeAnimationForKey:@"transitionViewAnimation"];
        //next column
        currentColumn++;

        i++;
    }

    animation = nil;
}
</code>```

How can animate this movement for sliding from a to b??

Or better still if i have it all wrong, point me in the right direction :)

Cheers

答:
What you're looking for is UIView's animateWithDuration: methods.

You'll get the appropriate duration from willRotateToInterfaceOrientation:duration: in the view controller.

Body:
I have a multiview application and i have built a custom panelview controller to display panels with limited information about a product, the problem is that there should be 3 panels in portrait aspect and 4 in landscape.

Due to the depth of view controllers (about 5) the didRotateFromInterfaceOrientation: event will not trigger on the child viewcontroller so i am using the NSNotificationCenter on the rootViewController to post a message and picking it up with the child controller.

I can move the panels (UIScrollViews) without trouble but they move into place when i want them to but they move instantly which isn't smooth or tidy, i want them to slide into their new location.

After some searching i am still having no luck finding out how to do this.

-(void) updatePanelLocations{
    int buttonWidth = 230;
    int buttonHeight = 335;
    float frameWidth = mainPanel.frame.size.width;
    int numberOfcolumns = frameWidth / buttonWidth;
    float margin = (frameWidth - (numberOfcolumns * buttonWidth)) / (numberOfcolumns +1);
    int currentRow = 0;
    int currentColumn = 0;

    CATransition *animation = [CATransition animation];
    [animation setDelegate:self];
    [animation setType:kCATransitionReveal];
    [animation setDuration:0.4];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];

    int i = 0;

    for (UIView* curView in [mainPanel subviews]) {
        //set an arbutrary tag field in generating the scrollviews so i can detect this
        if (curView.tag != 9991) continue;
        //newline detection
        if (currentColumn == numberOfcolumns){
            currentRow++;
            currentColumn = 0;
        }

        [[curView layer] addAnimation:animation forKey:@"transitionViewAnimation"];

        //XY Coordinates
        int buttonX = (margin * (currentColumn + 1)) + (buttonWidth * currentColumn);
        int buttonY = (margin * (currentRow + 1)) + (buttonHeight * currentRow);

        //make the frame
        [curView setFrame:CGRectMake(buttonX, buttonY, buttonWidth, buttonHeight)];
        [curView setAutoresizingMask: UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin];
        //put the button on the target uiscrollview
        [[curView layer] removeAnimationForKey:@"transitionViewAnimation"];
        //next column
        currentColumn++;

        i++;
    }

    animation = nil;
}

How can animate this movement for sliding from a to b??

Or better still if i have it all wrong, point me in the right direction :)

Cheers


问:
How to cache the response of API calls in Flutter?
I am working in Flutter App to get the items from API. I want to cache the API response for 12 hours. Every 12 hours the response will be changed. Once the 12 hours completed then I need to fetch it from Internet. I used the below code to get it from internet.

```<code>Future<List<Playlist>> fetchPlaylistByChannelId({String channelId}) async {
Map<String, String> parameters = {
  'part': 'snippet,contentDetails',
  'channelId': channelId,
  'maxResults': '10',
  'key': API_KEY,
};
Uri uri = Uri.https(
  _baseUrl,
  '/youtube/v3/playlists',
  parameters,
);
Map<String, String> headers = {
  HttpHeaders.contentTypeHeader: 'application/json',
};

// Get Playlist details
var response = await http.get(uri, headers: headers);
if (response.statusCode == 200) {
  var data = json.decode(response.body);
  List<dynamic> playListJson = data['items'];

  // Fetch all play list
  List<Playlist> playLists = [];
  playListJson.forEach(
    (json) => playLists.add(
      Playlist.fromMap(
        json["id"],
        json["snippet"],
        json["contentDetails"],
      ),
    ),
  );
  return playLists;
} else {
  throw json.decode(response.body)['error']['message'];
}   }
</code>```

Please help me out this.

答:
Another way of caching is by using hive a No-SQL database it is faster to retrieve documents and is easy to use. And when users come online just refresh the data in hive

For more details check:https://github.com/shashiben/Anime-details to know how to cache using hive

Body:
I am working in Flutter App to get the items from API. I want to cache the API response for 12 hours. Every 12 hours the response will be changed. Once the 12 hours completed then I need to fetch it from Internet. I used the below code to get it from internet.

Future<List<Playlist>> fetchPlaylistByChannelId({String channelId}) async {
Map<String, String> parameters = {
  'part': 'snippet,contentDetails',
  'channelId': channelId,
  'maxResults': '10',
  'key': API_KEY,
};
Uri uri = Uri.https(
  _baseUrl,
  '/youtube/v3/playlists',
  parameters,
);
Map<String, String> headers = {
  HttpHeaders.contentTypeHeader: 'application/json',
};

// Get Playlist details
var response = await http.get(uri, headers: headers);
if (response.statusCode == 200) {
  var data = json.decode(response.body);
  List<dynamic> playListJson = data['items'];

  // Fetch all play list
  List<Playlist> playLists = [];
  playListJson.forEach(
    (json) => playLists.add(
      Playlist.fromMap(
        json["id"],
        json["snippet"],
        json["contentDetails"],
      ),
    ),
  );
  return playLists;
} else {
  throw json.decode(response.body)['error']['message'];
}   }

Please help me out this.


问:
Can't create database when using string type primary key
I create Entity class for spring boot project

```<code>package com.example.pharmanic.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import javax.persistence.Id;

@NoArgsConstructor
@AllArgsConstructor
@Entity
@Data
@Table(name = "Rdhs_Driver")
public class Rdhs_Driver {
    @Id
    private String nic;
    private String name;
    private String email;
    private String address;
    private String telephone;

    @ManyToOne
    @JoinColumn(name = "reg_no", nullable = false, referencedColumnName = "reg_no")
    private Rdhs rdhs;

    @Override
    public String toString(){
        return "Rdhs_Driver{" +
                "nic=" + nic +
                ", name='" + name + '\'' +
                ", telephone='" + telephone + '\'' +
                ", email='" + email + '\'' +
                ", address='" + address + '\'' +

                '}';
    }
}
</code>```

But when i run this project, haven't create table.
But i use 'Long nic' instead of 'String nic', when i change like this tables is created. but i want to use string type primary key.

How I solve this matter ?

答:
Use column annotation like below by putting nullable False.</p>

```<code>@Id
@Column(name = "NIC", nullable = false)
private String nic;
</code>```

Body:
I create Entity class for spring boot project

package com.example.pharmanic.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import javax.persistence.Id;

@NoArgsConstructor
@AllArgsConstructor
@Entity
@Data
@Table(name = "Rdhs_Driver")
public class Rdhs_Driver {
    @Id
    private String nic;
    private String name;
    private String email;
    private String address;
    private String telephone;

    @ManyToOne
    @JoinColumn(name = "reg_no", nullable = false, referencedColumnName = "reg_no")
    private Rdhs rdhs;

    @Override
    public String toString(){
        return "Rdhs_Driver{" +
                "nic=" + nic +
                ", name='" + name + '\'' +
                ", telephone='" + telephone + '\'' +
                ", email='" + email + '\'' +
                ", address='" + address + '\'' +

                '}';
    }
}

But when i run this project, haven't create table.
But i use 'Long nic' instead of 'String nic', when i change like this tables is created. but i want to use string type primary key.

How I solve this matter ?

Body:
Use column annotation like below by putting nullable False.

@Id
@Column(name = "NIC", nullable = false)
private String nic;