text:
Q: How to set ValueSerde per Binding Spring Cloud Kafka Streams I'm trying to set valueSerde per binding, however only default valueserde is being considered.
AppSerde class
public class AppSerdes {

    public static final class DepartmentSerde extends WrapperSerde<Department> {
        public DepartmentSerde() {
            super(new ProtobufSerializer<>(), new ProtobufDeserializer<>(Department.class));
        }
    }

    public static final class EmployeeSerde extends WrapperSerde<Employee> {
        public EmployeeSerde() {
            super(new ProtobufSerializer<>(), new ProtobufDeserializer<>(Employee.class));
        }
    }

    public static final class DepartmentDataSerde extends WrapperSerde<DepartmentData> {
        public DepartmentDataSerde() {
            super(new ProtobufSerializer<>(), new ProtobufDeserializer<>(DepartmentData.class));
        }
    }
}

StreamsConfig.java
@Configuration
@Slf4j
public class StreamsConfiguration {

    @Bean
    public BiFunction<KStream<String, Employee>, KStream<String, Department>, KStream<String, DepartmentData>> process() {
        return (Employee, Department) -> Employee.leftJoin(Department, (v1, v2) -> {
            if (v2 == null) {
                log.info("No Department is present");
                return null;
            } else {
                var data = DepartmentData.newBuilder();
                data.setId(v2.getId());
                data.setName(v2.getName());
                data.addEmployees(v1);
                return data.build();
            }
        }, JoinWindows.of(Duration.ofMinutes(1))).peek((k, v) -> {
            log.info("Key->{}, value->{}", k, v);
        });
    }
}

and application.yml
spring:
  application.name: kafka-join-example
spring.kafka.bootstrap-servers: 192.168.56.101:19092
spring.cloud.stream.kafka.streams.bindings.process-in-0.consumer.valueSerde: io.github.kprasad99.streams.AppSerdes$EmployeeSerde
spring.cloud.stream.kafka.streams.bindings.process-in-1.consumer.valueSerde: io.github.kprasad99.streams.AppSerdes$DepartmentSerde
spring.cloud.stream.kafka.streams.bindings.process-out-0.producer.valueSerde: io.github.kprasad99.streams.AppSerdes$DepartmentDataSerde
spring.cloud.stream:
  bindings:
    process-in-0:
      destination: kp.sch
      consumer:
        use-native-decoding: true
    process-in-1:
      destination: kp.lm
      consumer:
        use-native-decoding: true
    process-out-0:
      destination: kp.lm.sch
      producer:
        use-native-encoding: true
  kafka.streams.bindings:
    process-in-0:
      consumer:
        value.serde: io.github.kprasad99.streams.AppSerdes$EmployeeSerde
    process-in-1:
      consumer:
        value.serde: io.github.kprasad99.streams.AppSerdes$DepartmentSerde
    process-out-0:
      producer:
        value.serde: io.github.kprasad99.streams.AppSerdes$DepartmentDataSerde
  kafka.streams.binder:
    brokers:
    - 192.168.56.101:19092
#    replication-factor: 3
#    required-acks: 2
    min-partition-count: 5
    configuration:
      commit.interval.ms: 100
      default:
        key.serde: org.apache.kafka.common.serialization.Serdes$StringSerde
        value.serde: io.github.kprasad99.streams.kafka.serde.ProtobufSerde

Edit
Full sample code is here
**stack trace**2020-12-06 21:55:39.929 ERROR 141897 --- [-StreamThread-1]

o.a.k.s.p.i.AssignedStreamsTasks         : stream-thread [kafka-join-example-4aa10729-e5b7-4a33-89c6-906dd8ab2e5d-StreamThread-1] Failed to process stream task 1_4 due to the following error:

org.apache.kafka.streams.errors.StreamsException: Exception caught in process. taskId=1_4, processor=KSTREAM-SOURCE-0000000001, topic=kp.department, partition=4, offset=1, stacktrace=org.apache.kafka.common.errors.SerializationException: java.lang.InstantiationException: No target type provided
Caused by: java.lang.InstantiationException: No target type provided
    at io.github.kprasad99.streams.protobuf.serialization.ProtobufDeserializer.deserialize(ProtobufDeserializer.java:45)
    at io.github.kprasad99.streams.protobuf.serialization.ProtobufDeserializer.deserialize(ProtobufDeserializer.java:1)
    at org.apache.kafka.streams.state.StateSerdes.valueFrom(StateSerdes.java:160)
    at org.apache.kafka.streams.state.internals.MeteredWindowStoreIterator.next(MeteredWindowStoreIterator.java:56)
    at org.apache.kafka.streams.state.internals.MeteredWindowStoreIterator.next(MeteredWindowStoreIterator.java:26)
    at org.apache.kafka.streams.kstream.internals.KStreamKStreamJoin$KStreamKStreamJoinProcessor.process(KStreamKStreamJoin.java:100)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.lambda$process$2(ProcessorNode.java:142)
    at org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.maybeMeasureLatency(StreamsMetricsImpl.java:806)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:142)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:201)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:180)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:133)
    at org.apache.kafka.streams.kstream.internals.KStreamJoinWindow$KStreamJoinWindowProcessor.process(KStreamJoinWindow.java:55)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.lambda$process$2(ProcessorNode.java:142)
    at org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.maybeMeasureLatency(StreamsMetricsImpl.java:806)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:142)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:201)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:180)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:133)
    at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:104)
    at org.apache.kafka.streams.processor.internals.StreamTask.lambda$process$3(StreamTask.java:383)
    at org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.maybeMeasureLatency(StreamsMetricsImpl.java:806)
    at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:383)
    at org.apache.kafka.streams.processor.internals.AssignedStreamsTasks.process(AssignedStreamsTasks.java:475)
    at org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:550)
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:802)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:697)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:670)

    at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:400) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.AssignedStreamsTasks.process(AssignedStreamsTasks.java:475) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:550) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:802) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:697) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:670) ~[kafka-streams-2.5.1.jar:na]
Caused by: org.apache.kafka.common.errors.SerializationException: java.lang.InstantiationException: No target type provided
Caused by: java.lang.InstantiationException: No target type provided
    at io.github.kprasad99.streams.protobuf.serialization.ProtobufDeserializer.deserialize(ProtobufDeserializer.java:45) ~[classes/:na]
    at io.github.kprasad99.streams.protobuf.serialization.ProtobufDeserializer.deserialize(ProtobufDeserializer.java:1) ~[classes/:na]
    at org.apache.kafka.streams.state.StateSerdes.valueFrom(StateSerdes.java:160) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.state.internals.MeteredWindowStoreIterator.next(MeteredWindowStoreIterator.java:56) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.state.internals.MeteredWindowStoreIterator.next(MeteredWindowStoreIterator.java:26) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.kstream.internals.KStreamKStreamJoin$KStreamKStreamJoinProcessor.process(KStreamKStreamJoin.java:100) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorNode.lambda$process$2(ProcessorNode.java:142) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.maybeMeasureLatency(StreamsMetricsImpl.java:806) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:142) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:201) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:180) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:133) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.kstream.internals.KStreamJoinWindow$KStreamJoinWindowProcessor.process(KStreamJoinWindow.java:55) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorNode.lambda$process$2(ProcessorNode.java:142) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.maybeMeasureLatency(StreamsMetricsImpl.java:806) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:142) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:201) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:180) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:133) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:104) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.StreamTask.lambda$process$3(StreamTask.java:383) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.maybeMeasureLatency(StreamsMetricsImpl.java:806) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:383) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.AssignedStreamsTasks.process(AssignedStreamsTasks.java:475) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:550) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:802) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:697) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:670) ~[kafka-streams-2.5.1.jar:na]

2020-12-06 21:55:39.930 ERROR 141897 --- [-StreamThread-1] o.a.k.s.p.internals.StreamThread         : stream-thread [kafka-join-example-4aa10729-e5b7-4a33-89c6-906dd8ab2e5d-StreamThread-1] Encountered the following unexpected Kafka exception during processing, this usually indicate Streams internal errors:

org.apache.kafka.streams.errors.StreamsException: Exception caught in process. taskId=1_4, processor=KSTREAM-SOURCE-0000000001, topic=kp.department, partition=4, offset=1, stacktrace=org.apache.kafka.common.errors.SerializationException: java.lang.InstantiationException: No target type provided
Caused by: java.lang.InstantiationException: No target type provided
    at io.github.kprasad99.streams.protobuf.serialization.ProtobufDeserializer.deserialize(ProtobufDeserializer.java:45)
    at io.github.kprasad99.streams.protobuf.serialization.ProtobufDeserializer.deserialize(ProtobufDeserializer.java:1)
    at org.apache.kafka.streams.state.StateSerdes.valueFrom(StateSerdes.java:160)
    at org.apache.kafka.streams.state.internals.MeteredWindowStoreIterator.next(MeteredWindowStoreIterator.java:56)
    at org.apache.kafka.streams.state.internals.MeteredWindowStoreIterator.next(MeteredWindowStoreIterator.java:26)
    at org.apache.kafka.streams.kstream.internals.KStreamKStreamJoin$KStreamKStreamJoinProcessor.process(KStreamKStreamJoin.java:100)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.lambda$process$2(ProcessorNode.java:142)
    at org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.maybeMeasureLatency(StreamsMetricsImpl.java:806)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:142)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:201)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:180)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:133)
    at org.apache.kafka.streams.kstream.internals.KStreamJoinWindow$KStreamJoinWindowProcessor.process(KStreamJoinWindow.java:55)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.lambda$process$2(ProcessorNode.java:142)
    at org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.maybeMeasureLatency(StreamsMetricsImpl.java:806)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:142)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:201)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:180)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:133)
    at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:104)
    at org.apache.kafka.streams.processor.internals.StreamTask.lambda$process$3(StreamTask.java:383)
    at org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.maybeMeasureLatency(StreamsMetricsImpl.java:806)
    at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:383)
    at org.apache.kafka.streams.processor.internals.AssignedStreamsTasks.process(AssignedStreamsTasks.java:475)
    at org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:550)
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:802)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:697)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:670)

    at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:400) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.AssignedStreamsTasks.process(AssignedStreamsTasks.java:475) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:550) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:802) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:697) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:670) ~[kafka-streams-2.5.1.jar:na]
Caused by: org.apache.kafka.common.errors.SerializationException: java.lang.InstantiationException: No target type provided
Caused by: java.lang.InstantiationException: No target type provided
    at io.github.kprasad99.streams.protobuf.serialization.ProtobufDeserializer.deserialize(ProtobufDeserializer.java:45) ~[classes/:na]
    at io.github.kprasad99.streams.protobuf.serialization.ProtobufDeserializer.deserialize(ProtobufDeserializer.java:1) ~[classes/:na]
    at org.apache.kafka.streams.state.StateSerdes.valueFrom(StateSerdes.java:160) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.state.internals.MeteredWindowStoreIterator.next(MeteredWindowStoreIterator.java:56) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.state.internals.MeteredWindowStoreIterator.next(MeteredWindowStoreIterator.java:26) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.kstream.internals.KStreamKStreamJoin$KStreamKStreamJoinProcessor.process(KStreamKStreamJoin.java:100) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorNode.lambda$process$2(ProcessorNode.java:142) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.maybeMeasureLatency(StreamsMetricsImpl.java:806) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:142) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:201) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:180) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:133) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.kstream.internals.KStreamJoinWindow$KStreamJoinWindowProcessor.process(KStreamJoinWindow.java:55) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorNode.lambda$process$2(ProcessorNode.java:142) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.maybeMeasureLatency(StreamsMetricsImpl.java:806) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:142) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:201) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:180) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:133) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:104) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.StreamTask.lambda$process$3(StreamTask.java:383) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.maybeMeasureLatency(StreamsMetricsImpl.java:806) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:383) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.AssignedStreamsTasks.process(AssignedStreamsTasks.java:475) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:550) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:802) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:697) ~[kafka-streams-2.5.1.jar:na]
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:670) ~[kafka-streams-2.5.1.jar:na]

A: I cleaned up your configuration a little bit, this should work. If it doesn't please create a small sample app and share, then we can look at this further.
spring:
  application.name: kafka-join-example
spring.kafka.bootstrap-servers: 192.168.56.101:19092
spring.cloud.stream.kafka.streams.bindings.process-in-0.consumer.valueSerde: io.github.kprasad99.streams.AppSerdes$EmployeeSerde
spring.cloud.stream.kafka.streams.bindings.process-in-1.consumer.valueSerde: io.github.kprasad99.streams.AppSerdes$DepartmentSerde
spring.cloud.stream.kafka.streams.bindings.process-out-0.producer.valueSerde: io.github.kprasad99.streams.AppSerdes$DepartmentDataSerde
spring.cloud.stream:
  bindings:
    process-in-0:
      destination: kp.sch
    process-in-1:
      destination: kp.lm
    process-out-0:
      destination: kp.lm.sch
  kafka.streams.binder:
    brokers:
    - 192.168.56.101:19092
#    replication-factor: 3
#    required-acks: 2
    min-partition-count: 5
    configuration:
      commit.interval.ms: 100
      default:
        key.serde: org.apache.kafka.common.serialization.Serdes$StringSerde
        value.serde: io.github.kprasad99.streams.kafka.serde.ProtobufSerde

You can also define these beans in your application as below.
@Bean
public Serde<Department> departmentSerde() {
  return new DepartmentSerde();
}

// add the other two Serde beans.

If you define these Serde beans in the application, then you don't need the 3 corresponding valueSerde properties in the configuration as the beans get priority.


text:
Q: How do I assign specific roles to each user in rails? Suppose there are 2 roles- admins who can manage everything, and users who have registered, and need admin approval of the specific CRUD actions they can perform on each controller.
Like X can create and read Articles only, while Y can perform update and delete actions.
How do I also provide for the admin to assign the users these specific roles from the website itself?

A: You should check rolify gem: https://github.com/RolifyCommunity/rolify
But if you want just 2 roles(User and Admin), you can add new column to user table :admin, :boolean, default: false, then you can check in your controllers you can write before_filter which check if @current_user.admin and if not it redirects or does smth else.
In your view you can hide buttons for updating and deleting unless @current_user.admin

A: How about this Gem https://github.com/stffn/declarative_authorization/ ?
You can make it very granule. Define the roles then you can assign your CURD accordingly. Also it has a very good Helper methods that you can use to determine which role do what task on the View or Controller.
Assumption is based on

*

*User has many roles through AccessList

*Role has many users through AccessList

*AccessList belongs to role

*AccessList belongs to user

Here is a quick digram ( I assume you will take care of the Models )

Here is the module that I made to DRY some of the common tasks.
NOTE: Declarative Authorization has stacks of helpers, following is just to compliment them, some of the functions might be redundant and can be refactored and written better. It is just a nightly built :)
module AuthenticationRelated
  def what_are_current_user_roles
    objArray = []
    current_user.roles.each do |role|
      objArray.push role.name
    end
    return objArray
  end

  def does_user_have_this_role?(role_name)
    result = false
    obj_array = what_are_current_user_roles
    obj_array.each do |a_role|
      if a_role == role_name
        result = true
      end
    end
    result
  end

  def is_admin?
    athu = false
    if  signed_in?
      current_user.roles.each do |role|
        if role.name == 'admin'
          athu = true
        end
      end
    end
    return athu
  end

#  class_instance MUST be a parent class
# If you need to Authenticate
  def user_allowed_create_and_edit?(class_model, class_instance)
    user_is_allowed = false
    if permitted_to? :create, class_model.new and has_user_own_this(class_instance)
      user_is_allowed = true
    else
      user_is_allowed = false
    end
    # Override everything if user is admin
    if is_admin?
      user_is_allowed = true
    end

    return user_is_allowed

  end

# Authentication for Builder
# relation has to be set to access_list
  def has_user_own_this(model)

    user_who_owns_this = model.access_list.user_id
    if current_user.id == user_who_owns_this
      return true
    else
      return false
    end

  end

  def find_current_user_acls
    acl = []
    acls = AccessList.joins(:user).where("users.id = ?",current_user.id)
    acls.each do |an_acl|
     acl.push an_acl.id
    end
    acl
  end

end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Let's Encrypt setup for subdomain which is pointed to other host I'm trying to setup a two server system, where one is doing webhosting and the another is delivering content (CDN) for the webhost server.
I currently own two servers and they both have Let's Encrypt SSL.
webhost https://example.com
example.com 123.123.123.123

CDN https://foo.com
foo.com 111.111.111.111

I have setuped a subdomain to my webhost server:
cdn.example.com, which is pointing to the CDN server foo.com 111.111.111.111.
The problem is that the cdn.example.com does not have Let's Encrypt SSL.
How can I get the Let's Encrypt SSL for the cdn.example.com which is pointing to the foo.com 111.111.111.111?
When I run:
certbot --apache --cert-name example.com -d cdn.example.com

It gives an error:
Failed authorization procedure. cdn.example.com (http-01): urn:acme:error:unauthorized :: The client lacks sufficient authorization :: Invalid response from http://cdn.example.com/.well-known/acme-challenge/PaKenmvAqHoOdOBUhThxxxxx: "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML
2.0//EN\">\n\n<title>404 Not Found</title>\n\n
Not Found
\n<p"

IMPORTANT NOTES:
 - The following errors were reported by the server:

   Domain: cdn.example.com    Type:   unauthorized    Detail: Invalid response from    http://cdn.example.com/.well-known/acme-challenge/PaKenmvAqHoOdOBUhThxxxxx: "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML
   2.0//EN\">\n\n<title>404 Not    Found</title>\n\n
Not Found
\n<p"

   To fix these errors, please make sure that your domain name was    entered correctly and the DNS A/AAAA record(s) for that domain    contain(s) the right IP address.

Running default Debian and Apache2 installation.
I guess I have to manually set the acme-challenge files in my CDN server? What commands should I run?

A: In order to achieve what you want: you can copy the SSL configuration of the CDN domain(https://foo.com) and edit it for the domain cdn.example.com; just replace the traces of foo.com with cdn.example.com.
I can't give any more detail on the process since I don't know your server configuration.
However, as a suggestion(since I don't know your exact requirements), it seems to me like you aren't really in need of a separate domain for your CDN. On the other server, you can simply create a configuration for cdn.example.com.

A: The short answer is "You don't".
You don't need SSL on your secondary host (foo.com).
Here is all you need to do:

*

*Generate SSL for cdn.example.com

*Setup reverse http proxy on your cdn.example.com. So that all HTTPS requests will be provided with valid ssl from cdn.example.com, but the content would be served using HTTP content of http://foo.com
Apache configuration: https://www.digitalocean.com/community/questions/apache-proxypass-and-reverseproxy-to-a-ssl-https-configured-domain
Here is example on how I would do it using NGINX:
server  {
    listen  443 ssl;
    server_name  cdn.example.com;
    ssl  on;
#BEGIN OPTIONAL--in case you want to have more stats on foo.com
    proxy_set_header Host            $host;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header ClientIP $remote_addr;
#END OPTIONAL--
    ssl_certificate /etc/ssl/cdn.example.com.pem;
    ssl_certificate_key /etc/ssl/cdn.example.com.key;
    location  / {
            proxy_pass  http://foo.com:80/;
    }
}


text:
Q: android communicate with webpage, get 502 error I have a friend who's written a servlet which just serves XML (just XML, no SOAP or etc., Content-Type: text/xml).
Now I'm trying to access it using android. I can access the page fine if I surf to the page with Firefox, but if I access it using my android application I get an HTTP 502 error.
The code I'm using is:
AlertDialog alertDialog;
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("x");
try {
    HttpResponse response = httpClient.execute(httpGet, localContext);
    alertDialog = new AlertDialog.Builder(view.getContext()).create();
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
           return;
        }
    });
    alertDialog.setTitle("Response");
    alertDialog.setMessage(response.getStatusLine().toString());
    alertDialog.show();

    alertDialog.setMessage(EntityUtils.toString(response.getEntity()));
    alertDialog.show();
} catch (IOException e) {
    alertDialog = new AlertDialog.Builder(view.getContext()).create();
    alertDialog.setTitle("Sorry");
    alertDialog.setMessage("There was a problem connecting to the login-service.");
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
             return;
         }
     });
    alertDialog.show();
}

And are there any recommended ways to parse the XML? Like if there was a specific tag in there such as title, message, ...

A: For the connection problem I would suggest the following: It seems like there is a problem with a proxy or with the method you try to connect. Usually it would be a proxy, which is not able to forward the request to the specific server. But in the case, that you can view the site via FireFox it shouldn't be that problem. You could try to use the FireBug Addon to analyze the request onto that server though.
Anyway, try this method instead of the HttpGet:
HttpReq request = Http.getInstance().createRequest();
request.setUrl("URL");
request.setMethod("GET");
request.execute();
message = request.getResult();

Another thing you could try would be, using the HttpGet and play with the setFollowRedirects(true/false) method. Maybe you have to turn it off or explicit on.
For the XML problem, I would suggest this site: http://www.ibm.com/developerworks/xml/library/x-android/ which helped me alot to parse some RSS Feeds. Personally I prefer the SAX Parser on that site (they introduce a few technics).


text:
Q: how to put two parameters by jquery in a link to use by codeigniter i want to put two parameters by jquery in href of a link and then use by codeigniter, my code is below:
$("#user_comment_show").append("
"+...+'<a id="remove_link" href="<?php echo base_url().'my_site/remove_user_comment/';?>'+data.user_email_address+"/"+data.user_text+'">'+.....+"
"

i see data.user_email_address and data.user_text in source page but by select a link codeigniter shows me an error :

The URI you submitted has disallowed characters.

what's wrong with code and how to send these two parameters to my public function in codeigniter by jquery in a link. i appreciate to help me solve my problem

data.user_email_address  &&    data.user_text find by ajax in database

my a link in source page

A: change into like this
$("#user_comment_show").append("
<a id='remove_link' href='<?php echo base_url()?>/my_site/remove_user_comment/'+data.user_email_address+'/'+data.user_text+'>Your Link Name
")

hopefully this will work fine.


text:
Q: How to make nvidia command permanent I'm running Ubuntu 12.04 with an Nvidia GeForce GT620 video card. As I'm running it through an older LG DLP tv I was having problems with overscan till I discovered this command that fixes the overscan problem:
sudo nvidia-settings --assign 0/CurrentMetaMode="DFP-0: 1280x720 { ViewPortIn=1280x720, ViewPortOut=1190x680+44+20 }"
Unfortunately I've had no luck in making this part of the startup process and I need to run the command in a terminal each time the pc starts. I've tried adding
0/CurrentMetaMode="DFP-0: 1280x720 { ViewPortIn=1280x720, ViewPortOut=1190x680+44+20 }"
to nvidia-settings-rc via gedit ~/.nvidia-settings-rc but still no luck in making the command permanent for each reboot. Any ideas on what should I try next?

A: Add the command to /etc/rc.local before exit 0 and it will execute on boot.


text:
Q: Как вызвать метод дочернего класса, записанного в другом файле? У меня возникла проблема, если кто знает как ее решить и имеет время, помогите пожалуйста.
Я имею родительский класс, который находится в файле tester.py
l1 = [1, 1, 2]

class A:
   def __init__(self,l):
      self.l = l

   def qw(self):
        if l1[0] == 1:
           import qwe
           qwe.calculate()

f = A(l)
f.qw()

И также дочерний класс который находится в файле qwe.py
import tester

class B(tester.A):

   def calculate(self):
        print(self.l[0]+'Ok')

Я хочу использовать метод дочернего класса который находится в другом файле в родительском. Я пыталась сделать это так
              import qwe
            qwe.calculate()

f = A(l1)
f.qw()

Но у меня возникает ошибка и я не знаю почему, возможно, кто-то знает решение?

A: Вам надо объект класса B создать внутри класса A, тогда к нему можно будет применить метод calculate
test.py
l1 = [1, 1, 2]

class A:
   def __init__(self,l):
      self.l = l

   def qw(self):
        if l1[0] == 1:
           import test2
           qwe = test2.B(l1)
           qwe.calculate()

f = A(l1)
f.qw()

test2.py
class B():
    def __init__(self, _list):
        self._list = _list

    def calculate(self):
        print(f'{self._list[0]} Ok')

A: Попробуйте так:
tester.py
from qwe import B

class A:
    def __init__(self, _list, value):
        self._list = _list
        self.value = value

        self.b = B(self._list)

    def qw(self):
        if self._list[0] == self.value:
            self.b.calculate()

my_list = [1, 1, 2]

a = A(my_list, 1)
a.qw()

qwe.py
class B():
    def __init__(self, _list):
        self._list = _list

    def calculate(self):
        print(f'{self._list[0]} Ok')


text:
Q: NSString to ByteArray and back I am implementing an interface, which specifies writeBytes() and readBytes() on a file.
The data has to be transported as JSON.
For readBytes I do the following:

*

*NSFileHandle readDataOfLength  - to read from a file

*NSString initWithData: encoding: - to specify a given encoding

*NSString getBytes:buffer

*put each buffer[i] into a JSON array for transport : [116,101,115,116] for example "test" as UTF-8

On the other hand writeBytes should be doing about the same:

*

*Parse the JSON array to a NSArray

*NSArray getObjects:buffer - the conversion up to this point is successful

*NSString initWithBytes:buffer length: encoding: - is not working, the return value is null

*NSData dataUsingEncoding:

*NSFileHandle writeData
Apparently NSString initWithBytes cannot handle buffers with content such as [116,101,115,116]. Is there any other way to convert a NSString into a byte array and back ?
Thanks

A: Are you using the NSUnicodeStringEncoding encoding ? If so, then you may have to prefix your bytes with a valid B.O.M (See NSString reference, section "Interpreting UTF-16-encoded data").
Have you made a test with the NSASCIIStringEncoding to check that your code works for simple case ?

A: Have you verified that the bytes within the array are a valid UTF-8 representation of a string? (http://en.wikipedia.org/wiki/UTF-8)
If not, you'll get back nil:
#import <Foundation/Foundation.h>

int
main()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    char ary[] = { 116, 101, 115, 116, 255 };

    NSString *s = [[NSString alloc] initWithBytes: ary length: 5 encoding: NSASCIIStringEncoding];
    NSString *s2 = [[NSString alloc] initWithBytes: ary length: 5 encoding: NSUTF8StringEncoding];
    NSLog(@"s: %@, s2: %@", s, s2);

    [pool release];
}

When run, this prints:

2010-01-13 14:08:23.315 a.out[50653:903] s: testÿ, s2: (null)


text:
Q: JqGrid SubGrid with Entity framework MVC I have two tables (Parent/Child) that i want to display using the subgrid functionality in Jqgrid. the Main Grid Populates the data from my datamodel (parent table) but when the subgrid is expanded the data from the child table is not populated. have a look at my code, where am i going wrong?
Jquery
$(function () {
    $("#grid").jqGrid({
        url: "./EditManifest/GetTodoLists",
        datatype: 'json',
        mtype: 'Get',
        colNames: ['ID', 'BL', 'CARRIER BL', 'CARRIER', 'DESTINATION', 'TIN', 'TELEPHONE', 'ADRESS',],
        colModel: [
            { key: true, name: 'ID', index: 'ID', editable: false },
            { key: true, name: 'BL', index: 'BL', editable: false, sortable: true },
            { key: false, name: 'CARRIER_BL', index: 'CARRIER_BL', editable: true, edittype: 'text' },
            { key: false, name: 'CARRIER', index: 'CARRIER', editable: true, edittype: 'text' },
            { key: false, name: 'DESTINATION', index: 'DESTINATION', editable: true, edittype: 'text' },
            { key: false, name: 'TIN', index: 'TIN', editable: true, edittype: 'text' },
            { key: false, name: 'TELEPHONE', index: 'TELEPHONE', editable: true, edittype: 'text' },
            { key: false, name: 'ADRESS', index: 'ADRESS', editable: true, edittype: 'text' },
           ],
        pager: jQuery('#pager'),
        rowNum: 10,
        rowList: [10, 20, 30, 40],
        height: '100%',
        viewrecords: true,
        multiselect: false,
        subGrid: true,
        subGridUrl: "./EditManifest/subgrid",
        subGridModel: [{
            colNames: ['BL', 'Container', 'Size', 'Type', 'TotalWeight', 'HS Code', 'ATA'],
            colModel: [{ key: true, name: "BL", index: "BL", width: 80 },
                        { key: true, name: "ContianerNumber", index: "ContianerNumber", width: 130 },
                        { name: "Contianersize", index: "Contianersize", width: 70 },
                        { name: "ContianerType", index: "ContianerType", width: 70 },
                        { name: "TOTALWEIGHT", index: "TOTALWEIGHT", width: 70 },
                        { name: "hscode", index: "hscode", width: 130 },
                        { name: "ArrivalDate", index: "ArrivalDate", width: 70 }]
        }
        ],
        caption: 'Edit Manifest Data',
        emptyrecords: 'No records to display',
        jsonReader: {
            root: "rows",
            page: "page",
            total: "total",
            records: "records",
            repeatitems: false,
            Id: "0"
        },
        autowidth: true,
        multiselect: false

    }).navGrid('#pager', { edit: true, add: false, del: false, search: false, refresh: true },
        {
            // edit options
            zIndex: 100,
            url: './EditManifest/Edit',
            closeOnEscape: true,
            closeAfterEdit: true,
            recreateForm: true,
            afterComplete: function (response) {
                if (response.responseText) {
                    alert(response.responseText);
                }
            }
        });
});

controller
  public class EditManifestController : Controller
    {
        public StatusFollowUPEntities db = new StatusFollowUPEntities();
        public ActionResult Index()
        {
            return View();
        }
    public JsonResult GetTodoLists(string sidx, string sord, int page, int rows)
            {
                int pageIndex = Convert.ToInt32(page) - 1;
                int pageSize = rows;
                var todoListsResults = db.tblBLs.Select(
                        a => new
                        {
                            a.ID,
                            a.BL,
                            a.CARRIER_BL,
                            a.CARRIER,
                            a.DESTINATION,
                            a.SAILINGDATE,
                            a.TIN,
                            a.TELEPHONE,
                            a.ADRESS,

                        });
                int totalRecords = todoListsResults.Count();
                var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
                if (sord.ToUpper() == "DESC")
                {
                    todoListsResults = todoListsResults.OrderByDescending(s => s.BL);
                    todoListsResults = todoListsResults.Skip(pageIndex * pageSize).Take(pageSize);
                }
                else
                {
                    todoListsResults = todoListsResults.OrderBy(s => s.BL);
                    todoListsResults = todoListsResults.Skip(pageIndex * pageSize).Take(pageSize);
                }
                var jsonData = new
                {
                    total = totalPages,
                    page,
                    records = totalRecords,
                    rows = todoListsResults
                };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
    public JsonResult subgrid(string id)
            {

                var ctrDetails = db.tblCtrDetails.Where(a => a.BL == id).Select(
                        a => new
                        {

                            a.BL,
                            a.ContianerNumber,
                            a.Contianersize,
                            a.ContianerType,
                            a.TOTALWEIGHT,
                            a.hscode,
                            a.ArrivalDate,

                        });

                //Returning json data
                return Json(ctrDetails);
            }
}

View


text:
Q: beginner error handling to return boolean these are my error handling instructions:
Write a function that takes a function f as its first parameter and a positive integer x as its second parameter. When given these two parameters, no_errors should then apply the function f on every integer from 0 up to and including x. If this series of applications runs just fine (no errors occur) then no_errors should return True. If instead at some point applying f causes an error, then no_errors should return False.
I realize this should be fairly simple but as a new coder I'm struggling to see what is wrong with my code. Any help is greatly appreciated, thank you!
def no_errors(f,x):
    try:
        for i in range(0, x+1):
            f(i)
            print(f(i))
            return True

    except:
        return False

A: You need return True to occur AFTER the loop has finished, so do not indent as far:
def no_errors(f, x):
    try:
        for i in range(0, x+1):
            f(i)
            print(f(i))
        return True
    except:
        return False

A working example:
def foo(x):
    return x * x

print no_errors(foo, 10)

0
1
4
9
16
25
36
49
64
81
100
True


text:
Q: Hide the chart's series in ExtJs 4 I'm migrating ExtJs 3 application to ExtJs 4. One of the component that I need to change is a chart that has series of bars and lines on it. It displays the data for previous and current years. Beside the chart there is a checkbox "Compare to previous year". When it checked all line series should be visible and hidden when it is not checked.
In ExtJs 3 I did this task by setting visibility:hidden for series styles this way: chart.setSeriesStyles(...). But in ExtJs 4 this function is absent and I can't find any other way to hide series on demand.
Here is the code of my chart:
    var store = Ext.create('Ext.data.Store', {
    fields: [
        'month','data1','data2','data3','prev_data1','prev_data2','prev_data3'
    ],
    proxy: {
        type: 'ajax',
        url: '/getmonthlystats.php'
    }
});

this.statChart = Ext.create('Ext.chart.Chart', {
    flex: 1,
    store: store,
    axes: [{
        type: 'Numeric',
        position: 'left',
        minimum: 0,
        maximum: 100,
        fields: [
            'data1',
            'data2',
            'data3',
            'prev_data1',
            'prev_data2',
            'prev_data3'
        ],
        label: {
            renderer: Ext.util.Format.numberRenderer('0,0')
        },
        grid: true
    },{
        type: 'Category',
        position: 'bottom',
        fields: ['month'],
        label: {
            rotate: {
                degrees: 315
            }
        }
    }],
    series: [{
        type: 'column',
        yField: ['data1','data2','data3'],
        xField: 'month'
    },
    {
        type: 'line',
        yField: 'prev_data1',
        xField: 'month'
    },{
        type: 'line',
        yField: 'prev_data2',
        xField: 'month'
    },{
        type: 'line',
        yField: 'prev_data3',
        xField: 'month'
    }]
});

So, the lines prev_data1, prev_data2, prev_data3 should be shown or hidden when needed (depending on the checkbox state). Does anyone know the way to do that?
Thanx.

A: Try this (sample from my code):
handler: function (checkbox, checked) {
    if (checked)
        chart.series.getAt(index).showAll();
    else
        chart.series.getAt(index).hideAll();
}

A: For ExtJS 4.2.x
If you use 'legend' with your charts, this code will be better for you:
var chart = Ext.getCmp(chartId);
var series = chart.series.getAt(seriesIndex);
if (value) {
    series.showInLegend = true;
    series.showAll();
} else {
    series.showInLegend = false;
    series.hideAll();
}
chart.redraw();


text:
Q: Is there a way to reduce the size of the git folder? Seems like my project is getting bigger and bigger with every git commit/push. Is there a way to clean up my git folder?

A: Run:
git remote prune origin

Deletes all stale tracking branches which have already been removed at origin but are still locally available in remotes/origin.
git gc --auto

'G arbage C ollection' - runs housekeeping tasks (compresses revisions, removes loose/inaccessible objects). The --auto flag first determines whether any work is required, and exits without doing anything if not.

A: yes yes, git gc is the solution, naturally,
and locally - you can just delete the local repository and clone it again,
but there is something more important here...
the seconds you wait for that huge git & externals to process are collected to long minutes in which are collected to hours of inefficient time spent,
Create a new (entirely, not just a branch) repository from scratch, including the only recent version of files, naturally you'll loose all the history,
but when in code-world it is not time to get sentimental, there is no point dragging along the entire 5 years of code every commit or diff,
you can still store the old git & externals somewhere, if you get nostalgic :]
but, at some point you really have to move along :]
your team will thank you!

A: One scenario where your git repo will get seriously bigger with each commit is one where you are committing binary files that you generate regularly. Their storage won't be as efficient than text file.
Another is one where you have a huge number of files within one repo (which is a limit of git) instead of several subrepos (managed as submodules).
In this article on git space, AlBlue mentions:

Note that Git (and Hg, and other DVCSs) do suffer from a problem where (large) binaries are checked in, then deleted, as they'll still show up in the repository and take up space, even if they're not current.

If you have large binaries stored in your git repo, you may consider:

*

*managing those binaries in an external repository.

*manage your .git repo size

*try and remove those binaries from your history with git filter-branch (warning: this will rewrite the history, which is bad if you have already pushed your repo and if other have pulled from it)

As I mentioned in "What are the file limits in Git (number and size)?", the more recent (2015, 5 years after this answer) Git LFS from GitHub is a way to manage those large files (by storing them outside the Git repository).

A: I'm not sure what you want. First of all, of course each time you commit/push the directory is going to get a little larger, since it has to store each of those additional commits.
However, probably you want git gc which will "cleanup unnecessary files and optimize the local repository" (manual page).
Another possibly relevant command is git clean which will delete untracked files from your tree (manual page).

A: Running this command is extremely dangerous, but will shrink your repository by erasing all your git recovery/backup files:
git reflog expire --expire=now --all && git gc --prune=now --aggressive

It will erase all files git uses to recover your repository from some bad command, for example, if you did git reset --hard, you can usually recover the files lost. But if you do git reset --hard before the git reflog expire... command, then you lost everything. Now, your only hope is to use some tool which analyses your file system and try to recover the erased files, if they were not overridden.

A: git clean -d -f -i is the best way to  do it.
This will help to clean in a more  controlled manner.
-i stands for interactive.

A: Don't know if it will shrink it, but after I run git clean, I often do git repack -ad as well, which reduces the number of pack files.


text:
Q: How can I detect the device and browser being used so that autoPlay for video components work on iOS devices? [React.js] The Problem
I'm in the process of creating my web portfolio and have a video looping in the background. This works fine on my website when being used on desktop on all major browsers (Chrome, Firefox, Safari) and on my Android with the exception of Firefox for some reason... but I realized that iOS overrides the autoPlay attribute on video tags. This then leaves my website with a huge play button in the background that the user cant press since it's z-index is -1.

My Proposed Solution
To remedy this, I thought maybe I can detect the device and browser being used and then use conditional rendering to have a gif of the same video playing in the background instead. I know this doesn't seem like the most practical approach but at least I can have the major browsers on iOS devices displaying something rather than a play button that isn't accessible.

What I Need to Know
What code can I use to detect the device and browser being used, or will using the browser be enough and I won't have to worry about the device? Or maybe there is a more practical approach to tackle this problem? Maybe there is something wrong in my code? Anything will help!

Code
<video
    autoPlay
    playsInline
    loop
    muted
    style={{
      position: 'absolute',
      width: '100%',
      left: '50%',
      right: '50%',
      top: '50%',
      height: '100%',
      objectFit: 'cover',
      transform: 'translate(-50%, -50%)',
      zIndex: '-1'
    }}
    >
    <source src={s3BucketObject} type='video/mp4' />
  </video>

A: You could parse the user agent https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent, but it won't be fun and you'll probably forget some cases.
Best choice is using a library like https://www.npmjs.com/package/react-device-detect, the most popular for React.


text:
Q: Linked Lists Java Replacing Nodes I'm having difficulty with a linked lists program. I want to write a method that destructively replaces the value in each node n by the sum of the values in the tail of the list. So if the list is 2,3,5,7; I want to change it to 17,15,12,7. I am given a program where I have to add a method that does this. I can change the first number, but I can not change the other three, and I am stuck. If anyone could help me, that would be great.
Original Program
public class IntList {
private int value;
private IntList next;

public IntList(int v, IntList n) {          // Constructor
    value = v;
    next = n;
  }

public int getValue() { return value; }       // Getters
public IntList getNext() { return next; }
public void setValue(int v) { value = v; }    // Setters
public void setNext(IntList n) { next = n; }

// Find the last node of a linked list.
public IntList findLast() {
   if (getNext() == null) return this;
   else return getNext().findLast();
 }

// Add a new node with value v at the end of l;

public void addEnd(int v) {
    findLast().setNext(new IntList(v,null));
  }

// Add up the values in a list, recurring down the owner
public int sumList() {
   if (getNext() == null) return getValue();
   else return getValue() + getNext().sumList();
  }

// Convert list of int to string

// Recursive method for constructing the end of the string, after the
// initial open bracket.

 public String toString1() {
   if (getNext() == null)
      return getValue() + "]";
   else return getValue() + ", " + getNext().toString1();
 }

// Top level rountine that starts with the "[" and then calls toString1 to
// do the rest.

  public String toString() {
    return "[" + toString1();
  }

// Recursive method for finding the sum of a list, using recursion down
// an argument. Note that this is a static method, associated with the class
// not with an object owner.

 static public int sumListArg(IntList l) {
    if (l==null) return 0;
    else return l.getValue() + sumListArg(l.getNext());
   }

 static public void main(String[] args) {
   IntList l = new IntList(2,null);
   l.addEnd(3);
   l.addEnd(5);
   l.addEnd(7);
   System.out.println("h");
   System.out.println(l.toString());
   System.out.println("Sum = " + l.sumList());
} // end main
} // end RecursiveIntList

Here is what I have so far for my method (I think it's logically ok, but it's incorrect):
 public static void runningSum(IntList l)
{
     l.setValue(l.sumList());

    while(l.getNext() != null)
     {
        l.setNext(l.getNext()); //Set Next to be the next reference
        l.getValue();  //Get the Next's value
        l.setValue(l.sumList()); //Add the rest of the numbers together
     }

     if(l.getNext() == null)
     {
         l.setValue(l.getValue());
     }

     System.out.println(l.toString());
}

A: There is a nice and elegant solution:
public int sumList() {
    if (getNext() == null) {
        return getValue();
    }
    value = getValue() + getNext().sumList();
    return value;
 }

In this method you recursively iterate through the List, and summarize all the elements that are behind the current element, and set the value at the same time.

A: This is the code:
public static void runningSum(IntList l)
{
    IntList head = l;
    int rSum = l.sumList();

    while(l != null)
    {
        int curRS = rSum;
        curRS -= l.getValue();
        l.setValue(rSum);
        rSum = curRS;
        l = l.getNext();
    }

    System.out.println(head.toString());
}

I'll break it in several parts to explain what's going on. We want to code a procedure that takes the head of a list and alters the list in the way you describe; basically the first element must become the sum of all the original elements; the second element must be the sum of all elements except the first, and so on. The last element, the tail, must remain unchanged.
public static void runningSum(IntList l)
{

The function we need to remember the head that was passed to the function; we save l in a variable called head.
    IntList head = l;

The running sum for the first element is the sum of all elements; so we call sumList and store the result in a variable called rSum.
    int rSum = l.sumList();

This is a very typical idiom in data structures programming; while the element is not null, you loop.
    while(l != null)
    {

The running sum of the next element is rSum minus the value of the current element.
        int nextRS = rSum - l.getValue();

Now we can set running sum of the current element to rSum.
        l.setValue(rSum);

For the next iteration, the current running sum is nextRS. Finally we update l to point to the next element.
        rSum = nextRS;
        l = l.getNext();
    }

If we didn't keep track of head, now we wouldn't know what to print.
    System.out.println(head.toString());
}

A: Linked lists lend themselves to recursion. A recursive solution might look like this:
public static void runningSum(IntList l) {
    if (l.getNext() != null) {
        runningSum(l.getNext());
        l.setValue(l.getValue() + l.getNext().getValue());
    }
}


text:
Q: Appropriate word for a specific situation I am trying to translate a word into English. (More details at the end, but please read this first, so that your judgment is not influenced by my bias).
What I am trying to find is a word for this situation:
Say, I have a machine that gives packages of candy. Let's say I can get 10 packs of candy. At the end, the machine will print in the last package "Hello from the candy machine" or whatever. So the initial state is that this printing is done always at the end. Let's call this "Print at the end mode"
But I want another mode, in which I can indicate the machine that I want the message to be printed every 2 packs... or every three packs... or every five packs...
You see, I can customize at will at what point I want my event (the printing) to happen.
How can I call this mode?

The word I am trying to translate is the Japanese 任意, which according to dictionary means "at your discretion" "voluntary" "any" "arbitrary" "optional" "discretion" "free will".
I don't think one of this would be appropriate for the problem above.

A: You are talking about the ability to change the settings on the machine at will. This would be called a custom setting or customizable setting. Once you have changed this setting, you would call it a customized setting.*  In your example, you may call it a **customizable print setting or something similar.


text:
Q: Strange Qt crash when deleting a QTextEdit I've been beating my head against a Qt crash for a day now. A coworker suggested I try to simplify the situation, which I did. I cannot get it to crash in a small test app, but inside the app I'm working on, this silly minimal code usually crashes on the delete line (and calling deleteLater()) doesn't help -- I get the same call stack.
QTextEdit *blah = nullptr;
void MyClass::DoTheThing()
{
   if (blah != nullptr)
   {
       delete blah;
   }
   blah = new QTextEdit();
   blah->setText("BLAH");
   // like, literally, i'm not even attaching the QTextEdit to anything
}

A QPushButton triggers DoTheThing. Sometimes I get a crash immediately, sometimes it takes 15-20 tries.
    Qt5Cored.dll!QListData::isEmpty() Line 116  C++
    Qt5Cored.dll!QList<QObject *>::isEmpty() Line 201   C++
    Qt5Cored.dll!QObject::~QObject() Line 1106  C++
    Qt5Widgetsd.dll!QLayout::~QLayout() Line 772    C++
    Qt5Widgetsd.dll!QBoxLayout::~QBoxLayout() Line 571  C++
    [External Code]
    Qt5Widgetsd.dll!QWidget::~QWidget() Line 1444   C++
    [External Code]
    Qt5Cored.dll!QObjectPrivate::deleteChildren() Line 2123 C++
    Qt5Widgetsd.dll!QWidget::~QWidget() Line 1532   C++
    Qt5Widgetsd.dll!QFrame::~QFrame() Line 264  C++
    Qt5Widgetsd.dll!QAbstractScrollArea::~QAbstractScrollArea() Line 507    C++
    Qt5Widgetsd.dll!QTextEdit::~QTextEdit() Line 667    C++

The QList is of course the child list, which is bad data.
I've also seen a crash constructing the QTextEdit.
>   Qt5Cored.dll!QListData::isEmpty() Line 116  C++
    Qt5Cored.dll!QList<QObject *>::isEmpty() Line 201   C++
    Qt5Cored.dll!QObject::~QObject() Line 1106  C++
    Qt5Widgetsd.dll!QGesture::~QGesture() Line 123  C++
    Qt5Widgetsd.dll!QPanGesture::~QPanGesture() Line 304    C++
    [External Code]
    Qt5Widgetsd.dll!qDeleteAll<QSet<QGesture *>::const_iterator>(QSet<QGesture *>::const_iterator begin, QSet<QGesture *>::const_iterator end) Line 320 C++
    Qt5Widgetsd.dll!qDeleteAll<QSet<QGesture *> >(const QSet<QGesture *> & c) Line 328  C++
    Qt5Widgetsd.dll!QGestureManager::filterEventThroughContexts(const QMultiMap<QObject *,enum Qt::GestureType> & contexts, QEvent * event) Line 418    C++
    Qt5Widgetsd.dll!QGestureManager::filterEvent(QWidget * receiver, QEvent * event) Line 527   C++
    Qt5Widgetsd.dll!QApplication::notify(QObject * receiver, QEvent * e) Line 2960  C++
    Qt5Cored.dll!QCoreApplication::notifyInternal2(QObject * receiver, QEvent * event) Line 1075    C++
    Qt5Cored.dll!QCoreApplication::sendEvent(QObject * receiver, QEvent * event) Line 1470  C++
    Qt5Widgetsd.dll!QWidgetPrivate::propagatePaletteChange() Line 1862  C++
    Qt5Widgetsd.dll!QWidget::setBackgroundRole(QPalette::ColorRole role) Line 4226  C++
    Qt5Widgetsd.dll!QTextEditPrivate::init(const QString & html) Line 194   C++
    Qt5Widgetsd.dll!QTextEdit::QTextEdit(QWidget * parent) Line 636 C++

Any idea where to start looking? I've commented out all of the surrounding code. Might be a double delete, or maybe something is trashing some shared data in Qt somewhere, but because of the semi-reproducible nature of the crash it's proving very difficult to debug. Might also be a timing issue, though none of the other threads seem to be doing anything.

A: You are assigning something to nullptr:
QTextEdit *blah = nullptr;

Which basically means you never allocated any memory to it in the first place, so when you call:
delete blah;

You are deleting something that does not exist.

A: Alright, so this looks like memory trashing from something completely unrelated. Early returning from a fragile function that uses Qt objects but has nothing to do with UI prevents this crash.
Nothing mysterious in Qt, nothing to see here, move along.


text:
Q: Animation when changing 'home:' content class Segunda extends StatefulWidget {
  Tercera createState() => Tercera();
}

class Tercera extends State<Segunda> {
  var size, heightA, widthA;

  List<StatefulWidget> bodys = [Segunda2(), Segunda3()];

  int n = 0;

  @override
  Widget build(BuildContext context) {
    setState(() {
      size = MediaQuery.of(context).size;
      heightA = size.height;
      widthA = size.width;
    });

    return Scaffold(
        body: Container(
      width: widthA,
      height: heightA,
      child: Column(children: [
        Container(
          width: widthA,
          height: heightA * 0.1,
          color: Colors.blue,
          child: ElevatedButton(
              onPressed: () {
                setState(() {
                  n++;
                });
              },
              child: Text("Change")),
        ),
        Container(
          width: widthA,
          height: heightA * 0.9,
          child: MaterialApp(
            home: bodys[n],
          ),
        )
      ]),
    ));
  }
}

I want to always have a little bar at the beginning of my app, but changing the content (im learning flutter and i want to make a little game).
So, I made a test app like this

that changes the content when you press a button, I have a list with different StatefulWidgets (Segunda2 and Segunda3 returns just a solid background color).
Is there anyway I can add a animation when changing the content of the 'home', like the ones you can do with Navigator (the new content sliding from the left, for example)
Im using this way because when I try to use navigator to change between classes while trying to have a permanent widget (like the blue bar in this case) it just ignores it and changes the whole thing, I want to press a button and see the new content coming from a side.
i tried using navigator to change content with an animation, but the persistent widget that i want to have just changes as well.
I tried using persistent widget perse, and it didnt work for me

A: Dont use Multiple MaterialApp and you can use PageView widget.
Try to follow this widget structure.
void main() => runApp(ProviderScope(child: MyApp()));

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Segunda(),
    );
  }
}

class Segunda extends StatefulWidget {
  Tercera createState() => Tercera();
}

class Tercera extends State<Segunda> {
  var size, heightA, widthA;

  // List<StatefulWidget> bodys = [Segunda2(), Segunda3()];
  List<Widget> bodys = [Text("Segunda2"), Text("Segunda3")];

  final PageController controller = PageController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LayoutBuilder(builder: (_, constraints) {
        heightA = constraints.maxHeight;
        widthA = constraints.maxWidth;
        return Container(
          width: widthA,
          height: heightA,
          child: Column(children: [
            Container(
              width: widthA,
              height: heightA * 0.1,
              color: Colors.blue,
              child: ElevatedButton(
                  onPressed: () {
                    // setState(() {});
//                     controller.animateToPage(page,
//                         duration: duration, curve: curve);
                    controller.nextPage(
                        duration: Duration(milliseconds: 300),
                        curve: Curves.ease);
                  },
                  child: Text("Change")),
            ),
            Expanded(
              child: PageView.builder(
                controller: controller,
                itemBuilder: (context, index) {
                  return bodys[index];
                },
              ),
            )
          ]),
        );
      }),
    );
  }
}


text:
Q: How do I pass an unflattened array repetition to a reduce in Perl 6? I'm trying to pass an xx repeated array to an [X~] reduce function but finding that the array gets flattened. I've searched the online docs and stack overflow, but couldn't find anything. Unfortunately, my Perl 6 knowledge is quite rudimentary (though I do know Perl 5 quite well).
[X~](<1 2>, <1 2>)    # 11 12 21 22 (WHAT I WANT)
[X~](<1 2> xx 2)      # 1 2 1 2 (NOT WHAT I WANT)
[X~](<1 2> xx 2).tree # 1 2 1 2
[X~](<1 2>.tree xx 2) # 1 2 1 2

Looking at the .perl dumps doesn't enlighten me much:
(<1 2>, <1 2>).perl    # (("1", "2"), ("1", "2"))
(<1 2> xx 2).perl      # (("1", "2"), ("1", "2")).list
(<1 2> xx 2).tree.perl # ("1", "2"; "1", "2").item

I'm using rakudo-star-2014.12.1-parrot.msi.

A: Assuming you also want your code to work with arrays repeated more than twice, the workaround I came up with reads
(<1 2> xx 2).tree.reduce({ @^a X~ @^b })

Note that flattening behaviour and the List/Parcel distinction1 are known pain points.
A plan to improve the situation has been around for a while (cf Great List Refactor) and is supposed to land before the 6.0 release at the end of the year.
1 All three expressions you looked at have different types:
(<1 2>, <1 2>).WHAT    # (Parcel)
(<1 2> xx 2).WHAT      # (List)
(<1 2> xx 2).tree.WHAT # (LoL)

The last one is a List-of-Lists.


text:
Q: How to render a razor components with subcomponents without any parameters when functions wants to be passed a renderFragment I try to use BUnit for component testing in a Blazor server-side project.
I am quite new to this and tried to start a real simple setup:
using var ctx = new TestContext();
ctx.Services.AddTransient<IProposalService, ProposalService>();
var cut = ctx.Render<Proposals>();

Now I can't run this since Rider states:

Method 'Render' has 1 parameter(s) but is invoked with 0 argument(s)

After this, I checked in the documentation how to pass arguments for this.
Since my component Proposals does not have any [parameter] tag in it only two injections:
[Inject] private IProposalService ProposalService { get; set; }
[Inject] private NavigationManager NavigationManager { get; set; }

So I though there might be some ChildContent missing, since I am using a ProposalCard like so:
@foreach (var prop in _proposalList)
{
   <ProposalCard Proposal="@prop"/>
}

referring to the section Rendering a component under test inside other components in the last section from the documentation link above.
Here they use the following code:
public class NestedComponentTest
{
  [Fact]
  public void Test()
  {
    using var ctx = new TestContext();

    var wrapper = ctx.RenderComponent<Wrapper>(parameters => parameters
      .AddChildContent<HelloWorld>()
    );
    var cut = wrapper.FindComponent<HelloWorld>();
  }
}

I tried like so:
var cut = ctx.Render<Proposals>(parameters => parameters.AddChildContent<ProposalCard>());

*

*the first render: Method 'Render' has 1 parameter (s) but iS invoked with 0 argument (s)

*the second render: Cannot resolve symbol 'AddChildContent'

*when I run the first render: ProposalTest.cs(35, 35): [CS7036] There is no argument given that corresponds to the required formal parameter 'renderFragment' of 'TestContext. Render (RenderFragment)'

*when running the second render: ProposalTest.cs (37, 35): [CS1061] 'RenderTreeBuilder' does not contain a definition for 'AddChildContent' and no accessible extension method 'AddChildContent' accepting a first argument of type
'RenderTreeBuilder' could be found (are you missing a using directive or an assembly reference?)

I thought maybe I have to create the renderFragment myself with new renderFragment(..) and pass it though I feel really puzzled with this right now and was not able to find any reference for this within the documentation which make it seem kind of a weird idea.
How can I make the render method work for my context here?
update
it seems a little bit better but still now working
Though when I read the second exmpample from here I seems like I shouldn't be passing anything at all, since the are able to just call
var cut = RenderComponent<FetchData>();

A: I just had to call:
ctx.RenderComponent<Proposals>();

be cautious I overlooked that my IDE made the wrong suggestion for this


text:
Q: Implement SQL Server 2012 AlwaysOn I have two SQL Server instances running on Windows Server, SQL Server cluster with 2 nodes with shared storage (Active, Active type).
The SQL Server version running is SQL Server 2012 Enterprise edition.
Can we implement AlwaysOn on this? Is it feasible then what are the complexities and steps?

A: Yes and no. You cannot configure it in such a way that each server hosts a copy of the database. They both share the same storage, so that is logical. You have a SQL Server cluster OR you configure AlwaysOn between the 2. However, you can host an AlwaysOn copy on a SQL Server failover cluster instance (FCI). In that case, you need one or more other SQL Servers to host the synchronous or a-synchronous copies. The picture below might illustrate this a bit (no sure where I got it from, it is from my own library):
Mind the difference between the two: a SQL Server failover cluster hosts an instance of SQL Server using 2 servers in an active/passive configuration. An AlwaysOn node hosts a database or group of databases on a single instance.
Here are some possible usefull links:
https://blog.papercut.com/the-ultimate-guide-to-high-availability-methods-for-microsoft-sql-server/
https://www.brentozar.com/archive/2012/02/introduction-sql-server-clusters/
https://techcommunity.microsoft.com/t5/Premier-Field-Engineering/An-overview-of-High-Availability-and-Disaster-Recovery-solutions/ba-p/370479
Is this the configuration you currently have?

If so, then you can create a setup like the one below. You can see that there is an extra SQL Server node with 1 instance that hosts an a-synchronous copy for each database of the availability group (where a-synchronous would be common for a DR setup). You can use synchronous copies technically, but you would not use that for a DR scenario. Synchronous copies rely heavily on latency and is therefore suitable for an High Availability scenario. For your understanding; look at the AlwaysOn layer as a seperate thing. There is no difference in configuring the AlwaysOn group on single server instances or a Failover Cluster Instance. AlwaysOn is configured at the database level.

Be aware that you need to buy an extra license in this configuration. However, recently there was a change in licensing for SA customers, which would make it free:
https://cloudblogs.microsoft.com/sqlserver/2019/10/30/new-high-availability-and-disaster-recovery-benefits-for-sql-server/
Also; don't forget to look how you would setup your maintenance scripts and that instance level configuration is not copied to the other server. If you require things to be in sync, then you need to script that or update it manually every time you change something.
I found this easy setup guide for you to configure the AlwaysOn group:
https://www.sqlservercentral.com/blogs/alwayson-availability-groups-step-by-step-setup
Also be aware that mixing 2 seperate technologies (Failover Cluster Instances and AlwaysOn) make things more complex. It is more complex to troubleshoot then when you have only 1 technology. You could setup a similar HA/ DR setup with AlwaysOn only like below. Just be aware that you need double the storage space (which you don't need for a cluster setup) and you would have some more latency (because you need to wait for the commit of the synchronous copy):

There are a lot of things you need to make decisions on, because all the technologies have their strong and weak points. The only option to learn them all is to read about it, but I think you get a fairly good jumpstart with all this information.
Oh and you might want to delete your Answer earlier. I saw you also set it in the comments, so it is double.


text:
Q: Universal Linking Bad JSON I have my apple-app-site-association uploaded correctly on the server. It's formatted as follows:
{
    "activitycontinuation": {
      "apps": [
        "ASDF.com.company.appname"
      ]
    },
    "applinks": {
        "apps": [],
        "details": [
            {
                "appID": "ASDF.com.company.appname",
                "paths": [ "/menu/*", "/menu/*/*", "/account/history", "/"]
            }
        ]
    }
}

My entitlements is set up correctly:
applinks:company-site.com
activitycontinuation:company-site.com

I've verified with Charles proxy on install the device fetches the correct file from the server.
When looking at the device log, I get the following error:
Bad apple-app-site-association JSON: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
I've ran the JSON through a linter and it came out fine. The server sends back Content-Type: application/json in the header. I'm testing on a physical device. I've tried typing the URLs manually in safari and clicking them through a text message. Does anyone see where the problem is?

A: I believe the first section of your apple-app-site-association is unnecessary and may be causing the validation error (Apple is pretty strict about this file). I haven't seen this in any other places — is there a particular reason you're including it?
Try this and see if it works better:
{
    "applinks": {
        "apps": [],
        "details": [
            {
                "appID": "ASDF.com.company.appname",
                "paths": [ "/menu/*", "/menu/*/*", "/account/history", "/"]
            }
        ]
    }
}

Also note that Universal Links will never work when entered manually into Safari. See here for more info.


text:
Q: css font url stops working when publishing Assets in yii2 In my css file
 @font-face {
             url('fontpu/anmo000-webfont.woff') format('woff'),
             url('fontpu/anmo000-webfont.ttf') format('truetype'),
                            }

    .punjabi{

    font-family: 'anmollipiregular';
    }

then I registered this in my AppAsset class.
public $css = [
        'css/site.css',
        'css/punjabi.css',
    ];

the fontpu folder is in the web folder (the web accessible folder which contains index.php).
if I place the css under the <style> tags in the index.php the font works fine but when publishing asset, it does not load.
 How do I give font's path to it?

A: According to W3 :

Partial URLs are interpreted relative to the source of the style sheet, not relative to the document

You should simply use the correct relative path :
url('../fontpu/anmo000-webfont.woff') format('woff'),
url('../fontpu/anmo000-webfont.ttf') format('truetype'),


text:
Q: Replace a computed getter/setter with mapState and mapMutations So, I am syncing a computed value to a component and setting it with a computed setter when it syncs back from the component.
My question is: Is it possible to replace a computed getter/setter with mapState and mapMutations or how would one achieve this in a more compact way?
<template>
    <SomeComponent :value.sync="globalSuccess"></SomeComponent>
</template>
export default {
    //...
    computed: {
        globalSuccess: {
            get() {
                return this.$store.state.globalSuccess;
            },
            set(val) {
                this.$store.commit("globalSuccess", val);
            }
        }
    }
}

I tried replacing it like this:
export default {
    //...
    computed: {
        ...mapState(["globalSuccess"]),
        ...mapMutations(["globalSuccess"]),
    }
}

But unfortunately mapMutations(["globalSuccess"]) maps this.globalSuccess(value) to this.$store.commit('globalSuccess', value) according to the documentation of vuex.
But since my computed value gets set with globalSuccess = true internally through :value.sync in the template and not this.globalSuccess(true), globalSuccess will never be set to true.
Any idea how this could be possible? Or am I stuck using computed values with getter and setter?

A: So I just found out about this vuex module https://github.com/maoberlehner/vuex-map-fields which I installed as described on there:
// store.js
import { getField, updateField } from 'vuex-map-fields';
Vue.use(Vuex);
export default new Vuex.Store({
    getters: {
        getField,
        //...
    },
    mutations: {
        updateField,
        //...
    },
});

And then I made use of mapFields function:
// App.vue
export default {
    //...
    computed: {
        ...mapFields(["globalSuccess"]),
    }
}

Which apparently dynamically maps to a computed setter and getter exactly as I wanted it:
export default {
    //...
    computed: {
        globalSuccess: {
            get() {
                return this.$store.state.globalSuccess;
            },
            set(val) {
                this.$store.commit("globalSuccess", val);
            }
        }
    }
}

A: Here's a syntax I use:
export default {
  //...
  computed: {
    globalSuccess: {
      ...mapState({ get: 'globalSuccess' }),
      ...mapMutations({ set: 'globalSuccess' }),
    },
  },
}

No additional dependencies needed. If you use it a lot, I suppose you could create a helper for it, but it is pretty neat as it is.


text:
Q: I need to convert my timestamp of "1/1/2018 0:00" for my time series analysis. Is there a code to keep the time relevant in this function? My goal is to highlight anomalies and trends seasonally in water quality data so I am trying to determine how I can convert and format the time stamps correctly.
I am reading in from a csv. I have tried as.Date but that doesn't keep the time stamp and the time of day is relevant to my analyses.

A: You can also use as.timeDate("2019-07-02 13:33:12") from the timeDate package.


text:
Q: Send uglify parameter for certain flow in gulp Problem:
Having multiple tasks for uglifying different javascript bundles and wanting to uglify this only on production with his own deploy task.
Solutions:
Too much verbosity to define every task by itself.
Using yargs for getting the parameters is also a too difficult approach for this problem.

A: Thought about this for a while, and came up with the perfect solution for myself.
For instance I have this gulp task that concatenates javascript files:
gulp.task('concat', function() {
  var stream = gulp
    .src('public/js/**/*.js')
    .pipe(concat('bundle.js'));
  if (ugly) {
    stream
      .pipe(uglify());
  }
  return stream
    .pipe(gulp.dest('public/dist'));
});

As you can see I check if the ugly variable is set within the task, so all I have to do is to create a task that is triggered before the concat task and sets the ugly variable to true.
You could make such a function, do make sure the ugly variable is accessible to the scope of both task functions.
var ugly;
gulp.task('set-ugly', function() {
  ugly = true;
});

Last but not least the gulp deploy task, with as first task set-ugly.
gulp.task('deploy', ['set-ugly', 'concat']);

You can also use this approach for any other variable that you need to use within a task.

A: You can use gulp-if in your pipeline testing your environment variable and executing the uglify step only when needed


text:
Q: What does this block of code do? I'm not quite sure what this means or whats it doing, Could some one elaborate?
Player player = (Player) sender;

A: It takes the object referenced by sender, and attempts to cast it into the type Player.  Java objects are strongly typed, which means you have to declare the type of the object.
If the object referenced by sender cannot be cast to a Player object, than an exception will be thrown for an InvalidCast.

A: That's a plain old java type cast. See the JLS Casting conversion for the full details.
It assumes that sender is type-compatible with a Player.

A: It converts sender to a Player object. Otherwise, the datatype of player wouldnt match the datatype of sender. Usually done if sender could initially have been declared as a subclass.

A: This is an assignment, with a cast operation.
You can learn a lot about java cast operator with the answers to this question: How does the Java cast operator work?

A: When you read it 'converts' sender to Player, don't think it literally converts them.
There are many times where you pass a variable which COULD be many different things, then when you figure out what thing it is, you use the cast operator to actually MAKE one of those things.
Heres a imperfect analogy:
Imagine you get a phone call from your local computer club president, he says that a member of the club will be coming to see you about something.
Now, you don't know which member is coming, if its female or male, how old or even their name, you know nothing about the future visitors attributes.
Once they appear at your door, you realize its your buddy Frank, now in your mind, the 'visitor' (sender) from code above, is CAST to 'Frank', who you know lots of stuff about, age, how many kids, address etc.
Before the CAST, you knew very little about the sender, but after the cast you can now access all kinds of info on the new Object, since you now know its TYPE.
Hope this helps.

A: this is a simple java typecast...
is this in a bukkit minecraft server plugin? if it is, what it does is typecast the player sending the command to a Player object. Player Objects are used to target specific players in code. the player object will have the name of the player who sent the command.


text:
Q: R - Using an if else statement to categorise sickness type based on the number of days off? I am currently trying to find out how many people in a company have 3 days off out of the prior consecutive 5 in a year.
The following fake data is listed below for an example:
structure(list(Region = c("20SUSSX", "20SUSSX", "20SUSSX", "20SUSSX",
"20SUSSX", "20SUSSX", "20SUSSX", "20SUSSX", "20SUSSX", "20SUSSX",
"20SUSSX", "20SUSSX", "20SUSSX", "20SUSSX", "20SUSSX", "20SUSSX",
"20SUSSX", "20SUSSX", "20SUSSX", "20SUSSX"), On_date = structure(c(16122,
16123, 16127, 16128, 16129, 16130, 16132, 16133, 16134, 16135,
16279, 16280, 16281, 16282, 16286, 16287, 16290, 16291, 16444,
16458), class = "Date"), Name = c("bob", "bob", "bob", "bob",
"bob", "bob", "bob", "bob", "bob", "bob", "bob", "bob", "bob",
"bob", "bob", "bob", "bob", "bob", "bob", "bob"), Sickness_Type = c("?",
"?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?",
"?", "?", "?", "?", "?", "?")), .Names = c("Region", "On_date",
"Name", "Sickness_Type"), row.names = c(NA, -20L), class = c("tbl_df",
"tbl", "data.frame"))

With this data frame, my aim is to use an if else statement in the 'Sickness_Type' variable that enters a 1 if sickness occurs for 3 out of the previous 5 days and a 0 if it is has occurred less frequently than this. A row is only present for an employee where sickness is present.
I am unsure how to do this due to my lack of familiarity with the date formats in R. Currently I have been trying using dplyr's mutate and if_else but had no luck.
Any help on this would be much appreciated,
Thanks!

A: I believe you can achieve this using dplyr's lag function, e.g.:
dat %>%
    group_by(Name) %>%
    arrange(On_date) %>%
    mutate(Sickness_Type=ifelse(On_date - lag(On_date, 3) <= 5, 1, 0))

The lag(On_date, 3) retrieves the date of the third entry before the current one, so if this is less than or equal to five, then you know there have been three sicknesses in that time range.
The result is:
    Region    On_date  Name Sickness_Type
     <chr>     <date> <chr>         <dbl>
1  20SUSSX 2014-02-21   bob            NA
2  20SUSSX 2014-02-22   bob            NA
3  20SUSSX 2014-02-26   bob            NA
4  20SUSSX 2014-02-27   bob             0
5  20SUSSX 2014-02-28   bob             0
6  20SUSSX 2014-03-01   bob             1
7  20SUSSX 2014-03-03   bob             1
8  20SUSSX 2014-03-04   bob             1
9  20SUSSX 2014-03-05   bob             1
10 20SUSSX 2014-03-06   bob             1
11 20SUSSX 2014-07-28   bob             0
12 20SUSSX 2014-07-29   bob             0
13 20SUSSX 2014-07-30   bob             0
14 20SUSSX 2014-07-31   bob             1
15 20SUSSX 2014-08-04   bob             0
16 20SUSSX 2014-08-05   bob             0
17 20SUSSX 2014-08-08   bob             0
18 20SUSSX 2014-08-09   bob             1
19 20SUSSX 2015-01-09   bob             0
20 20SUSSX 2015-01-23   bob             0

Obviously, you will need to handle the cases where there are not that many previous days, leading to NA's.
A straight-forward way to do that would be to add a second nested ifelse statement with an is.na().


text:
Q: Update values in a column by incrementing a counter using SQL query I have a table structure like this :
-----------------------------------
ID  |    NAME   |   SORTED_ID
-----------------------------------
1   |    B      |
2   |    D      |
3   |    A      |
4   |    C      |

Using a single SQL query i want to update the SORTED_ID column like this, based on the sorted order.
-----------------------------------
ID  |    NAME   |   SORTED_ID
-----------------------------------
1   |    B      |      2
2   |    D      |      4
3   |    A      |      1
4   |    C      |      3

How can i do so?

A: In SQLite, this is a bit painful.  Here is one method using a correlated subquery:
update t
    set sorted_id = (select count(*)
                     from t t2
                     where t2.name <= t.name
                    );

Note:  this is expensive on mediumish tables (those more than a thousand rows or so).


text:
Q: What is the best way to feed image data (tfrecords) from GCS to your model? I set myself a goal to solve the MNIST Skin Cancer dataset using only Google Cloud.
Using GCS & Kubeflow on Google Kubernetes.
I converted the data from jpeg to tfrecord with the following script:
https://github.com/tensorflow/tpu/blob/master/tools/datasets/jpeg_to_tf_record.py
I have seen a lot of examples how they feed a csv-file to their model but no examples with image data.
Should it be smart to copy all the tfrecords to the Google Cloud Shell so I can feed the data to my model like that?
Or are there any better methods available?
Thanks in advance.

A: In the case you are using Kubeflow, I would suggest to use the kubeflow pipelines.
For the preprocessing you could use an image that is build on top of the standard pipeline dataflow image gcr.io/ml-pipeline/ml-pipeline-dataflow-tft:latest where you simply copy your dataflow code and run it:
FROM gcr.io/ml-pipeline/ml-pipeline-dataflow-tft:latest
RUN mkdir /{folder}
COPY run_dataflow_pipeline.py /{folder}
ENTRYPOINT ["python", "/{folder}/run_dataflow_pipeline.py"]

See this boilerplate for the dataflow code that does exactly this. The idea is that you write the TF records to Google Cloud Storage (GCS).
Subsequently you could use Google Cloud's ML engine for the actual training. In this case you can start also from the image google/cloud-sdk:latest and basically copy over the required files with probably a bash script that will be run to execute the gcloud commands to start the training job.
FROM google/cloud-sdk:latest
RUN mkdir -p /{src} && \
    cd /{src}
COPY train.sh ./
ENTRYPOINT ["bash", "./train.sh"]

An elegant way to pass on the storage location of your TF records into your model is to use TF.data:
# Construct a TFRecordDataset
train_records = [os.path.join('gs://{BUCKET_NAME}/', f.name) for f in
                 bucket.list_blobs(prefix='data/TFR/train')]
validation_records = [os.path.join('gs://{BUCKET_NAME}/', f.name) for f in
                      bucket.list_blobs(prefix='data/TFR/validation')]

ds_train = tf.data.TFRecordDataset(train_records, num_parallel_reads=4).map(decode)
ds_val = tf.data.TFRecordDataset(validation_records,num_parallel_reads=4).map(decode)

# potential additional steps for performance:
# https://www.tensorflow.org/guide/performance/datasets)

# Train the model
model.fit(ds_train,
          validation_data=ds_val,
          ...,
          verbose=2)

Check out this blog post for an actual implementation of a similar (more complex) kubeflow pipeline


text:
Q: Inverted index for top tags I am working with Spark and I want to know how can I get inverted index for top tags?
sqlDF = spark.sql("SELECT * FROM Users")
sqlDF.show(

+--------+--------------------+--------------------+----------+
|      id|               title|                tags|closeddate|
+--------+--------------------+--------------------+----------+
|48704243|Transfer files fr...|<java><android><f...| null|


text:
Q: What is the best complexity of N-Queens puzzle? Can the N-Queens puzzle theoretically be solved in polynomial time? If so, what is the best complexity of it? I have found many algorithms, but I haven't found what exactly the time complexity is. Are there any papers or documents giving an exact number of its complexity?
(P.S. The explicit solution is very interesting, but I forgot to say, I wish to find all the solutions.)

A: This link cites a "well known" explicit solution. It can be computed in linear time:
http://www.chegg.com/homework-help/questions-and-answers/poor-man-s-n-queens-problemn-queens-arranged-n-x-n-chessboard-way-queen-checks-queen-queen-q1009394

*

*n is even but not of the form (n mod 6 = 2).
  Place queens on the squares
  (m, 2m) and (n/2 +m, 2m-1) for m = 1, 2, . . . , n/2

*n is even but not of the form (n mod 6 = 0) and
  Place queens on the squares
  (m, 1+(2(m-1)+ n/2 - 1)mod n) and
  (n+1-m, n-(2(m-1)+n/2 -1)mod n) for m = 1,2,...,n/2

*n is odd.
  Use (1) or (2), whichever is appropriate, on n - 1 and extend with a queen at (n,n).

Note that enumerating all solutions would take much longer. The number of solutions grows super-exponentially with the size of the board (http://oeis.org/A000170), so they are impossible to enumerate even with 2^O(x) time (but only O(n) space is needed).

A: Do you mean finding one solution or all solutions? If you only want to find one solution, this can be done trivially, according to Wikipedia.

Explicit solutions exist for placing n queens on an n × n board,
  requiring no combinatorial search whatsoever.


text:
Q: SwiftUI - How to apply the minimumScaleFactor view modifier to scale down text sizes equally? How can we apply the minimumScaleFactor view modifier to scale down text sizes equally?
HStack(spacing: 60) {
    Text("L-V")
    Text("R-V")
}
.padding([.leading, .trailing],
         30)
.font(.custom("Large Title",
      size: 150.0))
.minimumScaleFactor(0.1)

Result:

As you can see, the L-V label is slightly bigger than the R-V label. Presumably this is because the views are assigned layout priority left -> right. But how can we ensure these two labels are scaled down to the same size on smaller screens?


text:
Q: emberjs: transitionToRoute Error no method 'addArrayObserver From the 'job' route I am trying to transition to 'careers' route using following code.
<script type="text/x-handlebars" data-template-name="job">
    <button {{action 'backToCareers' this}}>Back</button>
</script>

The controller with following gives 'Uncaught TypeError: Object # has no method 'addArrayObserver' ' error.
CareerApp.JobController = Ember.ObjectController.extend({
    backToCareers: function(){
       this.transitionToRoute('careers');
    }
});

If I change the code(see below) to provide model object the error changes to 'Uncaught More context objects were passed than there are dynamic segments for the route: careers '
CareerApp.JobController = Ember.ObjectController.extend({
    backToCareers: function(){
           var jobs = CareerApp.Job.findAll();
       this.transitionToRoute('careers', jobs);
    }
});

Following is the code of my Model and the router
CareerApp.Job = Ember.Model.extend({
  refNo: '',
  title: ''
});

CareerApp.Job.reopenClass({
 findAll: function(){
  return $.getJSON("http://site/jobs").then(
     function(response){
        var jobs = Ember.A();
        response.forEach(function(child){
           jobs.pushObject(CareerApp.Job.create(child));
        });
        return jobs;
     }
  );
 }
});

Router code
CareerApp.Router.map(function(){
 this.resource('careers', {path: '/'});
 this.resource('job', {path: '/jobs/:job_id'});
});

CareerApp.CareersRoute = Ember.Route.extend({
   model:function(){
       return CareerApp.Job.findAll();
   }
});

CareerApp.CareersController = Ember.ArrayController.extend({
   gradJobCount: function () {
       return this.filterProperty('isExp', false).get('length');
   }.property('@each.isExp')
});

A: The model hook is expected to return an array but you return a jQuery promise object. findAll should return an empty array which is filled when the callback is executed.
 findAll: function() {
     var jobs = [];

     $.getJSON("http://site/jobs").then(function(response){
         response.forEach(function(child){
             jobs.pushObject(CareerApp.Job.create(child));
         });
    });
    return jobs;
 }

A: As you pass jobs to CarreersController, this one needs to be an ArrayController, maybe you have to define it manually


text:
Q: HTTPRequest equivalent to cURL I have this particular cURL statement that I am trying to figure out the equivalent for it in an HTTP Request.
curl -X POST --upload-file movie-data-2013.json doc-movies-123456789012.us-east-1.cloudsearch.amazonaws.com/2013-01-01/documents/batch --header "Content-Type:application/json"
So far the HTTP Request equivalent I am able to compile is below:
Set oHTTPRequest = Server.CreateObject( "MSXML2.XMLHTTP.3.0" )
oHTTPRequest.Open "POST" _
              ,"doc-movies-123456789012.us-east-1.cloudsearch.amazonaws.com/2013-01-01/documents/batch" _
              False
oHTTPRequest.setRequestHeader "Content-type", "application/json"
oHTTPRequest.Send

For the most part I should be set, except there's one part it's missing, and I'm unsure how it's appended to the request.
There is a part in cURL that says: --upload-file movie-data-2013.json
Not sure how it applies in an HTTP Request. Does anyone how this applies?

A: I'd recommend trying .Net's built-in HttpWebRequest class over MSXML. There is an example of uploading text data on MSDN using the GetRequestStream method. You should be able to easily modify the sample to instead read the data from a file, for example using File.ReadAllBytes, and then write the returned data to the request stream.


text:
Q: pass line arguments to main from ant My question is How can I catch the arguments in the terminal using ant to run the main with these parameters,
example:
    ant 1 2 3 4 5
    public static void main(String[] args)
    {
      int[] meta = {0,0,0,0,0};
      for(int i=1; i < 6; i++)
      {
        meta[i-1] = Integer.parseInt(args[i]);
      }
    }

How can i do this, somebody help me pls C:?
 Here my build.xml
<project name="Tarea2LP" basedir="." default="main">

<property name="src.dir"     value="src"/>
<property name="classes.dir" value="classes"/>
<property name="jar.dir"     value="jar"/>
<property name="main-class"  value="Board"/>

<target name="clean">
    <delete dir="${classes.dir}"/>
    <delete dir="${jar.dir}"/>
</target>

<target name="compile">
    <mkdir dir="${classes.dir}"/>
    <javac srcdir="${src.dir}" destdir="${classes.dir}"/>
</target>

<target name="jar" depends="compile">
    <mkdir dir="${jar.dir}"/>
    <jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
        <manifest>
            <attribute name="Main-Class" value="${main-class}"/>
        </manifest>
    </jar>
</target>

<target name="run" depends="jar">

    <java jar="${jar.dir}/${ant.project.name}.jar" fork="true"/>
</target>

<target name="main" depends="run"/>

</project>

A: If the number of arguments is known you can use the -D option to pass in the argument and then in your "run" task target use 'arg' to pass it to jar file like
<target name="run" depends="jar">

    <java jar="${jar.dir}/${ant.project.name}.jar" fork="true">
        <arg value="${arg1}"/>
        <arg value="${arg2}"/>
        <arg value="${arg3}"/>
        <arg value="${arg4}"/>
        <arg value="${arg5}"/>
    </java>
</target>

and you should invoke your ant file as
ant -Darg1=1 -Darg2=2 -Darg3=3 -Darg4=4 -Darg5=5


text:
Q: Liveagent: the consol does not refresh I'm using the Liveagent console.
In the org ChatTest1 it worked fine: while the client was chatting with the operator he could see all the "actions" that the client was doing. The informations related to some objects ("Transcript" and another custom one) are updated automatically.
In the org ChatTest2 where we are now the refresh does not work anymore.
Has someone had the same issue? Do you know some possible solution?