text:
Q: RTD client in Python my goal is to get the updates of an rtd server in python
I've following call in excel which is working:
=RTD("xrtd.xrtd";;"EUCA")

For python I've found following client library: https://github.com/brotchie/pyrtd/blob/master/rtd/client.py
I tried to get a simple example where I can connect to the server
import sys
sys.path.append(".")
from client import RTDClient
name = "xrtd.xrtd"

try:
    client = RTDClient(name)
    client.connect(False)
    client.register_topic('EUCA')

except Exception as identifier:
    print(str(name) + " error : " + str(identifier))

My first problem was that I've used 64bit python, but after I solved this I receive following exception from the connect():

xrtd.xrtd error : This COM object can not automate the makepy process

*

*please run makepy manually for this object

I've no idea what I've to do now. I've python experience but no experience with COM Objects

A: Try this
import pythoncom
from rtd import RTDClient

if __name__ == '__main__':
    time = RTDClient('xrtd.xrtd')
    time.connect()
    time.register_topic('EUCA')

    while 1:
        pythoncom.PumpWaitingMessages()

        if time.update():
            print time.get('EUCA')


text:
Q: Adavantage of using connection from Data Source over JDBC Driver Manager Question is basically identify the best practices on data access layer.
I want to choose in between using a data source  or traditional driver manager to load the the connection on web applications.  I know very clearly following advantages

*

*Flexibility of configuration

*In built connection pooling mechanism

But if I can sacrifice advantage of flexibility with configuration and have own connection pooling mechanism, Do I get any other benefit out of data source. In other way around what are limitations or issues I would face while having application managed jdbc driver connection than container managed.
I know the question is so stupid that I should be knowing the advantage of somebody takes care of handling connection than my application.  But this is rare scenario where I can't use datasource in web application.  I would be looking following things

*

*How better I can design own connection pool my self?

*Is there any thing else I should take care when I access connection through DriverManager API

A: Note that is is very possible to programmatically create a DataSource (backed by a connection pool) dynamically based on user input.
Using Apache Commons-dbcp:
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(DATABASE_DRIVER_CLASS);
ds.setUsername(DATABASE_USERNAME);
ds.setPassword(DATABASE_PASSWORD);
ds.setUrl(DATABASE_URL);
ds.setInitialSize(1);
ds.setMaxActive(50);
ds.setDefaultAutoCommit(false);

So I think the question is not really between a DataSource and no-DataSource, but rather between a container managed DataSource and an application managed DataSource.
Container managed DataSources are easier to manage by server-admin types.  They can be tuned through the app server web UI, etcApplication managed DataSources do not have this advantage.

redpajama_set_name: RedPajamaStackExchange


text:
Q: c++ program performance difference in docker 3X slower I have c++ program and processing 1M lines , find pattern and select part of it as an example below .
The strange thing is its running almost 3 times slower in the docker in the same machine ?
both host / guest ubuntu 20.04 and same g++-8 compiled.
for (int i = 1; i <= 5; i++) {
      std::chrono::steady_clock::time_point begin =
          std::chrono::steady_clock::now();
      for (int i = 1; i <= val; ++i) {

        auto cx = data[i].find("sub");
        auto type_ = data[i].find("type"); //!= std::string::npos)
        type_ = data[i].find("type");

        type_ = data[i].find("applist");

        string str3 = data[1].substr(45, 110);

        str3 = data[1].substr(45, 110);
        str3 = data[1].substr(45, 110);
        str3 = data[1].substr(45, 110);

      }


text:
Q: R - Create ID by multiple factors How do I create a new ID label summarizing the information stored in two factors. I would like the one factor to be nested (!?) within the other one.
As a small example: Let's say I surveyed many trees and now I want to add a label to each examined branch that gives me the number of the tree and the number of the branch on that tree. It would be unnecessary and confusing, if all branches had just an ongoing ID.
Example code:
mydata = data.frame(tree   = rep(letters[1:3], each = 20),
                    branch = rep(round(runif(12)*1000, 0), each = 5),
                    values = runif(60))

(Please don't ask me, why the branches have such strange numbers, this is just an example!)
Of course, I could just use interaction(mydata$treat, mydata$labels) like this answer suggests. Also, for a unique ID I could use something like this. But both would give me an ongoing ID which is not discriminating between trees! I could also use a long and complicated for loop, but I'd like to have a simple answer (since I expect there to be one...).
Expected Output:
Should look something like the new ID column in the end.
mydata = data.frame(tree   = rep(letters[1:3],each = 20),
                    branch = rep(round(runif(12)*1000, 0), each = 5),
                    values = runif(60),
                    ID     = rep(rep(1:4, each = 5)));mydata

mydata$ID = interaction(mydata$tree, mydata$ID)

EDIT:
So the solution in the comments by @suchait works well for the example data actually gives me an ongoing ID not discriminating between trees. Also, I have no knowledge of the data.table package and I cannot get my head around how it works in detail. When I apply the solution to my tibble, it won't work (it gives me again an ongoing ID ignoring one factor). Therefore, I would really like to see a dplyr solution or something similar.

A: A dplyr solution using group_by to group the branches from each tree separately then just converting the branch IDs to factors and using the factor number as the branch ID
library(tidyverse)

tmp <- mydata %>%
  group_by(tree) %>%
  mutate(ID = str_c(tree, as.numeric(as.factor(branch)), sep = "."))


text:
Q: For which primes $p$ does $x^2\equiv3\pmod{p}$ have a solution? attempt at solution:  using Legendre symbol, what I did was notice that the equation has a solution if ($3/p$)=1 IFF ($p/3$)x(-1)^(p-1)/2 = 1
So, can I say that p has to satisfy two properties (4 cases)?  For example, case 1 is:
      If p≡1 mod3, then ($p/3$)=1, then we have a solution IFF p≡1 mod4

A: In this related question I proved that for every prime $p>3$, $-3$ is a quadratic residue iff $p\equiv 1\pmod{3}$ by using only the Cauchy theorem for groups. Since for every odd prime we know that $-1$ is a quadratic residue iff $p\equiv 1\pmod{4}$, and:
$$\left(\frac{3}{p}\right)=\left(\frac{-3}{p}\right)\left(\frac{-1}{p}\right),$$
it follows that $3$ is a quadratic residue $\!\!\pmod{p}$ iff $\color{blue}{p\equiv\pm 1\pmod{12}}$.


text:
Q: autoStatup = false not respected for spring cloud stream producer I'm using Spring Cloud Stream "2021.0.2" with Spring Boot "2.6.7" and having trouble disabling a producer from starting up automatically. Seems to work fine for consumer (checked actuator/bindings endpoint).
spring:
  kafka:
    bootstrap-servers: ${KAFKA_URL:http://localhost:29092}
  cloud:
    stream:
      function:
        definition: mqtt;mqttRoot;kafka
      bindings:
        mqtt-out-0:
          destination: input
          producer:
            autoStartup: false
        mqttRoot-out-0:
          destination: input
          producer:
            autoStartup: false
        kafka-in-0:
          destination: output
          group: mqtt
          consumer:
            autoStartup: false
            concurrency: 1

My use case is I'm trying to connect mqtt -> kafka and kafka -> mqtt using the spring-cloud-stream-kafka-binder and hive mq java reactor client. Alternatively is there another way to delay the initialisation of the producer/consumer beans? I've used an ApplicationRunner to connect to mqtt after startup.
@Configuration
@Log4j2
public class InputConfig {

    @Value("${mqtt.subscriptionTopic}")
    private String subscriptionTopic;

    private final Mqtt3ReactorClient inboundMqttClient;
    private final Mqtt3ReactorClient inboundRootMqttClient;

    @Autowired
    public InputConfig(@Qualifier("inboundMqttClient") Mqtt3ReactorClient inboundMqttClient,
                       @Qualifier("inboundRootMqttClient") Mqtt3ReactorClient inboundRootMqttClient) {
        this.inboundMqttClient = inboundMqttClient;
        this.inboundRootMqttClient = inboundRootMqttClient;
    }

    @Bean
    public Supplier<Flux<byte[]>> mqtt() {
        return new Input(inboundMqttClient, subscriptionTopic);
    }

    @Bean
    public Supplier<Flux<byte[]>> mqttRoot() {
        return new Input(inboundRootMqttClient, subscriptionTopic);
    }

}

@Log4j2
public class Input implements Supplier<Flux<byte[]>>, ApplicationRunner {

    private final Mqtt3ReactorClient inboundMqttClient;
    private final String subscriptionTopic;

    public Input(Mqtt3ReactorClient inboundMqttClient, String subscriptionTopic) {
        this.inboundMqttClient = inboundMqttClient;
        this.subscriptionTopic = subscriptionTopic;
    }

    @Override
    public Flux<byte[]> get() {
        FluxWithSingle<Mqtt3Publish, Mqtt3SubAck> subAckAndMatchingPublishes = inboundMqttClient.subscribePublishesWith()
                .topicFilter(subscriptionTopic).qos(MqttQos.AT_LEAST_ONCE)
                .applySubscribe();

        return subAckAndMatchingPublishes
                .doOnSingle(subAck -> log.info("Subscribed, " + subAck.getReturnCodes()))
                .doOnNext(publish -> log.debug(
                        "Received publish" + ", topic: " + publish.getTopic() + ", QoS: " + publish.getQos() +
                                ", payload: " + new String(publish.getPayloadAsBytes())))
                .map(Mqtt3Publish::getPayloadAsBytes);
    }

    @Override
    public void run(ApplicationArguments args) {
        Mono<Mqtt3ConnAck> connAckSingle = inboundMqttClient.connect();

        connAckSingle
                .doOnSuccess(connAck -> log.info("Connected, " + connAck.getReturnCode()))
                .doOnError(throwable -> log.info("Connection failed, " + throwable.getMessage()))
                .subscribe();
    }
}

@Configuration
@Log4j2
public class OutputConfig {

    @Value("${mqtt.publishTopic}")
    private String publishTopic;

    private final Mqtt3ReactorClient outboundMqttClient;
    private final Mqtt3ReactorClient outboundRootMqttClient;

    @Autowired
    public OutputConfig(@Qualifier("outboundMqttClient") Mqtt3ReactorClient outboundMqttClient,
                        @Qualifier("outboundRootMqttClient") Mqtt3ReactorClient outboundRootMqttClient) {
        this.outboundMqttClient = outboundMqttClient;
        this.outboundRootMqttClient = outboundRootMqttClient;
    }

    @Bean
    public Consumer<Flux<Output.GatewayNotification>> kafka() {
        return new Output(outboundMqttClient, outboundRootMqttClient, publishTopic);
    }
}

@Log4j2
public class Output implements Consumer<Flux<Output.GatewayNotification>>, ApplicationRunner {

    private final Mqtt3ReactorClient outboundMqttClient;
    private final Mqtt3ReactorClient outboundRootMqttClient;
    private final String publishTopic;

    public Output(Mqtt3ReactorClient outboundMqttClient,
                  Mqtt3ReactorClient outboundRootMqttClient,
                  String publishTopic) {
        this.outboundMqttClient = outboundMqttClient;
        this.outboundRootMqttClient = outboundRootMqttClient;
        this.publishTopic = publishTopic;
    }

    @Override
    public void accept(Flux<Output.GatewayNotification> gatewayNotifications) {
        Flux<Mqtt3Publish> messagesToPublish = gatewayNotifications
                .map(gatewayNotification -> Mqtt3Publish.builder()
                        .topic(publishTopic.replace("\\{gateway_address\\}", gatewayNotification.getAddress()))
                        .qos(MqttQos.AT_LEAST_ONCE)
                        .payload(gatewayNotification.getPayload().getBytes())
                        .build());

        outboundMqttClient.publish(messagesToPublish)
                .doOnNext(publishResult -> log.debug(
                        "Publish acknowledged: " + new String(publishResult.getPublish().getPayloadAsBytes())))
                .subscribe();

        outboundRootMqttClient.publish(messagesToPublish)
                .doOnNext(publishResult -> log.debug(
                        "Publish acknowledged: " + new String(publishResult.getPublish().getPayloadAsBytes())))
                .subscribe();
    }

    @Override
    public void run(ApplicationArguments args) {
        Mono<Mqtt3ConnAck> connAckSingle = outboundMqttClient.connect();

        connAckSingle
                .doOnSuccess(connAck -> log.info("Connected, " + connAck.getReturnCode()))
                .doOnError(throwable -> log.info("Connection failed, " + throwable.getMessage()))
                .subscribe();

        Mono<Mqtt3ConnAck> connAckSingleRoot = outboundRootMqttClient.connect();

        connAckSingleRoot
                .doOnSuccess(connAck -> log.info("Connected, " + connAck.getReturnCode()))
                .doOnError(throwable -> log.info("Connection failed, " + throwable.getMessage()))
                .subscribe();
    }

    @Data
    public static class GatewayNotification {
        private String address;
        private String payload;
        private Long buildingId;
    }
}

The underlying exception I'm trying to solve is:


text:
Q: How to create a Hashmap containing a vector of Regex options for each line in a file in Rust I am a Rust noob with a medium level knowledge of programming in general and have been stuck in this spot for quite a while. Essentially, I am reading from a file and performing regex to break up each line into groups that I want to process later. I am hoping to save each line in a hashmap as a vector of its groups, with the key of the hashmap being group 4.
I want to use a String to allow me to assign a value inside the for loop, but the captures_iter function is expecting a &str.
I am open to alternative solutions.
I alternate between two errors, and do not know a way around one without causing the other.
use std::fs::File;
use std::io::{BufRead, BufReader};
use regex::Regex;
use regex::Captures;
use std::collections::HashMap;

fn main() {
    //read file
    let input = File::open("../input.txt").unwrap();
    let reader = BufReader::new(input);

    //ugly regex, but it does exactly what I want it to
    let re = Regex::new(r"(?:(^[[:lower:]]+|^\d+) |)(?:([[:lower:]]+|[[:upper:]]+) |)(?:([[:lower:]]+|[[:upper:]]+|\d+|) |)-> ([[:lower:]]+)$").unwrap();

    //hashmap to store the 'instructions' which is the regex groups, with the key of group 4
    let mut instructions : HashMap<&str, Vec<&str>> = HashMap::new();

    for line in reader.lines().into_iter() {

        let line = line.unwrap();
        println!("Line Read: {}", line);

        for caps in re.captures_iter(&line){ //this line is where I am having touble, with or without the '&' before line, I get a different error

            let groups: Vec<&str> = caps.iter()
                .map(|m| match m {
                    Some(value) => value.as_str(),
                    None => ""
                })
            .collect();

            println!("{:?}", groups); //this prints exactly what I want

            instructions.insert(groups[4], groups); //this line is the one that causes the error, because of a reference outside the loop?
        }
    }
}

The error when line: for caps in re.captures_iter(&line){ is line does not live long enough

The error when line: for caps in re.captures_iter(line){ is mismatched types

I appreciate any help or advice. Please let me know if I can provide any more information.

P.S. This is for Advent of Code 2015, day 7. If you think I am going about this the complete wrong way also feel free to let me know.

A: You can make the groups to be a Vec<String> instead of Vec<&str>, and instructions to be HashMap<String, Vec<String>>, then it should work I think.
use regex::Captures;
use regex::Regex;
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
    //read file
    let input = File::open("../input.txt").unwrap();
    let reader = BufReader::new(input);

    //ugly regex, but it does exactly what I want it to
    let re = Regex::new(r"(?:(^[[:lower:]]+|^\d+) |)(?:([[:lower:]]+|[[:upper:]]+) |)(?:([[:lower:]]+|[[:upper:]]+|\d+|) |)-> ([[:lower:]]+)$").unwrap();

    //hashmap to store the 'instructions' which is the regex groups, with the key of group 4
    let mut instructions: HashMap<String, Vec<String>> = HashMap::new();

    for line in reader.lines().into_iter() {
        let line = line.unwrap();
        println!("Line Read: {}", line);

        for caps in re.captures_iter(&line) {
            //this line is where I am having touble, with or without the '&' before line, I get a different error

            let groups: Vec<String> = caps
                .iter()
                .map(|m| match m {
                    Some(value) => value.as_str().to_string(),
                    None => "".to_string(),
                })
                .collect();

            println!("{:?}", groups); //this prints exactly what I want

            instructions.insert(groups[4].clone(), groups); //this line is the one that causes the error, because of a reference outside the loop?
        }
    }
}

A: The values you store in your hashmap go out of scope at the end of each loop iteration, which is why Rust complains about lifetimes.
// A new `line` is created on each loop iteration.
for line in reader.lines.into_iter() {
    let line = line.unwrap();

    for caps in re.captures_iter(&line) {
        // This `Vec` stores slices of `line`.
        let groups: Vec<&str> = /* ... */;

        // Here you insert values into the hashmap that reference `line`.
        instructions.insert(groups[4], groups);
    }

    // `line` goes out of scope here, invalidating the stored references to it.
}

In order to avoid the error you see, you need to store the data in the HashMap such that it outlives each loop iteration. The simplest way to do this is to make it a HashMap<String, Vec<String>> and convert the &strs to Strings when storing them. That will copy the string data from line to a separate location on the heap, which will live as long as each stored string.
// A new `line` is created on each loop iteration.
for line in reader.lines.into_iter() {
    let line = line.unwrap();

    for caps in re.captures_iter(&line) {
        // This `Vec` stores owned copies of the data in `line`.
        let groups: Vec<String> = caps
            .iter()
            .map(|m| match m {
                Some(value) => value.as_str().to_string(),
                None => String::new(),
            })
            .collect();

        // All values inserted here are owned.
        instructions.insert(groups[4].clone(), groups);
    }

    // There are no outstanding references to `line`.
}

I recommend checking out The Rust Programming Language chapters on References and Borrowing and Validating References with Lifetimes to gain a better understanding of the error you encountered.


text:
Q: Problems with rails server I am just getting started with ruby on rails and heroku. I am following the getting started guid on herokus website but have ran into a problem. I have logged into heroku, created an app as such rails new myapp --database=postgresql and then created a controller rails generate controller welcome index in the app/views/welcome/index.html.erb I just created a header saying hello world. When I start a local server and go to it, I get could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"? and the output listed bellow in the terminal I followed another tutorial just for setting up rails without heroku and created the app like this rails new blog and then did the same as created a controller like in the heroku tutorial and everything worked fine, so I assume the problem is with rails new myapp --database=postgresql How would I fix this?
PG::ConnectionBad (could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
):
  activerecord (4.0.2) lib/active_record/connection_adapters/postgresql_adapter.rb:831:in `initialize'
  activerecord (4.0.2) lib/active_record/connection_adapters/postgresql_adapter.rb:831:in `new'
  activerecord (4.0.2) lib/active_record/connection_adapters/postgresql_adapter.rb:831:in `connect'
  activerecord (4.0.2) lib/active_record/connection_adapters/postgresql_adapter.rb:548:in `initialize'
  activerecord (4.0.2) lib/active_record/connection_adapters/postgresql_adapter.rb:41:in `new'
  activerecord (4.0.2) lib/active_record/connection_adapters/postgresql_adapter.rb:41:in `postgresql_connection'
  activerecord (4.0.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:440:in `new_connection'
  activerecord (4.0.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:450:in `checkout_new_connection'
  activerecord (4.0.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:421:in `acquire_connection'
  activerecord (4.0.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:356:in `block in checkout'
  /Users/mattmoss/.rbenv/versions/2.1.0/lib/ruby/2.1.0/monitor.rb:211:in `mon_synchronize'
  activerecord (4.0.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:355:in `checkout'
  activerecord (4.0.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:265:in `block in connection'
  /Users/mattmoss/.rbenv/versions/2.1.0/lib/ruby/2.1.0/monitor.rb:211:in `mon_synchronize'
  activerecord (4.0.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:264:in `connection'
  activerecord (4.0.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:546:in `retrieve_connection'
  activerecord (4.0.2) lib/active_record/connection_handling.rb:79:in `retrieve_connection'
  activerecord (4.0.2) lib/active_record/connection_handling.rb:53:in `connection'
  activerecord (4.0.2) lib/active_record/query_cache.rb:51:in `restore_query_cache_settings'
  activerecord (4.0.2) lib/active_record/query_cache.rb:43:in `rescue in call'
  activerecord (4.0.2) lib/active_record/query_cache.rb:32:in `call'
  activerecord (4.0.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:626:in `call'
  activerecord (4.0.2) lib/active_record/migration.rb:369:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.0.2) lib/active_support/callbacks.rb:373:in `_run__4242016335734095215__call__callbacks'
  activesupport (4.0.2) lib/active_support/callbacks.rb:80:in `run_callbacks'
  actionpack (4.0.2) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/reloader.rb:64:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.0.2) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.0.2) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.0.2) lib/active_support/tagged_logging.rb:67:in `block in tagged'
  activesupport (4.0.2) lib/active_support/tagged_logging.rb:25:in `tagged'
  activesupport (4.0.2) lib/active_support/tagged_logging.rb:67:in `tagged'
  railties (4.0.2) lib/rails/rack/logger.rb:20:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
  rack (1.5.2) lib/rack/runtime.rb:17:in `call'
  activesupport (4.0.2) lib/active_support/cache/strategy/local_cache.rb:83:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  actionpack (4.0.2) lib/action_dispatch/middleware/static.rb:64:in `call'
  rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
  railties (4.0.2) lib/rails/engine.rb:511:in `call'
  railties (4.0.2) lib/rails/application.rb:97:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  rack (1.5.2) lib/rack/content_length.rb:14:in `call'
  rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
  /Users/mattmoss/.rbenv/versions/2.1.0/lib/ruby/2.1.0/webrick/httpserver.rb:138:in `service'
  /Users/mattmoss/.rbenv/versions/2.1.0/lib/ruby/2.1.0/webrick/httpserver.rb:94:in `run'
  /Users/mattmoss/.rbenv/versions/2.1.0/lib/ruby/2.1.0/webrick/server.rb:295:in `block in start_thread'

  Rendered /Users/mattmoss/.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.0.2/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.5ms)
  Rendered /Users/mattmoss/.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.0.2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms)
  Rendered /Users/mattmoss/.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.0.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.0ms)
  Rendered /Users/mattmoss/.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.0.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (18.2ms)

Here is my database.yml
# PostgreSQL. Versions 8.2 and up are supported.
#
# Install the pg driver:
#   gem install pg
# On OS X with Homebrew:
#   gem install pg -- --with-pg-config=/usr/local/bin/pg_config
# On OS X with MacPorts:
#   gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config
# On Windows:
#   gem install pg
#       Choose the win32 build.
#       Install PostgreSQL and put its /bin directory on your path.
#
# Configure Using Gemfile
# gem 'pg'
#
development:
  adapter: postgresql
  encoding: unicode
  database: myapp_development
  pool: 5
  password:

  # Connect on a TCP socket. Omitted by default since the client uses a
  # domain socket that doesn't need configuration. Windows does not have
  # domain sockets, so uncomment these lines.
  #host: localhost

  # The TCP port the server listens on. Defaults to 5432.
  # If your server runs on a different port number, change accordingly.
  #port: 5432

  # Schema search path. The server defaults to $user,public
  #schema_search_path: myapp,sharedapp,public

  # Minimum log levels, in increasing order:
  #   debug5, debug4, debug3, debug2, debug1,
  #   log, notice, warning, error, fatal, and panic
  # Defaults to warning.
  #min_messages: notice

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: postgresql
  encoding: unicode
  database: myapp_test
  pool: 5
  password:

production:
  adapter: postgresql
  encoding: unicode
  database: myapp_production
  pool: 5
  password:

development:
  host: localhost

test:
  host: localhost

A: In your config/database.yml, try adding
host: localhost

in each of your development and testing environment or more specifically looking at your existing config/database.yml shown above:
development:
  adapter: postgresql
  encoding: unicode
  database: myapp_development
  pool: 5
  password:
  host: localhost

test:
  adapter: postgresql
  encoding: unicode
  database: myapp_test
  pool: 5
  password:
  host: localhost

Hope this helps

A: On most *nix servers "localhost" is handled through a Unix style socket.  If you use 127.0.0.1 instead it will use TCP/IP.  Try that or make sure your client and server are using the same socket address and that it is actually a usable *nix socket.
There is a configuration parameter in database.yml that lets you set the socket address, be certain that you have access to the directory as well.

A: I hear Heroku has made some changes to the db connection behaviour. For rails version >= 4.1 it does not overwrite your config/database.yml - it merges with it. First you need to visit https://postgres.heroku.com/databases and click on your database. You should look that parameter in the pic below

Use that variable for your production parameter like so
production:
  adapter: postgresql
  url: <%= ENV['HEROKU_POSTGRESQL_BLACK_URL'] %>

This is what worked for me after trying different things. I hope this helps someone.


text:
Q: C++ BigInteger and Assignment Operator Overloading I have to build a BigInteger class in C++. The BigInt has to be stored in an array with fixed size. I am now wondering, whether it is possible to overload the assignment operator to accept a number bigger than long long int on the right hand side (but internally storing the integers in an array).
Example:
BigInteger i = 1000000000000000010000000000000000010000000000000000100000000000;
and internally it might be stored like:
i.data = {10000000000000000,100000000000000000,10000000000000000,100000000000};
Is this possible? This is how far I've come:
#include "BigIntegerF.h"
using namespace std;

// Default Constructor
BigIntegerF::BigIntegerF() {
    data[0] = 0;
}

// Destructor
BigIntegerF::~BigIntegerF(){}

BigIntegerF& BigIntegerF::operator = (const BigIntegerF& bigInt)
{
    // don't know how i could implement it here
}

A: You can do this with user-defined literals:
BigInteger operator ""_bigInt(char const *str, std::size_t len) {
    // Create and return a BigInteger from the string representation
}

Then you can create a BigInteger as follows:
auto myBigInt = 1234567890_bigInt;

A: C++ has the operator "" syntax for exactly these cases, where you want to create a user-defined object out of a literal in code (see answer by Quentin).
If your compiler doesn't support the relatively new operator "" syntax (e.g. MS Visual Studio 2013 and older), you can use slightly less convenient syntax, which involves an initializer-list:
class BigInteger
{
public:
    ...

    BigInteger(std::initializer_list<unsigned long long> list)
    {
        std::copy(list.begin(), list.end(), data);
        size = list.size();
    }

private:
    ...
    unsigned long long data[999];
    size_t size;
};

Use it as follows:
BigInteger i{100000, 2358962, 2398572389, 2389562389};


text:
Q: magento community 1.7.0.2 product collection sort does not work I am having a problem with sort order in magento.
    $productPriceCollection = $products2->addAttributeToSort('mb_rank', 'DESC')->setPageSize("3")->addStoreFilter()->load();
    $priceOrderCollection = $productPriceCollection->setOrder('price', 'ASC')->load();

What I am trying to do here is getting the first 3 products which has the highest mb_rank and then sorting only that three by price ascending and loading that list as the final list that I use for the rest of the process.
But I am always getting the order as price Descending.
I have already tried
    $priceOrderCollection = $productPriceCollection->addAttributeToSort('price', 'ASC')->load();

No difference.
What am I doing wrong here?
Best

A: Sorry about the comments. I just realized that the attribute type is not important in your case.
The problem is that you are using ->load for your collection.
Once you load your collection you cannot modify the order or filters on it.
Try it like this.
$productPriceCollection = $products2->addAttributeToSort('mb_rank', 'DESC')
    ->setPageSize("3")
    ->addStoreFilter()
    ->addAttributeToSort('price', 'ASC')
    ->load();

A: I somehow found half of the solution, First of all if you use textfield, Magento will not sort it correctly, you need to use price as field type to sort your integer values correctly. Otherwise it will be counted as a string value.
Adding the second sort for the first three results is still not working in my case.


text:
Q: Bad Gateway with traefik Ingress I'm using minikube with traefik ingress to create a sticky sessions.
So i have done the deploy of traefik that user guide kubernetes provides me. https://docs.traefik.io/user-guide/kubernetes/
I deploy traefik using DaemonSet. Cause it's a small project and is my first time using kubernetes and docker.
This is my ingress yaml file
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: cp-pluggin
  annotations:
    kubernetes.io/ingress.class: traefik
spec:
  rules:
  - host: cppluggins.minikube
    http:
      paths:
      - path: /
        backend:
          serviceName: cp-pluggin
          servicePort: 80

My service yaml file
apiVersion: v1
kind: Service
metadata:
  name: cp-pluggin
  annotations:
    traefik.ingress.kubernetes.io/affinity: "true"
    traefik.ingress.kubernetes.io/session-cookie-name: "sticky"
spec:
  type: NodePort
  ports:
  - port: 80
    targetPort: 8080
    protocol: TCP
    name: http
  selector:
    app: cp-pluggin-app

Finally, my deployment yaml file
apiVersion: apps/v1
kind: Deployment
metadata:
  name: cp-pluggin-app
  labels:
    app: cp-pluggin-app

spec:
  replicas: 3
  selector:
    matchLabels:
      app: cp-pluggin-app
  template:
    metadata:
      labels:
        app: cp-pluggin-app
    spec:
      containers:
      - name: cp-pluggin-app
        image: essoca/ubuntu-tornado
        ports:
        - containerPort: 8080

I expected
Hello world from: [ipserver]
But i get a
bad gateway

A: I assume you are using Traefik 2.0, the latest version as of now. There are quite some changes in this version, i.e. the annotations are not used anymore. Besides that, I think the code that you posted is missing a big part of the required changes.
Also, it's not very useful to use a DaemonSet because you are using minikube and that's always one node. Using a Deployment will at least allow you to play with the scale up/down functionality of Kubernetes.
I wrote this article that might be useful for you Traefik 2 as Ingress Controller


text:
Q: Get a count of users in a specific OU and its sub OU's I'm looking for a PowerShell script that will get me:

*

*The name of the OU's

*The count of the number of AD users in each OU.

I have found this:
(Get-ADUser -Filter * -SearchBase "ou=Users,ou=A1,dc=contoso,dc=com").count

This does exactly what I want, but I would have to type in each OU name. The problem is that we have 100+ OU's.  The specific OU I'm wanting to run this in is contoso.com\cmsg\users  under the cmsg\users is where the 100+ OU's reside.

A: I propose you come at this from another angle. Each ad user contains information about its parent container. Since you are already returning all users. Lets use that to determine the counts. Caveat being that if you have user-less OU's they would not show in the results.
Get-ADUser -Filter * -Properties CN |
    Select-Object @{Label='ParentContainer';Expression={$_.Distinguishedname -replace "CN=$($_.cn),"}} |
    Group-Object -Property ParentContainer |
    Select-Object Name,Count

You can of course still use -SearchBase to narrow the scope of Get-ADUser.
If this is not what you wanted your next solution would require output from Get-ADOrganizationalUnit.
$ous = Get-ADOrganizationalUnit -Filter * -SearchBase "ou=Users,ou=CMSG,dc=contoso,dc=com" | Select-Object -ExpandProperty DistinguishedName
$ous | ForEach-Object{
    [psobject][ordered]@{
        OU = $_
        Count = (Get-ADUser -Filter * -SearchBase "$_").count
    }
}

A: Here is the PowerShell command to Get a count of users in a specific OU.
(Get-ADObject -Filter * -SearchBase "path of your OU").Count

A: I like this one - outputs exactly what original poster was after:
$root_ou = "ou=Users,ou=cmsg,dc=contoso,dc=com"
$User = get-aduser -filter * -SearchBase $ou -SearchScope Subtree | Select @{Name="OU";Expression={$_.distinguishedName -match "cn=.*?,OU=(?<OU>.*)" | Out-Null;$Matches.OU}}
$User | Group -Property OU | Select Name,Count

Output looks like this
Name                                                       Count
----                                                       -----
Office 1,ou=Users,ou=cmsg,dc=contoso,dc=com                1230
Office 2,ou=Users,ou=cmsg,dc=contoso,dc=com                390
Office 3,ou=Users,ou=cmsg,dc=contoso,dc=com                90
Office 4,ou=Users,ou=cmsg,dc=contoso,dc=com                10

To find the DistinguishedName of the root_ou you're after:
Get-ADOrganizationalUnit -Filter 'Name -like "*"' | Format-Table Name, DistinguishedName -A

A: If there are not many OU's a simple way is to select all in each OU and hit properties. This will bring up a total count for that OU. You can add each of them together after gathering counts.

A: in ADUC click View > Customize View > enable Description bar

A: Run in python - get-aduser will show you all users
(get-aduser -filter *).count will count those users for you. This is all users active or disabled.


text:
Q: Blazor input mask I'd like to know if it's possible to make a masked input with Blazor by inheriting InputBase, and preferably using Regex? If not possible with C# only then JavaScript is fine. I know Syncfusion has a paid component, but I'd prefer free stuff. Any GitHub repo or guidance/hint is just fine!

A: I ended up (based on Ali Borjian's advice) using the following code, I made a component by inheriting from InputBase:
@inject IJSRuntime JSRuntime
@inherits InputBase<string>
<input id="@guid"  @attributes="AdditionalAttributes" class="@CssClass" value="@CurrentValue" @oninput="EventCallback.Factory.CreateBinder<string>(this, __value => CurrentValueAsString = __value, CurrentValueAsString)" />
@code {
    Guid guid { get; set; }
    protected override void OnInitialized()
    {
        guid = Guid.NewGuid();
    }
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JSRuntime.InvokeVoidAsync("mask",guid.ToString(), AdditionalAttributes["data-mask"].ToString());
        }
    }
    protected override bool TryParseValueFromString(string value, out string result, out string validationErrorMessage)
    {
        result = value;
        validationErrorMessage = null;
        return true;
    }
}

Usage:
<EditForm Model="user" OnValidSubmit="Submit">

            First Name:
            <InputText @bind-Value="user.Name" class="form-control" placeholder="First Name" />

            French Phone no:
            <InputMask @bind-Value="user.Telephone" class="form-control" data-mask="00.00.00.00.00" placeholder="Phone No" />

        <button type="submit" class="btn btn-primary">OK</button>
        <ValidationSummary />
        <DataAnnotationsValidator />
    </EditForm>

@code{

    private User user = new User();

    private void Submit()
    {
    }
}

And in JS:
window.mask = (id,mask) => {
        var customMask = IMask(
            document.getElementById(id), {
            mask: mask
        });
    };

And our class (with a Data Annotations RegEx):
   public class User
    {
        [Required]
        public string Name { get; set; }
        [Required]
        [RegularExpression(@"^[0][1-9]([.][0-9][0-9]){4}", ErrorMessage="Incorrect phone number !")]
        public string Telephone { get; set; }

    }

A: You can use different javascript mask plugins, but I suggest imask (https://github.com/uNmAnNeR/imaskjs)

Now in blazor follow these steps :
1: In _Host.cshtml add a reference to the imask library
< script src="https://unpkg.com/imask">< /script >

2: Add a javascript file to handle your masks, and add its reference to _Host.cshtml
< script src="~/script/customMasks.js">< /script >

3: In customMasks.js you can have different masks, e.g a mask for phone number :
    window.masks = () => {

    var phoneMask = IMask(
        document.getElementById('phone-mask'), {
        mask: '+{7}(000)000-00-00'
    });

    ... (other masks)

   };

4: Now you need to call the window.masks function in each page that you want to mask the inputs,

 protected override async Task OnAfterRenderAsync(bool firstRender)
 {
  if (firstRender)
   {
     await JSRuntime.InvokeVoidAsync("mask");
   }
}

5: everything is ready, now you can mask your inputs like this :
 <input type="text" id="phone-mask" />


text:
Q: How to colour git branch name in zsh prompt I have the following set in my .zshrc
autoload -Uz add-zsh-hook vcs_info
setopt prompt_subst
add-zsh-hook precmd vcs_info

zstyle ':vcs_info:git:*' formats '%b'

and this in my
custom zsh theme :
vcs_info_wrapper() {
  vcs_info
  if [[ "${vcs_info_msg_0_}" == "master" ]]; then
    echo "%{$FG[196]%}"
  else
    echo "%{$fg[cyan]%}"
  fi
}

PROMPT=$'%B%{$FG[039]%}%n%b%{$fg_bold[white]%}@%m%{$FG[220]%} %{\x1b[3m%}%5~ %{$reset_color%}$(git_prompt_info)%{$reset_color%}%{\x1b[0m%} %(?.%{$fg[white]%}.%{$fg_bold[red]%}[%?])» %{$FG[010]%}  ||$(vcs_info_wrapper)${vcs_info_msg_0_}|| '
I have both $(vcs_info_wrapper)${vcs_info_msg_0_} and $(git_prompt_info) to test the colour output. For some reason the former always works and has the correct colour, but the latter doesn't and once the colour changes it never resets. I've basically tried everything at this point. Any ideas are welcome
EDIT:
Thanks @Gairfowl to I have most of it working now with:
function my_precmd {
  vcs_info
  local user='%B%F{#00ACE6}%n%f%b'

  local host='%B%F{white}@%m%f%b'
  local path='%F{#FFD700}%4~%f'
  local rcAndArrow='%(?.%F{white}.%B%F{red}[%?])»%f%b'

  local git2color='cyan'
  local git2=""

  [[ "${vcs_info_msg_0_}" == "master" || "${vcs_info_msg_0_}" == "main" ]] && git2color='196'

  if [[  "${vcs_info_msg_0_}" != "" ]]
    then
      local git2="%B%F{${git2color}}($(git_prompt_info))%f%b "
  fi

  psvar[1]="${user}${host} ${path} ${git2}${rcAndArrow} "

However I don't get any git information from $(git_prompt_info) If I combine it with path (like this local path="%F{#FFD700}%4~%f $(git_prompt_info)") that seems to work.

A: It's often much easier to read and debug a precmd function than to
put everything in the PROMPT variable. Try building your prompt like the function below; you can comment out pieces and isolate the parts you're working on:
autoload -Uz add-zsh-hook vcs_info
setopt prompt_subst
add-zsh-hook precmd my_precmd

zstyle ':vcs_info:git:*' formats '%b'

function my_precmd {
  local theUser='%B%F{39}%n%f%b'
  local theHost='%B%F{white}@%m%f%b'
  local git1="%F{220}~%f$(git_prompt_info)"
  local rcAndArrow='%(?.%F{white}.%B%F{red}[%?])»%f%b'

  vcs_info
  local git2color='cyan'
  [[ "${vcs_info_msg_0_}" == "master" ]] && git2color='196'
  local git2="||%F{${git2color}}${vcs_info_msg_0_}%f||"

  psvar[1]="${theUser}${theHost} ${git1} ${rcAndArrow} "
  psvar[2]="${git2}"
}

PROMPT='${psvar[1]}'
RPROMPT='${psvar[2]}'


text:
Q: What is a mathematic rigorous definition of "blue noise"? Let $d\in\mathbb N$, $I$ be a finite nonempty set, $(x_i)_{i\in I}\subseteq[0,1)^d$, $(w_i)_{i\in I}\subseteq[0,\infty)$ with $\sum_{i\in I}w_i=1$ and $$\sigma:=\sum_{i\in I}w_i\delta_{x_i}.$$
I really got trouble to understand what's meant by the property of the point pattern $(x_i)_{i\in I}$ to "admit blue noise characteristic". I think the term "blue noise" is used quite vaguely in the literature. One think I've often read is that $(x_i)_{i\in I}$ has "blue noise charateristic" if the corresponding power spectrum is near $0$ for low frequencies. This should mean that the absolute value of the Fourier transform $$\hat\sigma(x)=\sum_{i\in I}w_ie^{-{\rm i}2\pi\langle x,\:x_i\rangle}\;\;\;\text{for }x\in\mathbb R^d$$ is small (or near $0$) whenever $\left\|x\right\|$ is small.
There are also papers (like Blue Noise through Optimal Transport and Blue Moise Wasserstein Sampling) which seem to relate the blue noise property to a suitable minimization of a Wasserstein distance, but I actually don't understand why and in which sense that minimizer has blue noise characteristics.
What I actually would like to investigate is whether a specific Markov chain (e.g. generated by the Metropolis-Hastings algorithm) has blue noise characteristics.


text:
Q: IONIC 2: Searhing with json parsing I have two pages, search page which contains some filter searches like marital status, age etc.. and those filters are as combobox, firstly i want to display each option in combo box to fetch from json. and i do have another page called matches with a card containing details of a person. SO I want to store some peoples details as json. And when I search with particular filters I need to display the results in matches as card by fetching from json. Please do help.
search page ts and html:

import { Component } from '@angular/core';
import { NavController, AlertController, LoadingController, Loading, IonicPage } from 'ionic-angular';
import { ObsAuthService } from '../../services/obs_auth.services';
import { MatriregPage } from '../matrireg/matrireg';
import { MatrimatPage } from '../matrimat/matrimat';

@Component({
    selector: 'page-matrisear',
    templateUrl: 'matrisear.html',

    providers: [ObsAuthService]
})
export class MatrisearPage{

    maritalfilter=[
        {
            "marital":"Single"

            },
            {
                "marital":"Divorced"
            },
            {
                "marital":"Widowed"
            }
    ];

    religionfilter=[
        {
            "religion":"Any"
        },
        {
            "religion":"Hindu"
        },
        {
            "religion":"Muslim"
        },
        {
            "religion":"Christian"
        }
    ];

    selectedMarital:string;
    selectedReligion:string;
    constructor(private nav: NavController, private auth: ObsAuthService,
        private alertCtrl: AlertController, private loadingCtrl: LoadingController) {
        }

    selectChange(e) {
        console.log(e);
    }
    public create(){
        this.nav.push(MatriregPage);
    }
    public search(){
        this.nav.push(MatrimatPage);
    }
}
<ion-header>
    <ion-navbar>
        <ion-title>Search</ion-title>
    </ion-navbar>

</ion-header>
<ion-content>
    <ion-label class="link" (click)="create()">Create a Profile</ion-label>

    <ion-row>
        <ion-col>
            <ion-label>Age:</ion-label>
        </ion-col>
        <ion-col>
            <ion-select [(ngModel)]="selectedAge" interface="popover" placeholder="Select">
                <ion-option *ngFor="let ageObj of agefilter" [value]="ageObj">{{ageObj.age}}</ion-option>
            </ion-select>
        </ion-col>
        <ion-col>
            <ion-label>to</ion-label>
        </ion-col>
        <ion-col>
            <ion-select [(ngModel)]="selectedAge" interface="popover" placeholder="Select">
                <ion-option *ngFor="let ageObj of agefilter" [value]="ageObj">{{ageObj.age}}</ion-option>
            </ion-select>
        </ion-col>
    </ion-row>
    <ion-row>
        <ion-col>
            <ion-label>Height:</ion-label>
        </ion-col>
        <ion-col>
            <ion-select interface="popover" placeholder="Select">
                <ion-option value="nes">4ft 8in</ion-option>
                <ion-option value="n64">4ft 9in</ion-option>
                <ion-option value="ps">5ft</ion-option>
                <ion-option value="genesis">5ft 1in</ion-option>
                <ion-option value="saturn">5ft 2in</ion-option>

            </ion-select>
        </ion-col>
        <ion-col>
            <ion-label>to</ion-label>
        </ion-col>
        <ion-col>
            <ion-select interface="popover" placeholder="Select">
                <ion-option value="nes">4ft 8in</ion-option>
                <ion-option value="n64">4ft 9in</ion-option>
                <ion-option value="ps">5ft</ion-option>
                <ion-option value="genesis">5ft 1in</ion-option>
                <ion-option value="saturn">5ft 2in</ion-option>

            </ion-select>
        </ion-col>
    </ion-row>
    <ion-row>
        <ion-col>
            <ion-label>Marital Status:</ion-label>
        </ion-col>
        <ion-col>
            <ion-select [(ngModel)]="selectedMarital" interface="popover" placeholder="Select">
                <ion-option *ngFor="let maritalObj of maritalfilter" [value]="maritalObj">{{maritalObj.marital}}</ion-option>

            </ion-select>
        </ion-col>
        <ion-col>
            <ion-label>Religion</ion-label>
        </ion-col>
        <ion-col>
            <ion-select [(ngModel)]="selectedReligion" interface="popover" placeholder="Select">
                <ion-option *ngFor="let religionObj of religionfilter" [value]="religionObj">{{religionObj.religion}}</ion-option>

            </ion-select>
        </ion-col>
    </ion-row>
    <ion-row>
        <ion-col>
            <ion-label>Mother Toungue</ion-label>
        </ion-col>
        <ion-col>
            <ion-select interface="popover" placeholder="Select">
                <ion-option value="ns">Any</ion-option>
                <ion-option value="nes">Hindi</ion-option>
                <ion-option value="n64">Tamil</ion-option>
                <ion-option value="ps">Malayalam</ion-option>
                <ion-option value="genesis">English</ion-option>
            </ion-select>
        </ion-col>
        <ion-col>
            <ion-label>Country</ion-label>
        </ion-col>
        <ion-col>
            <ion-select interface="popover" placeholder="Select">
                <ion-option value="ns">Any</ion-option>
                <ion-option value="nes">India</ion-option>
                <ion-option value="n64">USA</ion-option>
                <ion-option value="ps">UAE</ion-option>
                <ion-option value="genesis">France</ion-option>
            </ion-select>
        </ion-col>
    </ion-row>
    <ion-row>
        <ion-col>
            <ion-label>State</ion-label>
        </ion-col>
        <ion-col>
            <ion-select interface="popover" placeholder="Select">
                <ion-option value="ns">Any</ion-option>
                <ion-option value="nes">Kerala</ion-option>
                <ion-option value="n64">TamilNadu</ion-option>
                <ion-option value="ps">Washington</ion-option>
                <ion-option value="genesis">Paris</ion-option>
            </ion-select>
        </ion-col>

        <ion-col>
            <ion-label>City/District</ion-label>
        </ion-col>
        <ion-col>
            <ion-select interface="popover" placeholder="Select">
                <ion-option value="ns">Any</ion-option>
                <ion-option value="nes">Thrissur</ion-option>
                <ion-option value="n64">Trivandrum</ion-option>
                <ion-option value="ps">North Washington</ion-option>
                <ion-option value="genesis">Georgia</ion-option>
            </ion-select>
        </ion-col>
    </ion-row>
    <ion-row>
        <ion-col>
            <ion-label>Education</ion-label>
        </ion-col>
        <ion-col>
            <ion-select interface="popover" placeholder="Select">
                <ion-option value="ns">Any</ion-option>
                <ion-option value="nes">UG</ion-option>
                <ion-option value="n64">PG</ion-option>
                <ion-option value="ps">Ph.D.</ion-option>
            </ion-select>
        </ion-col>
    </ion-row>

    <ion-row>
        <button ion-button (click)="search()" color="primary" block>Search</button>
    </ion-row>
</ion-content>

matches page html and ts:

import { Component } from '@angular/core';
import { NavController, AlertController, LoadingController, Loading, IonicPage } from 'ionic-angular';
import { ObsAuthService } from '../../services/obs_auth.services';
import { MatrisubPage } from '../matrisub/matrisub';
import { MatrirepPage } from '../matrirep/matrirep';

@Component({
    selector: 'page-matrimat',
    templateUrl: 'matrimat.html',

    providers: [ObsAuthService]
})
export class MatrimatPage{

    constructor(private nav: NavController, private auth: ObsAuthService,
        private alertCtrl: AlertController, private loadingCtrl: LoadingController) {
        }

    selectChange(e) {
        console.log(e);
    }

    goback() {
             this.nav.pop();
    }

    public report(){
        this.nav.push(MatrirepPage);
    }
}
<ion-header>
    <ion-navbar>
        <ion-title>Matches</ion-title>
    </ion-navbar>
</ion-header>

<ion-content>
    <ion-card>
        <ion-card-content>
            <ion-label>Name:</ion-label>
            <ion-row>
                <ion-col col-2>
                    <img src="assets/images/users.png" />
                </ion-col>
                <ion-col>
                    <ion-row>
                        <ion-label>Age:</ion-label>
                    </ion-row>
                    <ion-row>
                        <ion-label>Religion:</ion-label>
                    </ion-row>
                    <ion-row>
                        <ion-label>Marital Status:</ion-label>
                    </ion-row>
                    <ion-row>
                        <ion-label>Location:</ion-label>
                    </ion-row>
                    <ion-row>
                        <ion-label>Education:</ion-label>
                    </ion-row>
                    <ion-row>
                        <ion-label>Profession:</ion-label>
                    </ion-row>
                    <ion-row>
                        <ion-label>Annual Income:</ion-label>
                    </ion-row>
                </ion-col>
                <ion-col>
                    <ion-label item-end>Height:</ion-label>
                </ion-col>
            </ion-row>
            <ion-row>
                <ion-col>
                    <button ion-button full color="secondary" block>View Profile</button>
                </ion-col>
                <ion-col>
                    <button ion-button (click)="report()" full color="primary" block>Report</button>
                </ion-col>
            </ion-row>
        </ion-card-content>
    </ion-card>
</ion-content>


text:
Q: Uncaught Syntax Error. Unexpexcted end of input I have this javascript file that is calling a php file to return a JSON string. Chrome dev tools is throwing the error at line 10 in the javascript code. I know the error relates to a missing bracket but for the life of my and 3 other people who have looked at it the syntax is correct.
var request = new XMLHttpRequest();
var listings = [];
var json;
var url = "getListing.php";
request.open("GET", url, true);
request.send();
request.onreadystatechange = function(e)
{
if(request.readyState == 4){
    json = JSON.parse(request.responseText);

    for(var x = 0; x < json.length; x++){
        var list = new listingInfo();
        list.category = json[x].category;
        list.date = json[x].dateListed;
        list.description = json[x].description;
        list.id = json[x].listingID;
        list.title = json[x].title;
        list.userID = json[x].userID;
        listings.push(list);
    }
}
console.log(listings);
}

here is the php file
<?php
session_start();
$con = mysql_connect("localhost", "listAdmin", "hermes");
if(!$con)
{
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("GregsList", $con)
    or die("Unable to select database:" . mysql_error());

$result = mysql_query("SELECT * FROM Listings WHERE userID = '$_SESSION[userID]' ORDER BY dateListed DESC");

#converts to json
$rows = array();
while($r = mysql_fetch_assoc($result))
{
        $rows[] = $r;
}

#If you want to see if correct json is printing use ---> print json_encode($rows);

return json_encode($rows);
?>

A: request.readyState == 4 is not enough you should add request.status== 200
In your php script replace return json_encode($rows); with print json_encode($rows);


text:
Q: Verify the following statement, $ \{\{x\}, \{x,y\}\} \in\ A \implies \{x,y\} \in\bigcup A $? My attempt at solving it:

Let $ A = \{a,b,c,d\} $
where: $ a = \{x\} , b = \{x,y\} , c = \{x,y,z\} $ and $ d = \{\{x\}, \{x,y\}\} $
Then, $ \bigcup A  =a \cup\ b \cup\ c \cup\ d = \{x,y,z, \{x\},\{x,y\}\} $

I feel like this is correct, however I feel like my solution is kind of "brute forced" is there a more elegant way to solve this?

A: You are incorrectly assuming that $A$ is of a particular form. What if we just have $A=\{\{\{x\},\{x,y\}\}\}$? Then you certainly can't write $A=\{a,b,c,d\}$ as you do.
You can do it like this:
$\bigcup A = \bigcup_{a\in A} a=\{b\mid\text{there exists }a\in A\text{ such that }b\in a\}$.
And $\{x,y\}\in\{\{x\},\{x,y\}\}\in A$ therefore $\{x,y\}\in\bigcup A$.


text:
Q: pdf of combined models In a question, I have 5 systems. At a given time x, the probability that they're working is based on an exponential distribution. The combination of all systems will work if any single system is working

*

*Systems fail independently

How can I determine the pdf of the system reliability? (ie. the lifetime of the system)

My current process
The exponential function: $\lambda e^{-\lambda x}$
Therefore, the probability of a system failing is $1-\lambda e^{-\lambda x}$
Therefore, the probability of all systems failing at time x is $\prod\limits_{i=1}^{5}(1-\lambda_i e^{-\lambda_i x})$
So all systems working would be $p = 1- \prod\limits_{i=1}^{5}(1-\lambda_i e^{-\lambda_i x})$
Very unclear to me

A: Call $T_i$ as the lifetime of system $i$; then, your total system lifetime, $T=\max(T_1..T_5)$. You'll first write $F_T(t)=P(T\leq t)=\prod_{i=1}^5 P(T_i\leq t)$, and differentiate wrt $t$.
Your probability of system failing expression is wrong. You seem to confuse probability with density. P(A system fails before time $t$) = $P(T_i \leq t)=\int_0^{t}{\lambda_i e^{-\lambda_i x}dx}=1-e^{-\lambda_i t}$.


text:
Q: How to check, how often have dynamically created buttons been clicked, individually and in total? I created a loop with buttons in it. I also created an eventListener that keeps a count for every button. I want something to happen when all buttons have been presses at least 3 times, so I created an if statement that checks if the count is 3 and adds 1 to another count, but the other count stays on 1 even if multiple buttons have been pressed 3 times.

for (let i = 0; i < 7; i++) {
  let btn = document.createElement('button');

  btn.classList.add('buttons');
  btn.id = 'button' + i;

  document.getElementById('box').appendChild(btn);

  let count = 0;
  let count2 = 0;

  btn.addEventListener('click', () => {
    count++;
    console.log(count);

    if (count === 3) {
      console.log('3');

      count2++;
      console.log(count2);
    } else {

      console.log('not 3');
    }
  });
}
#box button { min-width: 20px; min-height: 20px; }
.as-console-wrapper { max-height: 87%!important; }
body { margin: 0; }

So the count variable works fine, and when 1 button has been clicked 3 times the count2 variable changes to 1, but it stays on 1 and I can't seem to find out why. At the end count2 should be 7, because there are 7 buttons.

A: as Vladimir implied in the comments its a scoping problem.
The variable count is only declared inside the event listener, so later on when you press different button your code does count++ for a different count variable.
To solve this declare var count instead of let count - that will make it global.
Or declare the count variable before the for loop.
BTW: make sure to stop updating count as it gets to 3, since it wouldn't update count2 if it gets to 4 or above

A: In addition to all the comments which already did point to the OP's problem I suggest a different approach based on storing/updating individual button-counts within a Map-instance.
With introducing event-delegation on top one would get rid of multiple on the fly (for each dynamically created button) applied event handlers which forces the approach to deal with different counter scopes (handler scope and the for block scope).
There will be exactly a single handler subscribed once to a single parent-node's 'click'-event. This handler keeps track of and handles the various click-count states by looking up a buttons individual click-count.

function createButton(id) {
  let elmNode = document.createElement('button');

  elmNode.classList.add('buttons');
  elmNode.id = `button${ id }`;

  return elmNode;
}
function main() {

  // keeps track of and handles the various click count states.
  function handleButtonClick({ target }) {
    const btnNode = target.closest('button');

    // update a single buttons click count total.
    const buttonClickTotal = clickCountStorage.get(btnNode) + 1;
    clickCountStorage.set(btnNode, buttonClickTotal);

    const clickCountList =  Array
      .from(
        clickCountStorage.values()
      );
    // calculate click count total of all buttons.
    const allButtonsClickTotal = clickCountList
      .reduce((total, count) => total + count, 0);

    // check whether the OP's each button minimum 3 times click applies.
    const isEveryButtonHasBeenClickedAtLeastThreeTimes = clickCountList
      .every(count => count >= 3);

    console.log({
      buttonClickTotal,
      allButtonsClickTotal,
      isEveryButtonHasBeenClickedAtLeastThreeTimes,
    });
  }
  const clickCountStorage = new Map;

  const root = document.querySelector('#box');
  // make use of event delegation ...
  // - a single eventhandler subscribed once to
  //   a single parent node's 'click' event.
  root.addEventListener('click', handleButtonClick)

  for (let elmNode, i = 0; i < 7; i++) {
    elmNode = createButton(i);

    // establish a new button reference related click count.
    clickCountStorage.set(elmNode, 0);

    root.appendChild(elmNode);
  }
}
main();
#box button { min-width: 20px; min-height: 20px; }
.as-console-wrapper { max-height: 87%!important; }
body { margin: 0; }


text: Q: Find and replace in Eclipse Oxygen Editing a C file in eclipse. I hit ctrl + f to search for a string in the file. A dialog box pops up and i type my search in there. Then I go back to editing the file. The next time I hit ctrl + f to do a different search, I lose focus on the editor window and i don't have focus in the search window. I have to actually click on the find and replace window to be able to type in what I want to search for now. If I close the find and replace window then ctrl + f works normally again, but I don't think that is really acceptable. Surely there is a way to navigate back to the find window without having to click on it?


text:
Q: Intel CPU microcode update fails everytime I have a few XenServer VMs all running CentOS 5.5. Some are 32-bit and others are 64-bit.
Every time they boot, the following message appears:
Applying Intel CPU microcode update: [FAILED]
Does anyone know why this is happening and how I can fix it?

A: This probably happens because the OS is running inside a VM and therefore can't apply CPU microcode updates. As for how to fix it, I have no idea. Does this message prevent any meaningful work or does it merely disturb you? In the latter case you can safely ignore it.

A: If you want to prevent the Intel CPU microcode from starting at boot, you can disable it as follows: (Run the command as root)
# chkconfig microcode_ctl off
This will prevent the microcode service from trying to apply the update at boot, since it will fail on your VMs every time.

A: On a CentOS 6 installation, microcode_ctl doesn't seem to be invoked via the /etc/init.d (chkconfig) mechanism any more.  I achieved the same effect by uninstalling the package:
# rpm --erase microcode_ctl

(I know the original question was centOS 5.5, but a search brought me here...)


text:
Q: com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized I have the following code:
package com.example.bluelightlite.modules

import android.content.Context
import android.os.AsyncTask
import com.example.bluelightlite.builders.ServiceBuilder
import com.google.api.client.auth.oauth2.Credential
import com.google.api.client.http.javanet.NetHttpTransport
import com.google.api.client.util.DateTime
import com.google.api.services.calendar.Calendar
import com.google.api.services.calendar.model.Event
import com.google.api.services.calendar.model.Events

class GoogleCalendarsServiceModule constructor(context: Context): AsyncTask<Void, Void, List<Event>>() {

    private val googleCredential: Credential
    private val httpTransport: NetHttpTransport = NetHttpTransport()
    private val googleCredentialsUtilityModule = GoogleCredentialsUtilityModule(context)

    init {
        this.googleCredential = this.googleCredentialsUtilityModule.execute(this.httpTransport).get()
    }

    private var googleCalendarService: Calendar =
        ServiceBuilder().buildGoogleCalendarService(this.googleCredential, this.httpTransport)

    /**
     * gets all calendar events
     * @return Events list
     */
    private fun getEvents(): List<Event> {
        val now = DateTime(System.currentTimeMillis())
        val events: Events = this.googleCalendarService
            .events()
            .list("Marc Freeman")
            .setMaxResults(10)
            .setOrderBy("startTime")
            .execute()

        return events.items;
    }

    override fun doInBackground(vararg params: Void?): List<Event> {
        return this.getEvents()
    }
}

The application asks the user to accept permissions to access calendar, I have an auth token, however when I call:
GoogleCalendarsServiceModule.execute() // because it needs to run on another thread
I get this error:
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process: com.example.bluelightlite, PID: 11410
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$4.done(AsyncTask.java:399)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
        at java.util.concurrent.FutureTask.run(FutureTask.java:271)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)
     Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
    {
      "code" : 401,
      "errors" : [ {
        "domain" : "global",
        "location" : "Authorization",
        "locationType" : "header",
        "message" : "Invalid Credentials",
        "reason" : "authError"
      } ],
      "message" : "Invalid Credentials"
    }
        at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
        at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
        at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1065)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
        at com.example.bluelightlite.modules.GoogleCalendarsServiceModule.getEvents(GoogleCalendarsServiceModule.kt:38)
        at com.example.bluelightlite.modules.GoogleCalendarsServiceModule.doInBackground(GoogleCalendarsServiceModule.kt:44)
        at com.example.bluelightlite.modules.GoogleCalendarsServiceModule.doInBackground(GoogleCalendarsServiceModule.kt:14)
        at android.os.AsyncTask$3.call(AsyncTask.java:378)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
            ... 4 more

How do I pass my access token into my request? I can't seem to find an API that allows me to do this when I call the GoogleCalendarService, Absolutely dispising Android by the way guys.

A: So I have no idea what happened but I cleaned out my project and the code worked... It goes as follows:
class GoogleCalendarsServiceModule constructor(context: Context) {

    private val googleCredential: Credential
    private val httpTransport: NetHttpTransport = NetHttpTransport()
    private val googleCredentialsUtilityModule = GoogleCredentialsUtilityModule(context)
    private var googleCalendarService: Calendar

    init {
        this.googleCredential = this.googleCredentialsUtilityModule.execute(this.httpTransport).get()
        this.googleCalendarService = ServiceBuilder().buildGoogleCalendarService(this.googleCredential, this.httpTransport)
    }

    /**
     * gets all calendar events
     * @see - https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-i-o.html
     * @return Events list
     */
    suspend fun getCalendarEvents(): List<Event> = withContext(Dispatchers.IO) {
        val now = DateTime(System.currentTimeMillis())
        val events: Calendar.Events? = googleCalendarService.events()

        val allEvents = events!!.list("primary")
        .setMaxResults(10)
            .setTimeMin(now)
            .setOrderBy("startTime")
            .setSingleEvents(true)
            .execute()

        allEvents.items
    }

    suspend fun getCalendarEventsForRoom(roomName: String): List<Event> = withContext(Dispatchers.IO) {
        val now = DateTime(System.currentTimeMillis())
        val events: Calendar.Events? = googleCalendarService.events()

        val allEventsForRoom = events!!.list("primary")
            .setMaxResults(10)
            .setTimeMin(now)
            .setOrderBy("startTime")
            .setSingleEvents(true)
            .execute()

        allEventsForRoom.items.distinctBy { x -> x.location == roomName }
    }
}

Credentials Module that sets up and maintains Google 0Auth Credentials. Including setting up the tokens folder if missing.
class GoogleCredentialsUtilityModule constructor(private val context: Context): AsyncTask<NetHttpTransport, Void, Credential>() {

    /**
     * Starts getting credentials on a different thread by implementing
     * AsyncTask<>()
     * @param params: a list of parameters
     * @return none
     */
    override fun doInBackground(vararg params: NetHttpTransport): Credential {
        return this.getCredentials(params[0])
    }

    /**
     * Creates an authorized Credential object.
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws java.io.IOException If the credentials.json file cannot be found.
     */
    private fun getCredentials(HTTP_TRANSPORT: NetHttpTransport): Credential {

        val inputStream: InputStream = getCredentialsAsInputStream()
        val clientSecrets: GoogleClientSecrets = GoogleClientSecrets.load(JSON_FACTORY, InputStreamReader(inputStream))

        createTokenFolderIfMissing()

        val authorisationFlow: GoogleAuthorizationCodeFlow = getAuthorisationFlow(HTTP_TRANSPORT, clientSecrets)
        val localServerReceiver: LocalServerReceiver = LocalServerReceiver.Builder().setPort(43783).build()

        val ab: AuthorizationCodeInstalledApp =
            object : AuthorizationCodeInstalledApp(authorisationFlow, localServerReceiver) {
                @Throws(IOException::class)
                override fun onAuthorization(authorizationUrl: AuthorizationCodeRequestUrl) {
                    val url = authorizationUrl.build()
                    val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                    context.startActivity(browserIntent)
                }
            }

        return ab.authorize("user")
    }

    /**
     * Gets the /credentials.json file
     * @return InputStream
     */
    private fun getCredentialsAsInputStream(): InputStream {
        return this.javaClass.getResourceAsStream(CREDENTIALS_FILE_PATH)
            ?: throw FileNotFoundException("Resource Not found: $CREDENTIALS_FILE_PATH")
    }

    /**
     * Creates the Tokens Folder for Google Authentication
     * Uses the current context for the folder path from
     * Context.getExternalFilesDir()
     */
    private fun createTokenFolderIfMissing() {
        val tokenFolder = getTokenFolder()
        if (!tokenFolder.exists()) {
            tokenFolder.mkdir()
        }
    }

    /**
     * gets External storage directory from the
     * current context
     * @return File
     */
    private fun getTokenFolder(): File {
        return File(this.context.getExternalFilesDir("")?.absolutePath + TOKENS_DIRECTORY_PATH)
    }

    /**
     * Gets authorisation flow so that the application can authenticate into Google Calendars
     * @param HTTP_TRANSPORT allows the app to use HTTP connections
     * @param clientSecrets secrets for authentication into Google
     * @return GoogleAuthorizationCodeFlow
     */
    private fun getAuthorisationFlow(HTTP_TRANSPORT: NetHttpTransport, clientSecrets: GoogleClientSecrets): GoogleAuthorizationCodeFlow {
        return GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(FileDataStoreFactory(getTokenFolder()))
            .setAccessType("offline")
            .build()
    }
}

And finally, calling the service using a co-routine:
class MainActivity : AppCompatActivity(), CoroutineScope, IMeetingRoomDelegate {
    private var job: Job = Job()
    override val coroutineContext: CoroutineContext
    get() = Dispatchers.Main + job

    @Inject
    lateinit var permissionsUtilityModule: PermissionsUtilityModule

    private lateinit var googleCalendarsServiceModule: GoogleCalendarsServiceModule
    private lateinit var meetingRooms: MeetingRooms

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DaggerUtilityModuleComponent.create().inject(this)

        this.permissionsUtilityModule.checkUserPermissions(this)
        this.googleCalendarsServiceModule = GoogleCalendarsServiceModule(this);

        launch {
            val events: List<Event> = googleCalendarsServiceModule.getCalendarEvents()
            meetingRooms = setMeetingRooms(events)
            setMeetingRoomFragments(meetingRooms)
        }

        setContentView(R.layout.activity_main)
    }

    override fun onDestroy() {
        super.onDestroy()
        this.job.cancel()
    }

    override fun onMeetingRoomFragmentClicked(fragment: MeetingRoomFragment, meetingRoom: MeetingRoom) {
        val intent = Intent(this, ViewMeetingRoomDataActivity::class.java)
        intent.putExtra("meetingRoomData", meetingRoom)

        startActivity(intent)
    }

    private fun setMeetingRooms(events: List<Event>): MeetingRooms {
        val mappedEvents: List<MeetingEvent> = mapMeetingEvents(events)
        val meetingEvents = MeetingEvents(mappedEvents)

        return MeetingRoomFactory().getRooms(meetingEvents)
    }

    private fun setMeetingRoomFragments(mappedMeetingRooms: MeetingRooms) {
        for(meetingRoom: MeetingRoom in mappedMeetingRooms.getMeetingRooms()) {
            val bundle = Bundle()
            val meetingRoomFragment = MeetingRoomFragment()

            bundle.putParcelable("meetingRoomData", meetingRoom)
            meetingRoomFragment.arguments = bundle

            supportFragmentManager.beginTransaction()
                .add(R.id.root_container, meetingRoomFragment)
                .commitAllowingStateLoss()
        }
    }
}

Thought I'd post in case anyone requires help with the whole 0Auth rigmarole.


text:
Q: Is it bad design to internally call API endpoints from within the API instance? For context, I am running a REST API built with Node.js. Because of callbacks and some complex DB calls, I have a chain of functions that are async but also unique, so it's tough to reduce redundancy. I came up with the idea to call my own endpoints (different endpoints) from within the code itself so I can reduce redundancy. Is this bad practice?
For instance, I would have:
app.get("/puppies/:id"...)  // Simple get by ID endpoint

app.post("/puppies"...)  // Simple puppy update, but checks an attribute of puppy first by getting by ID

In the post endpoint, it would be nice to simply call the "get" endpoint within the post code, but it feels dirty. Thoughts?

A: Yes its bad(tm).
The extra overhead of making the http call although needless probably wont be much of a factor.
I think The real dangers are:

*

*The accidental introduction of endless loops. ie Post calls get and Get calls Post or similar scenarios.

*Unindented caching effects

*http server issues, maximum requests on the server etc

*Threading issues, when you make the call and wait for it to be processed async
Basically a lot of bits and bobs that don't  break your code, but definitely introduce issues you would rather not have to worry about.
In any case your code should be structured in such a way that it is easy to make the get call, or part of it directly. without hitting the http layer. It sounds like you haven't put your code into a business layer

A: *

*There is little use of actually doing an HTTP request.
When the underlying application processes the GET request from your example, it probably calls the business layer which does some input checking, and then calls the data access layer which retrieves the puppy.
In a similar way, the POST request could, instead of doing an additional GET, simply ask the business layer to update the puppy; the business layer, in turn, will start by calling the data access layer method which retrieves the corresponding puppy.

*Doing an extra HTTP request will, however, have several drawbacks.

*

*There would be a performance cost. For instance, you'll sanitize inputs twice, while doing it once is enough. Creating HTTP context and processing it has a cost as well; it's not huge, but why adding it when you can avoid it so easily?

*It makes your application more complicated that it should be. Why would you do an HTTP request, while the data you need is just in front of you (i.e. in the data access layer interface)?
And I'm not even mentioning all the extra code you'll need. For instance, how you will configure the URI of the service to call? Will it be put in configuration (if yes, what would happen if the service moves), or will it be generated on the fly (in which case, how long it will take you to find the right solution, which will handle ports, relative URIs, HTTP/HTTPS, etc.?)

*It will add an extra line to your app server logs. And the logs of the reverse proxies.

*It will make the code more difficult to refactor. For instance, with the solution where the business layer calls the data access layer's method which retrieves a puppy, it's quite natural to think about moving the logic down the layer—in data access layer in a form of a query, or maybe the database itself. On the other hand, when you do an HTTP request, it completely abstracts away the logic behind the GET request, making it impossible to optimize later.

A: No it is not bad, just do it wisely. I mean, there is no point for calling one controller  from another, it breaks SOLID. But you can add additional layer of UseCases (as in Clean Architecture) and Services. There should be clear advantage of calling one use case from another or to calling few use cases from one service.
Edit: Original answer below:
Wordpress allows it in it's Rest API framework. It is called "internal request" and it's purpose is to ease making batch requests (as in your example). Method used to make internal requests accepts Request object, not an url. Just read the article, it will give you an idea how You could code it in Your solution.
PS: If u want to downvote just tell me in the comments why

A: I'm not an expert by any means with Node, but why don't endpoint call function. By decoupling the code from the endpoints, I would think that the function can be called from multiple endpoints without the need to make a request.
Let me know if that sounds stupid.


text:
Q: How to trigger change of input field in OPA5 tests I have a SAPUI5 application where a controller reacts to both the livechange and change events of sap.m.Input.
How do I trigger these events in OPA5 tests? Among the demo apps, I couldn't find any example.
So far, my code looks like this, employing jQuery.change:
return this.waitFor({
    id: "id_of_input_control",
    success: function (control) {
        control.$().children("input")
            .focus()
            .val("test")
            .change()
            .blur();
    },
    errorMessage: "Failed to find PLB input field"
});

This does trigger the change, but not the livechange event.
Any idea how to trigger both in the right order?

A: It would be simpler to use 'Actions' like this:
When.waitFor({
    id: "myInput",
    // If you want you can provide multiple actions
    actions: new EnterText({ text: "Hello " }))
});

OPA5 Actions

A: I came up with the following helper function:
/**
 *
 * @param {sap.ui.core.Control} oControl    - The UI5 control on which to enter input, usually sap.m.Input
 * @param {string}              sValue      - The text to set
 * @param {boolean}             [bDontBlur] - Avoid defocusing the control after text entry, which may be
 *                                            useful in non-modal popovers. Defaults to false.
 */
function processInputOnControl(oControl, sValue, bDontBlur) {
    oControl = oControl[0] || oControl;
    oControl = oControl.$().children("input");
    oControl.focus()
        .val(sValue)
        .trigger("input")
        .change();

    if (!bDontBlur) { // Blur event may close non-modal popovers, so it is optional
        oControl.blur();
    }
}


text:
Q: google document list api thumbnail link url I have a couple of questions about the url returned for the thumbnail link in document list api:
1) is the url public? (does not seem to be access controlled)
2) does the url remain the same no matter when we get the link (is the url time limited or anything like that)?
Regards,
LT


text:
Q: Is it possible to change the colour of the launcher/dash "glass"?
Possible Duplicate:
How can I change the background color of the unity launcher?

The launcher and dash have a semitransparent background which I think of as being made of black glass. I know you can change the transparency of the launcher (not sure about the dash), but is it possible to change the colour of this glass?

A: In Ubuntu 11.10, the color of the launcher and dash changes to match the color of the desktop wallpaper.


text:
Q: How to solve one to many relation tables foreign key field empty? I write this code but table relations one to many.So Person is add tables.But PersonFamily tables relations.The table is a table associated with the PersonFamily table.The code in this case works. But when I add into the PersonFamily table with ToList, the PersonFamily table data is multiplying.
Person family is taking data from two database.I want that personfamily come without data.(PersonFamily come empty.)
How can I set the StudentFamily table to come from the beginning?
How to make a clear personFamily table?
var listPerson = new List<PERSON>();
using (var t = DbContext.SingleInstance().Entities)
{
    listPerson.AddRange(t.PERSON);
}

using(var personInformation=DbContext.SingleInstance().TKEntities)
{
    foreach(var p in listPerson)
    {
        personInformation.PERSON.Add(p);
    }
    personInformation.SaveChanges();
}

PERSON TABLE : PersonID,NAME,SURNAME,PERSONFAMILYID,PERSONCOURSEID

PERSONFAMILY TABLE:PersonID,PERSONFAMILYID,PERSONFAMILYNAME,PERSONFAMILYSURNAME

PERSONCOURSE TABLE: PERSONID,COURSEID,COURSENAME

PERSONTABLE-PERSONFAMILY IS ONE TO MANY

PERSONTABLE-PERSONCOURSE IS ONE TO MANY.

I want to get PersonFamily table is empty.


text:
Q: How to set form input value in angularjs? how to set a value for an input form in angularjs?
this is my input form:
<input type="text" placeholder="John" ng-model="dataOrang.nama">

A: You can set value in controller like below.
$scope.dataOrang = {
        nama : "SomeValue"
    }

Ref: http://jsfiddle.net/Lvc0u55v/9233/

A: Add these in an controller,
$scope.dataOrang.nama = "Sample Data"

A: ng-value = Specifies the value of an input element.
ng-model = Binds the value of HTML controls to application data.

var app = angular.module( "myApp", [] );

app.controller( "myCtrl", ["$scope", function($scope) {

    // set value from app to input html
    $scope.value = {
        nama: "Doe"
    };

}] );

    <input type="text" placeholder="John" ng-model="model.nama" ng-value="value.nama" />

Nama: {{ model.nama }}


text:
Q: Why isn't my firebase notification using the proper icon? I've been trying to add a small icon to my firebase push notification. I was able to create a notification in the app (just for testing), where the icon works fine, but for some reason, firebase just wont use the icon when creating a notification. There's a blank grey circle in the top left of it.
My icon is the following: https://i.imgur.com/80UAoJc.png
My firebase notification looks like this: https://i.imgur.com/i56cecv.png?1
(notice the blank grey circle in the top left)
My manifest file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.chickentendersubsonsale">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:networkSecurityConfig="@xml/network_security_config"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <meta-data
                android:name="com.google.firebase.messaging.default_notification_icon"
                android:resource="@drawable/ic_stat_name" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

A: As per the Firebase Messaging documentation,

Within the application component, metadata elements to set a default notification icon and color. Android uses these values whenever incoming messages do not explicitly set icon or color.

You've added the <meta-data> element within your <activity> component. You need to move it to be directly within the <application> level:
<application
    android:networkSecurityConfig="@xml/network_security_config"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/ic_stat_name" />
</application>

A: Try setting the icon in the serverside code.
If you are using node.js to send Firebase notifications:
var message = {
    android: {
        notification: {
            body: "Message body",
            title: "Message title",
            icon: "ic_stat_name",
            channelId: "Your channel"
        },
        priority: "high"
    },
    tokens: "array_deviceid"
};
admin.messaging().sendMulticast(message)
    .then((batchResponse) => {
        console.log(batchResponse);
    })
    .catch((error) => {
        console.log(error);
    });

The icon takes to value of the name of the drawable resource.
See the documentation of icon key for details or if you are using another serverside language.
This also allows you to override the default icon for each notifications.

A: You can send notification with data messages with the help of Postman because right now there is not any medium to send the data messages through Firebase Console.
Data messages are handled here in onMessageReceived() whether the app is in the foreground or background.
However, notification messages are received only when the app is in the foreground.
So in both cases, we have to take care of that.
When notification messages received default notification pattern is generated and when you send data messages in your notification data payload then you can generate a custom notification as well with your proper layout.
private void sendNotification(PendingIntent pendingIntent, String notificationTitle, String notificationBody) {

        String channelId = getString(R.string.channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.ic_image)
                        .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.mipmap.ic_launcher))
                        .setContentTitle(notificationTitle)
                        .setContentText(notificationBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0, notificationBuilder.build());
    }

Mainly in your case notification icon size is taken care of as well.
Notification Icons  24 px (22px inset)  36 px   48 px   72 px   96 px


text:
Q: Can I invent an html input name or is there a standardized list, for a simple web page? I've researched this and not found this particular question answered -- I'm not asking specifically about form fillers but, for example, building a simple web page.
Is there a standardized list of input name attributes that will address all the possible options someone could put into their code?
This is an example:
<input type="radio" name="mobydick" />thewhale
<input type="radio" name="mobydick" />ahab

Thanks for your help!

A: You can use anything for the name attribute. The only restriction would be that you would want to choose something that's clear and easy for you to work with later down the road.
Or if you were looking for a list of html form attributes, check out the following:
http://www.w3schools.com/html/html_form_attributes.asp

A: According to the HTML5 specification, and in browser practice, the name attribute of an input element may have any nonempty string as its value, except that the values _charset_ and isindex have special predefined meanings.
Server-side techniques used may impose their own restrictions and implications on the names.
There are no standards on form field names. However, there were definitions of names that might be regarded as recommended names in HTML5 drafts. Although they were removed from the approved HTML5 specification due to lack of implementations, they have been retained in HTML 5.1 drafts, see clause on autofill in HTML 5.1 Nightly. The idea is that if different sites use the same names for commonly needed field types, browsers can autofill forms. E.g., after filling in your name, postal address, and date of birth on one page, your browser could automatically fill them in when you visit a page that asks for them, using the same names. Of course, such features come with risks, too.
Thus, you may, at your discretion, use the names suggested there. They partly reflect common practices, such as using email for an e-mail address field and tel for a phone number field; partly they are just ideas of what might become "standard".
Yet another aspect is that if you use the GET method, the names will become visible to users in browser's address bar after form submission. You might therefore wish to use descriptive names or, as the case may be, obfuscated names, depending on whether you want to make it easier to users to see what's happening.


text:
Q: AWS Lambda Error EADDRINUSE on every invoke I created a Nodejs AWS Lambda function which is accessed through API Gateway and it worked fine until yesterday. However, without me doing any changes to anything, it does not work anymore.
Whenever I try to invoke the function, it immediately terminates with the Error
{
    "errorType": "Error",
    "errorMessage": "listen EADDRINUSE: address already in use 0.0.0.0:3000",
    "code": "EADDRINUSE",
    "errno": -98,
    "syscall": "listen",
    "address": "0.0.0.0",
    "port": 3000,
    "stack": [
        "Error: listen EADDRINUSE: address already in use 0.0.0.0:3000",
        "    at Server.setupListenHandle [as _listen2] (net.js:1318:16)",
        "    at listenInCluster (net.js:1366:12)",
        "    at Server.listen (net.js:1452:7)",
        "    at Function.listen (/var/task/node_modules/express/lib/application.js:618:24)",
        "    at Object.<anonymous> (/var/task/app.js:433:5)",
        "    at Module._compile (internal/modules/cjs/loader.js:1068:30)",
        "    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)",
        "    at Module.load (internal/modules/cjs/loader.js:933:32)",
        "    at Function.Module._load (internal/modules/cjs/loader.js:774:14)",
        "    at Module.require (internal/modules/cjs/loader.js:957:19)"
    ]
}

My function doesn't even do anything. I tried to remove everything to check if it's human error but the error still occurs. Right now, the only thing that my function does is:
var AWS = require("aws-sdk");
AWS.config.update({ region: "eu-central-1" });
var express = require("express");
var bodyParser = require("body-parser");
var awsServerlessExpressMiddleware = require("aws-serverless-express/middleware");

var app = express();
app.use(bodyParser.json());
app.use(awsServerlessExpressMiddleware.eventContext());

app.get("/bids/:auctionid", async function (req, res) {
  res.json({ success: "true", url: req.url, body: "call success" });
});

The error happens on every lambda call.

A: I solved this by switching to port 3001


text:
Q: Which WiFi Module? We've been battling for a while with the MRF24WB0 wireless (802.11 b/g) module by microchip to finish up a project, and we are now realizing that getting it to work with most routers, and using all the various authentication types like WEP/WPA/WPA2 is quite the task.
We have seen other modules available, such as the Roving RN-171 and the Rabbit Semiconductor SPB105-WiF.
I'm wondering if any of you guys has had some experience with Wifi modules for commercial applications, and if yes which solution you would recommend.
Many thanks,
D.


text:
Q: If $A$ is a square matrix that satisfies $A^2-A+2I=0$, show that $A+I$ is invertible If $A$ is a square matrix that satisfies $A^2-A+2I=0$, show that $A+I$ is invertible. I understand how to find if $A$ is invertible but I don't know how to solve for the $A+I$ version.

A: $(A+I)(A-2I)=A^2-2A+A-2I=A^2-A-2I=-4I$

A: name $$  B = A + I \; , \; $$
$$ A = B - I $$
given
$$ A^2 - A + 2I = 0  $$
$$ (B-I)^2 - (B-I) + 2 I = 0  $$
$$ B^2 - 2 B + I - B + I + 2I = 0  $$
$$ B^2 - 3 B + 4 I = 0 $$

A: Write $B=A+I$, then $A=B-I$ and
$$0=(B-I)^2-(B-I)+2I=B^2-3B+4I.$$
From this, is it apparent that $B$ is invertible?


text:
Q: C# Regular Expression Attribute not working as expected I am using the RegularExpression attribute to verify multiple email addresses on one input in my view model.  The ErrorMessage keeps coming up on field.  I have validated my RegEx on 5 different online test sites and they all test positive.
Here is my code:
[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*([,;\s]+\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*){0,7}", ErrorMessage = "Please enter a valid email address.  For multiple addresses please use a comma or semicolon to separate the email addresses.")]
public string EmailAddresses { get; set; }

If I enter an email address it works, if I enter two email addresses without spaces it works, but if I add a space it breaks.  I added the '\s' to include white spaces and it does work on the online testers I have tried but it will not work in my application.
The expected valid result should be:
    'test@test.com, test2@test.com, test3@test.com'
However, this it coming back as invalid.  If I use the exact same sequence with no spaces it is valid.
Kendo UI is checking the validation of the form before sending it to the controller.
Any help is very appreciated.  Thank you in advance.

A: Try this pattern:
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"

A: You don't need  "@" symbol. I tested your pattern at http://regexstorm.net/tester and it is correct match for test@test.com, test2@test.com, test3@test.com . Use construct below
public class LoginViewModel
{
  [RegularExpression("\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*([,;\s]+\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*){0,7}", ErrorMessage = "Please enter a valid email address.  For multiple addresses please use a comma or semicolon to separate the email addresses.")]
  public string EmailAddresses { get; set; }

}

For it to work in ASP.NET MVC Framework ensure you do the have the following on the view
<input type="text" id ="EmailAddresses" name="EmailAddresses"/>

The id and name attributes are required for it to validate. You can do this manually as above or use @Html.EditorFor(model => model.EmailAddresses) which will create the id and name attributes for you

A: I found the issue.  In the end it had nothing to do with C#.  The problem was I was using Kendo UI on the front end, as updated in the main post.  Keno UI had to also receive the RegEx update sent by Andrew to solve the issue.  I will make Andrew as the correct solution as his RegEx did work for me.  I was totally turn around by the server side/client side difference as I am new to this.  Thank you all for your help.