Q: How do I encode URI parameter values? I want to send a URI as the value of a query/matrix parameter. Before I can append it to an existing URI, I need to encode it according to RFC 2396. For example, given the input:
http://google.com/resource?key=value1 & value2
I expect the output:
http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue1%2520%26%2520value2
Neither java.net.URLEncoder nor java.net.URI will generate the right output. URLEncoder is meant for HTML form encoding which is not the same as RFC 2396. URI has no mechanism for encoding a single value at a time so it has no way of knowing that value1 and value2 are part of the same key.

A: I don't have enough reputation to comment on answers, but I just wanted to note that downloading the JSR-311 api by itself will not work. You need to download the reference implementation (jersey).
Only downloading the api from the JSR page will give you a ClassNotFoundException when the api tries to look for an implementation at runtime.

A: Jersey's UriBuilder encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc

Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the path methods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded.

A: I wrote my own, it's short, super simple, and you can copy it if you like:
http://www.dmurph.com/2011/01/java-uri-encoder/

A: You could also use Spring's UriUtils

A: It seems that CharEscapers from Google GData-java-client has what you want. It has uriPathEscaper method, uriQueryStringEscaper, and generic uriEscaper. (All return Escaper object which does actual escaping). Apache License.

A: I think that the URI class is the one that you are looking for.

A: Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try.
You said:

For example, given an input:
http://google.com/resource?key=value
I expect the output:
http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue

So:
C:\oreyes\samples\java\URL>type URLEncodeSample.java
import java.net.*;

public class URLEncodeSample {
    public static void main( String [] args ) throws Throwable {
        System.out.println( URLEncoder.encode( args[0], "UTF-8" ));
    }
}

C:\oreyes\samples\java\URL>javac URLEncodeSample.java

C:\oreyes\samples\java\URL>java URLEncodeSample "http://google.com/resource?key=value"
http%3A%2F%2Fgoogle.com%2Fresource%3Fkey%3Dvalue

As expected.
What would be the problem with this?


Q: Comparing Long values using Collections.sort(object) I'm trying to sort a simple list of objects by a long - the below isn't working because one of the long strings is pushed to the top simply because it starts with a lower number. So I'm looking for a way to sort these by the actual long values directly
The current obj implementation looks something like the below. In the class I'm using this I call Collections.sort(trees);
public class Tree implements Comparable<Tree> {
    public String dist; //value is actually Long

    public int compareTo(Tree o) {
        return this.dist.compareTo(o.dist);
    }
}

A: Just an example I made for sorting Files by date using a Long comparator:
public File[] getAllFoldersByDescendingDate(File folder) {
    if (!folder.isDirectory()) {
        return null;
    }
    allFiles = folder.listFiles();
    Arrays.sort(allFiles, new Comparator<File>()
    {
        public int compare(final File o1, final File o2)
        {
            return Long.compare(o2.lastModified(), o1.lastModified());
        }
    });
    return allFiles;
}

A: Long.compare( x , y )
If you have an object that you want to sort on a long value, and it implements Comparable, in Java 7+ you can use Long.compare(long x, long y) (which returns an int)
E.g.
public class MyObject implements Comparable<MyObject>
{
  public long id;

  @Override
  public int compareTo(MyObject obj) {
    return Long.compare(this.id, obj.id);
  }
}

Call Collections.sort(my_objects) where my_objects is something like
  List<MyObject> my_objects = new ArrayList<MyObject>();
  // + some code to populate your list

A: It depends on how you want to do things? Do you want to keep the current implementation of Comparable? If yes, use the sort method which takes a Comparator and implement a custom comparator which uses the actual "long" values of the string (Long.parseLong(dist)). If no, then just modify the current compareTo and use the Long values of the "dist".
BTW, I'd revisit the logic and ask myself why "dist" is of type String when it is actually a Long?

A: why not actually store a long in there:
public class Tree implements Comparable<Tree> {
    public long dist; //value is actually Long

    public int compareTo(Tree o) {
        return this.dist<o.dist?-1:
               this.dist>o.dist?1:0;
    }
}

that or first compare the length of the strings and then compare them
public String dist; //value is actually Long
public int compareTo(Tree o) {
    if(this.dist.length()!=o.dist.length())
          return this.dist.length()<o.dist.length()?-1:1;//assume the shorter string is a smaller value
    else return this.dist.compareTo(o.dist);
}

A: well if the dist variable is actually long then you might try using
public int compareTo(Tree o) {
    return Long.valueOf(this.dist).compareTo(Long.valueOf(o.dist));
}

A: Why not
public class Tree implements Comparable<Tree> {
    public Long dist;

    public int compareTo(Tree o) {
        return this.dist.compareTo(o.dist);
    }
}


Q: Register php to sql server Postman when executing my register.php method and verifying it by POSTMAN I do not get any results, and when verifying in my preuse table of my SQL database I do not see any saved record.
This is my code register.php
  try {
    $dbh = new PDO("sqlsrv:Server=$host,1433; Database=$dbname", $user, $password);
       if( $dbh === false ) {
            die( print_r( sqlsrv_errors(), true));
        }

    $json=file_get_contents('php://input');
    $data=json_decode($json);

      $stm = $dbh->query("INSERT INTO AUT_APP_PREUSO (IDPERSONAL,IDVEHICULO,IDPREGUNTAS,RESPSI,RESPNO,RESPNA,RESPIVSS,RESPDSS,RESPFM,RESPFS,OBSERVACION,FIRMA,FECHAREGISTRO,IDDISPOSITIVO,NOMBREDISPOSITIVO)
            VALUES  ('".$data->{'idper'}."',
                     '".$data->{'idveh'}."',
                     '".$data->{'idpre'}."',
                     '".$data->{'respsi'}."',
                     '".$data->{'respno'}."',
                     '".$data->{'respna'}."',
                     '".$data->{'respivss'}."',
                     '".$data->{'respdss'}."',
                     '".$data->{'respfm'}."',
                     '".$data->{'respfs'}."',
                     '".$data->{'obs'}."',
                     '".$data->{'freg'}."',
                     '".$data->{'iddisp'}."',
                     '".$data->{'nombdis'}."')
                     ");

        if( $stm === false) {
            die( print_r( sqlsrv_errors(), true) );
        }

     $stmt->execute();
    $res=$stm-> fetch(PDO::FETCH_ASSOC);
    if(!$res) $mensaje="ERROR";
    else $mensaje="GRABADO";

    sqlsrv_free_result($res);
    sqlsrv_close($dbh);

    header('Content-type: application/json');
    $response = array("resultado" => $mensaje);
    echo json_encode($response);

 } catch(PDOException $e) {
        die("Database connection failed: " . $e->getMessage());
        exit;
    }


Q: Why would it be impossible to mannually test AES algorithm? I have this teacher who asked to study AES encryption algorithm, a C code implementation and do a bench testing of it.
So, I've not even tried to do a calculation of the number of steps it would take, but rather I'd like to have these rational reasons why a human can´t or might not go for it.

A: There is enough scope for misunderstanding and ambiguity in a cryptographic algorithm that it is standard practice to release example inputs and outputs (test vectors) with the specification of the algorithm, so you don't have to work through the algorithm by hand. There appear to be test vectors in the specfication at http://csrc.nist.gov/groups/STM/cavp/. In fact, appendix B of fips-197.pdf appears to show how the state table evolves during a single encryption.
Of course, for a system like AES, where it is not practical to test every possible input and key, you can always argue that while testing can find errors it can never prove the absence of errors.

A: Anything a computer can do - you can do as well.... they don't use magic for calculation.
To test your algorithm, you should encrypt a small text and than decrypt and see that you get the same results (it will prove the algorithm works, it won't prove it's AES....)


Q: msvc++ doesn't see overloaded operator<< I'm porting a piece of code which was written for Linux and compiled with gcc v4.8.2 (using -std=c++11) to Windows. Part of it is an overloaded operator<< which MSVC++ 2013 doesn't agree with. A condensed example is below.
We've defined a custom stream class which supports the standard stream manipulator functions. For this reason we've overloaded operator<< which accepts a function pointer as second argument.
If I define a templated overload of operator<< for . MSVC++ complains:

error C2676: binary '<<' : 'foobar' does not define this operator
         or a conversion to a type acceptable to the predefined operator

But if I specify the type of the second argument as std::ostream instead of the templated std::basis_ostream<..,..> the code works as expected.
At first I thought I had messed up the template arguments. However, if I define an arbitrary template function instead of an overload of operator<< the code compiles fine. What's going on here?
Example
#include "stdafx.h"

#include <iostream>
#include <sstream>
#include <string>

struct foobar {
    std::stringstream s_;
};

/* Causes compiler error C2676
template <typename CharT = char, typename Traits = std::char_traits<CharT> >
foobar& operator<<(foobar& foo, std::basic_ostream<CharT, Traits>& (*manip)(std::basic_ostream<CharT, Traits>&))
{
    foo.s_ << manip;
    return foo;
}
 */

/* works as intendend */
foobar& operator<<(foobar& foo, std::ostream& (*manip)(std::ostream&))
{
    foo.s_ << manip;
    return foo;
}

/* works too */
template <typename CharT = char, typename Traits = std::char_traits<CharT> >
foobar& qux(foobar& foo, std::basic_ostream<CharT, Traits>& (*manip)(std::basic_ostream<CharT, Traits>&))
{
    foo.s_ << manip;
    return foo;
}

int _tmain(int argc, _TCHAR* argv[])
{
    foobar foo;
    foo << std::endl;

    qux(foo, std::endl);
    return 0;
}

A: There appears to be some kind of bug with default arguments, overloaded operators, and template function parameter overload resolution.
These are all complex, so sort of understandable.
The good news is that you shouldn't be taking just any iomanip there -- you should be taking a specific one.
You can either hard code it, or deduce it like so:
// Get the nth type from a template instance:
template<class...>struct types{using type=types;};
template<class T, size_t N>
struct nth{};
template<class T, size_t N>
using nth_t=typename nth<T,N>::type;
template<template<class...>class Z, class T0, class...Ts, size_t N>
struct nth<Z<T0,Ts...>,N>:nth<types<Ts...>,N-1>{};
template<template<class...>class Z, class T0, class...Ts>
struct nth<Z<T0,Ts...>,0>{using type=T0;};

// From a String type, produce a compatible basic_stream type:
template<class String>
using compat_stream = std::basic_ostream<nth_t<String,0>, nth_t<String,1>>;

// From a type T, produce a signature of a function pointer that
// pass-through manipulates it:
template<class T>
using manip_f = T&(*)(T&);

// From a String type, produce a compatible io-manipulator:
template<class String>
using io_manip_f = manip_f< compat_stream<String> >;

// The return of foobar:
struct foobar {
  std::stringstream s_;
  // the type of manipulators that is compatible with s_:
  using manip_f = io_manip_f<std::stringstream> manip;
  // a Koenig operator<<:
  friend foobar& operator<<( foobar& self, manip_f manip ) {
    self.s_ << manip;
    return self;
  }
};


Q: What are pipe and tap methods in Angular tutorial? I'm following the tutorial at https://angular.io, and I'm having trouble finding documentation; specifically for the methods pipe and tap.  I can't find anything on https://angular.io or http://reactivex.io/rxjs/.
My understanding is that pipe and tap are both methods of Observable, which is being imported from RxJS, correct? What are they supposed to do?
Are these methods part of Angular? What do these two methods do?

A: You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:
  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:
Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).
Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().


Q: How to store continuous user input in an array? For example:
  user input: 12345

then each integer will be placed inside an array.
    int[] arr = { 1, 2, 3, 4, 5 };

A: You can try some variation on the following
//get user input as a string and convert to integer array

int[] num = "12345".Select(a => Int32.Parse(a.ToString())).ToArray();

A: Try this way
string str1 = "123456";
    int[] arr = new int[str1.Length];
    for (int ctr = 0; ctr <= str1.Length - 1; ctr++)
    {
        arr[ctr] = Convert.ToInt16(str1[ctr].ToString());
    }

Demo result:

Take a look at Page load event code only.... :p Cheers

A: String input="123456";
int [] intArray=new int[input.Length];
int count=0;
foreach(var ch in input)
{
intArray[count]=Convert.ToInt32(ch.ToString());
count++;
}


Q: SQL Server: Find words in string that don't exist in dictionary Consider the following tables:
DROP TABLE IF EXISTS ##tableA;
CREATE TABLE ##tableA (id int,keywords VARCHAR(MAX));
INSERT INTO ##tableA (id,keywords) VALUES
    (1,'apple,orange,potato'),
    (2,'I typed a sentence here because I can''t follow directions.'),
    (3,'potato and apple');

DROP TABLE IF EXISTS ##dictionary;
CREATE TABLE ##dictionary (id int,keyword VARCHAR(255));
INSERT INTO ##dictionary (id,keyword) VALUES
    (1,'apple'),
    (2,'orange'),
    (3,'lemon'),
    (4,'potato');

We have users entering keywords into the keyword column in tableA.  I want return the id of any record that contains a word not in ##dictionary.
In the case above:
- id 1 would not be returned because each comma separated keyword is found in the dictionary
- id 2 would be returned because it contains words that are not in the dictionary
- id 3 would be returned because it contains the word "and", which is not in the dictionary

The ideal situation I think would somehow break up the keywords column from ##tableA into individual keywords, then check each of them against the keyword column in ##dictionary.

A: Here is an inline approach
Example
Select Distinct A.*
 From  ##tableA A
 Cross Apply (
                Select RetSeq = Row_Number() over (Order By (Select null))
                      ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
                From  (Select x = Cast('<x>' + replace((Select replace(replace(A.KeyWords,',',' '),' ','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
                Cross Apply x.nodes('x') AS B(i)
             ) B
 Left Join ##dictionary C on B.RetVal=C.keyword
 Where C.keyWord is null

Returns
id  keywords
2   I typed a sentence here because I can't follow directions.
3   potato and apple

Just another BRUTE FORCE OPTION - Just for fun

Declare @S varchar(max) = (Select * From ##tableA For XML Raw )
Select @S = replace(@S,keyword,'') From  ##dictionary

Select id = B.i.value('@id', 'int')
 From  (Select x = Cast(@S as xml).query('.')) as A
 Cross Apply x.nodes('row') AS B(i)
 Where B.i.value('@keywords', 'varchar(max)') like '%[a-z]%'

A: Under SQL Server 2017, you can use STRING_SPLIT:
SELECT
    id
FROM
    ##tableA
    CROSS APPLY STRING_SPLIT(keywords, ' ') splitBySpace
    CROSS APPLY STRING_SPLIT(splitBySpace.value, ',') splitBySpaceOrComma
WHERE
    splitBySpaceOrComma.value NOT IN (SELECT keyword FROM ##dictionary)
GROUP BY
    id;

A: Using:
Splitter
you can split lines by delimiter then use the result to match against the dictionary.  like this:
SELECT t.keywords FROM ##tablea t
CROSS APPLY (SELECT REPLACE(t.keywords, ' and ', ',')) new(kwds)
CROSS APPLY dbo.DelimitedSplit8K(new.kwds, ',') s
WHERE s.item NOT IN (SELECT keyword FROM ##dictionary)

A: Try this:
select t.*
from ##tableA t
cross join (
    select max(case when id = 1 then keyword end) firstKeyword,
           max(case when id = 2 then keyword end) secondKeyword,
           max(case when id = 3 then keyword end) thirdKeyword,
           max(case when id = 4 then keyword end) fourthKeyword
    from ##dictionary
) d where
  len(replace(replace(replace(replace(replace(replace(keywords, firstKeyword, ''), secondKeyword, ''), thirdKeyword, ''), fourthKeyword, ''), ' ', ''), ',', '')) > 0

First, you need to pivot your data from ##dictionary, then you can replace your keywords with '' as well as spaces and commas, and see in the end if the are any characters left.


Q: Android application, listening to streaming radio. No internet or mobile data bug http://pastebin.com/G4UrTT7Z
What can I do to check for a working internet connection?
Or how do I check if connection is lost?
Can someone help me with this ?
I suppose this is a IOException. I am not sure. When watching logcat and console I don't see any exceptions or forcecloses.
My source code is posted on pastebin.

A: One way is to read a well known site content with URL connection. If you can read it, then it means you have an Internet connection.
Other is to connect to your radio station site: this has double requirement: you have Internet connection AND the radio station site is up.
Maybe both of them will block you, if you read too often!
There is android buggy API to read the network state and suck, but if you connect to WIFI , then you will have the Connected state from API even if your WAN cable pulled out...


Q: How to add more than one image to application using Spring Boot? I have an application which allows to add an image to a product but I don't know how to refactor it that there will be possibility to add many images to one product.
This is model:
  @Entity
  public class ProductEntity {

   @Lob
   private byte[] image;

   public String getImageBase64() {
    return Base64.getEncoder().encodeToString(this.image);
}

This is Controller:
@PostMapping("/add")
@Secured(ROLE_ADMIN)
public String saveProduct(ProductDTO productDTO, @RequestParam("image2") MultipartFile[] files) {
    try {
        if (files != null && files.length > 0) {
            InputStream is = files[0].getInputStream();
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            productDTO.setImage(buffer);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    productService.addProduct(productDTO);
    return "redirect:/product/list";
}


Q: FlatList inside FlatList scrolling problem I want to put a FlatList inside another one, but the child flatlist not scrolling.
I tried to convert the child FlatList to ScrollView, put the props scrollEnabled to false to the parent FlatList and both not work.
Here is a code example of what I want to do: https://snack.expo.io/HJ6d97gNH
I expect to scroll inside both flatlist, not only one.

A: use nestedScrollEnabled in inner Flatlist for enabling the scrolling activity

A: You can use the nestedScrollEnabled prop but I would recommend using a <SectionList> since this is somehow buggy!


Q: How to define static folder path in nodejs multer image upload I am setting static path but getting error : "Error: ENOENT: no such file or directory, open 'C:\dashboard new - Copy\uploads\2019-11-28T08:11:09.164Z1564660431900.jpg'"
const storage = multer.diskStorage({  destination: function(req, file, cb) { let dest = path.join(__dirname, '../../uploads'); cb(null, dest);  }, filename: function(req, file, cb) {    cb(null, new Date().toISOString() + file.originalname);  }});

const fileFilter = (req, file, cb) => {  if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {    cb(null, true);  } else {    cb(null, false);  }};

const upload = multer({  storage: storage,  limits: {    fileSize: 1024 * 1024 * 5  }, fileFilter: fileFilter});

router.post("/", upload.single('productImage'), async (req, res, next) => {
try {
    cosole.log('hi');
    const product = new Product({
      _id: new mongoose.Types.ObjectId(),
      name: req.body.name,
      price: req.body.price,
      productImage: req.file.path
    });
    const saveImage = await product.save();
    console.log(saveImage)
    res.json(saveImage);
} catch (error) {
  console.log(error);
  res.json(error);
}

});

How to do this?

A: I think you need to provide the destination folder as a key and value, something like this(below)
var upload = multer({ dest: 'uploads/' })
You can check out the full multer documentations here
https://expressjs.com/en/resources/middleware/multer.html


Q: Why is this query with WHERE, ORDER BY and LIMIT so slow? Given this table posts_lists:

                      Table "public.posts_lists"
   Column   |          Type          | Collation | Nullable | Default
------------+------------------------+-----------+----------+---------
 id         | character varying(20)  |           | not null |
 user_id    | character varying(20)  |           |          |
 tags       | jsonb                  |           |          |
 score      | integer                |           |          |
 created_at | integer                |           |          |
Indexes:
    "tmp_posts_lists_pkey1" PRIMARY KEY, btree (id)
    "tmp_posts_lists_idx_create_at1532588309" btree (created_at)
    "tmp_posts_lists_idx_score_desc1532588309" btree (score_rank(score, id::text) DESC)
    "tmp_posts_lists_idx_tags1532588309" gin (jsonb_array_lower(tags))
    "tmp_posts_lists_idx_user_id1532588309" btree (user_id)

Getting a list by tag is fast:
EXPLAIN ANALYSE
SELECT * FROM posts_lists
WHERE jsonb_array_lower(tags) ? lower('Qui');

Bitmap Heap Scan on posts_lists  (cost=1397.50..33991.24 rows=10000 width=56) (actual time=0.110..0.132 rows=2 loops=1)
  Recheck Cond: (jsonb_array_lower(tags) ? 'qui'::text)
  Heap Blocks: exact=2
  ->  Bitmap Index Scan on tmp_posts_lists_idx_tags1532588309  (cost=0.00..1395.00 rows=10000 width=0) (actual time=0.010..0.010 rows=2 loops=1)
        Index Cond: (jsonb_array_lower(tags) ? 'qui'::text)
Planning time: 0.297 ms
Execution time: 0.157 ms

Getting a list ordered by score, limit 100 - also fast:
EXPLAIN ANALYSE
SELECT *
FROM posts_lists
ORDER BY score_rank(score, id) DESC
LIMIT 100;

Limit  (cost=0.56..12.03 rows=100 width=88) (actual time=0.074..0.559 rows=100 loops=1)
  ->  Index Scan using tmp_posts_lists_idx_score_desc1532588309 on posts_lists  (cost=0.56..1146999.15 rows=10000473 width=88) (actual time=0.072..0.535 rows=100 loops=1)
Planning time: 0.586 ms
Execution time: 0.714 ms

But combining the above two queries is very slow:
EXPLAIN ANALYSE
SELECT * FROM posts_lists
WHERE jsonb_array_lower(tags) ? lower('Qui')
ORDER BY score_rank(score, id) DESC
LIMIT 100;

Limit  (cost=0.56..33724.60 rows=100 width=88) (actual time=2696.965..493476.142 rows=2 loops=1)
  ->  Index Scan using tmp_posts_lists_idx_score_desc1532588309 on posts_lists  (cost=0.56..3372404.39 rows=10000 width=88) (actual time=2696.964..493476.139 rows=2 loops=1)
        Filter: (jsonb_array_lower(tags) ? 'qui'::text)
        Rows Removed by Filter: 9999998
Planning time: 0.426 ms
Execution time: 493476.190 ms

Why? How to improve the efficiency of the query?
Definition of the two functions used above:
create or replace function score_rank(score integer, id text)
  returns text as $$
select case when score < 0
  then '0' || lpad((100000000 + score) :: text, 8, '0') || id
       else '1' || lpad(score :: text, 8, '0') || id
       end
$$
language sql immutable;

create or replace function jsonb_array_lower(arr jsonb)
  returns jsonb as $$
SELECT jsonb_agg(lower(elem))
FROM jsonb_array_elements_text(arr) elem
$$
language sql immutable;

A: The problem with this statement is, that the query planner has no usable statistics for jsonb_array_lower(tags).
As seen in the first explain:
(cost=0.00..1395.00 rows=10000 width=0) (actual time=0.010..0.010 rows=2 loops=1)

The planner expects 10.000 rows to be returned if he uses the filter jsonb_array_lower(tags) ? lower('Qui') but there are just two rows returned.
The same happens in the last statement. Because of this missing information, the planner assumes, that a scan on the index tmp_posts_lists_idx_score_desc1532588309 would be more efficient.
You could try to avoid the need of lower and normalize the input during INSERT and UPDATE.
Another method would be:
WITH c AS (
    SELECT id FROM posts_lists
    WHERE jsonb_array_lower(tags) ? lower('Qui')
)
SELECT * FROM posts_lists l, c
WHERE l.id = c.id
ORDER BY score_rank(score, id) DESC
LIMIT 100;

This statement uses a CTE as optimization fence, but be careful, the performance may get worse for other WHERE conditions or table content.

A: Sorting and paging
Your function score_rank() produces a text from an integer score and the appended PK id. That's not helpful for sorting. Replace it completely, I suspect you do not need it at all. Instead use the two columns score and id directly for sorting:
SELECT *
FROM   posts_lists
ORDER  BY score DESC, id DESC
LIMIT  100;

Replace your index tmp_posts_lists_idx_score_desc1532588309 with a smaller, faster, cheaper to maintain, more versatile index on (score DESC, id DESC).
You can also base pagination on this multicolumn index efficiently with row value comparison. See:

*

*Optimize query with OFFSET on large table

*SQL syntax term for 'WHERE (col1, col2) < (val1, val2)'
You later mentioned a new function concatenating strings with base256 etc. All that smart trickery is not going to increase performance. Sorting on an integer is faster than sorting on strings in Postgres. Using integer (or bigint) instead of varchar(20) would actually help in multiple ways.
Statistics and query plan (a.k.a: Why?)
The main issue is the lack of statistics for values nested in the jsonb column. Postgres consequently sometimes misjudges the selectivity of the predicate jsonb_array_lower(tags) ? lower('Qui') and chooses a bad query plan. In your example with LIMIT 2 the logic of the query planner can be illustrated like this - let's call this "Plan 1":
Only two rows with the highest scores? Let's scan the index posts_lists_idx_score_desc starting with the highest scores. With any luck we'll have the result in no time!
It's a reasonable plan for most cases with at least moderately common tags. But the tag 'qui' turns out to be very rare, and with low scores, too. The worst case. Postgres ends up scanning close to 4 million rows, just to keep 2. A colossal waste of time:

Rows Removed by Filter: 3847383

If the query planner had any idea how rare that tag actually is, it would start with the other index posts_lists_idx_tags like we see in your second example with LIMIT 100 - let's call this "Plan 2":
Find matching rows, then sort by score and take the top N.
Plan 1 is more favorable the smaller the LIMIT and the more frequent the tag. (And if qualifying rows happen to sort on top.)
Plan 2 is more favorable the bigger the LIMIT and the less frequent the tag.
Postgres has currently no statistics about nested values in document types like jsonb. And no combined frequencies at all. See:

*

*SELECT very slow when no results and a LIMIT is specified

*Inconsistent statistics on jsonb column with btree index
Update: "Combined statistics" became possible with CREATE STATISTICS in Postgres 10.
What ever else you do, be sure to run the latest version of Postgres. The planner gets smarter with every release.
Alternatives
1. One idea might be to use a Postgres array (text[]) and array operators instead of the jsonb column to have some statistics for most common elements. Columns most_common_elems, most_common_elem_freqs, and elem_count_histogram in the system view pg_stats.
Helps Postgres to generate better query plans for some constellations, but it's no silver bullet. For starters, only the most common elements are stored. Postgres still doesn't know about the rarest elements.
2. Normalize your db design and move tags to a separate 1:n table with a single tag per row. That increases the disk footprint because of the added row overhead per tag. (But changing tags becomes much cheaper with less table bloat.) If your tags are stable, consider a full n:m relationship between posts_lists and a new table tags. That's a bit smaller for lots of common tags, too. And it's the "clean" way. You have more detailed statistics and should see fewer bad query plans.
3. Since Postgres 10 there is a variant of to_tsvector() that processes json(b) values. So it's simple to create a text search index and work with text search operators now.
Index:
CREATE INDEX posts_lists_idx_tags_fts ON posts_lists USING gin (to_tsvector('simple', tags));

Query:
SELECT * FROM posts_lists
WHERE  to_tsvector('simple', tags) @@ to_tsquery('simple', 'qui') -- text search is case insensitive
ORDER  BY score DESC, id DESC
LIMIT  2;

Be sure to use the simple dictionary. You don't want stemming which is built into most other dictionaries.
Text search functions produce lower case output, it all works case insensitive by design. No need for processing like in your original function jsonb_array_lower().
4. While sticking with a jsonb index, try the more specialized jsonb_path_ops operator class:
CREATE INDEX ON posts_lists USING gin (jsonb_array_lower(tags) jsonb_path_ops);

Query with:
WHERE  jsonb_array_lower(tags) @> '["qui"]'

The manual:

Although the jsonb_path_ops operator class supports only queries with
the @> operator, it has notable performance advantages over the
default operator class jsonb_ops. A jsonb_path_ops index is usually
much smaller than a jsonb_ops index over the same data, and the
specificity of searches is better, particularly when queries contain
keys that appear frequently in the data. Therefore search operations
typically perform better than with the default operator class.

But I do not expect much for your particular case.
5. Use a regime of "granulated" indexes, combined with a procedural solution. See:

*

*Can spatial index help a "range - order by - limit" query
db<>fiddle here - with a number of tests ...


Q: For which x does this series converge? Assume $f: \mathbb{R} \to \mathbb{R} $ is differentiable, $f(0)=0$ and $f’$ is bounded. For $x \in \mathbb{R}$ we define $\sum_{n \geq 1} f\left( \frac{x}{n^2}\right)$. For what $x$ does this series converge?

I have no clue how to solve this. I know that because $f$ is differentiable, it is continuous and because the derivative is bounded, it is even uniformly continuous. I know that the series converges for $x=0$ (or any $x$ for which $f(x)=0$). I’m trying out various convergence tests, but I feel like there’s something I’m missing...

How do I use the uniform continuousness?

A: Using Lagrange's theorem and the boundedness of $f'$
$$|f(\frac{x}{n^2})|\leq C\frac{|x|}{n^2}$$
and so the series always (absolutely) converges


Q: getting MismatchSenderId with firebase serverside I am trying to send the notification using a php script that is stored in my server and I am getting the MismatchSenderId.
$to="device_id";
$title="MYAPP Push";
$message=" MYAPP Push Notification Message";

sendPush($to,$title,$message);

function sendPush($to,$title,$message){
  // API access key from Google API's Console
  // replace API
  define( "API_ACCESS_KEY", "server_key_provided_by_firebase");

  $registrationIds = array($to);

  $msg = array(
    'message' => $message,
    'title' => $title,
    'vibrate' => 1,
    'sound' => 1
    // you can also add images, additionalData
  );

  $fields = array(
    'registration_ids' => $registrationIds,
    'data' => $msg
  );

  $headers = array(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
  );

  $ch = curl_init();
  curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
  curl_setopt( $ch,CURLOPT_POST, true );
  curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
  curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
  curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
  curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
  $result = curl_exec($ch );

  curl_close( $ch );
  echo $result;
}

Here the error I get when I run the php script:
{"multicast_id":7804476702639319453,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}
I've checked every single question here in stackoverflow and could not solve it.
I am using firebase (spark plan) and developing the app with Phonegap. I believe that has nothing to do with the app
Any Ideas???

A: Copy your google-service.json file to root folder (that contains www, config.xml etc).
Step 1:
Login to your firebase console.

Step 2:
On Project Overview Settings, Copy the Cloud Messaging ServerKey
My key ex:
`AAAAjXzVMKY:APA91bED4d53RX.....bla bla

Step 3:
Replace the key
define( "API_ACCESS_KEY", "My key");

Finally Test the app :D
I sent push notification using node succesfully.

var gcm = require('node-gcm');

// Replace these with your own values.
var apiKey = "MY_SERVER_KEY";
var deviceID = "MY_DEVICE_ID";

var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'Hi');
message.addData('body', 'BLA BLA BLA BLA');
message.addData('actions', [
  { "icon": "accept", "title": "Accept", "callback": "app.accept"},
  { "icon": "reject", "title": "Reject", "callback": "app.reject"},
]);

service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
 if(err) console.error(err);
 else  console.log(response);
});

A: The documentation for this error states:

A registration token is tied to a certain group of senders. When a
  client app registers for FCM, it must specify which senders are
  allowed to send messages. You should use one of those sender IDs when
  sending messages to the client app. If you switch to a different
  sender, the existing registration tokens won't work.

You should double check that you are using the Server Key from the same project used to generate the google-services.json file the app was built with.  The project_number at the top of the google-services.json file must be the same as the Sender ID shown in the project settings Cloud Messaging tab of the Firebase Console.


Q: Problems with TEXTAREA line breaks in ASP.NET MVC 2 I really don't think this has anything to do with ASP.NET MVC 2 itself, but I mention that as it is the environment I am working in and at least one aspect of my problem is connected to the way MVC 2 behaves.  My problem is this:
I have a TEXTAREA element on a form that allows multiple lines of data to be entered.  When the form is posted back to the server (using IE8), I can see that the data is formatted as "A\n\rB\n\rC\n\rD".  I then save this data to a database table where it appears exactly the same way.  However, when I come back to the page at a later time, loading the data from the database and setting it as the value of the TEXTAREA element, it displays the "\n\r" as literal characters instead of line breaks!
As a side note, with ASP.NET MVC, if I follow the standard if (!ModelState.IsValid) return View(viewModel); approach, the TEXTAREA displays fine when re-rendering the same form due to a validation error.  This tells me that the problem must be related to persisting and retrieving the data to/from the (SQL Server) database.
I have the same display problem in FireFox and Chrome with the notable difference being that the data is formatted as "A\r\nB\r\nC\r\nD" when submitted from those browsers.
With these differences in behavior, how can I handle persisting multi-line data from a TEXTAREA that will render properly in ALL browsers?

A: You should replace \r\n char with  tag and create a MvcHtmlString when you want render the text, I use this:
@(MvcHtmlString.Create(Model.Text.Replace("\r\n","
").Replace("\n\r","
)))

Model.Text is a text from an TextArea, I've tested this line of code and it works as well on all five major browsers (IE, FF, Chrome, Opera, Safari).

A: I haven't found an actual solution but have implemented a work around.
When I set the property on my object to the submitted value from the TEXTAREA, I perform a regular expression replacement on the text to convert whatever characters are returned from the browser to '\n' which appears to work as a line break in all browsers I checked (IE8, Chrome & FireFox). Here is the code I'm using (in .NET):
cleanValue = Regex.Replace(value, "(\\n|\\\\n|\\r|\\\\r)+", "\n", RegexOptions.IgnoreCase);


Q: Can anyone give me a little explanatory example about InsertOnSubmit and InsertAllOnSubmit I am trying to understand difference between those two and really need a explanatory simple example for them.
Thanks in advance..

A: Theres a good Q&A about this on the MSDN forums. Most interesting bit:

InsertAllOnSubmit() simply loops over
  all the elements in the IEnumerable
  collection and calls InsertOnSubmit()
  for each element.

A: InsertOnSubmit adds a single record. InsertAllOnSubmit does the same, but for a set (IEnumerable<T>) of records. That's about it.

A: I found this example of InsertAllOnSubmit() at the very bottom of this page.  Just remember to add a using statement for System.Collections.Generic
// Create list with new employees
List<Employee> employeesToAdd = new List<Employee>();

employeesToAdd.Add(new Employee() { EmployeeID = 1000, FirstName = "Jan", LastName = "Jansen", Country = "BE" });
employeesToAdd.Add(new Employee() { EmployeeID = 1001, FirstName = "Piet", LastName = "Pieters", Country = "BE" });
employeesToAdd.Add(new Employee() { EmployeeID = 1002, FirstName = "John", LastName = "Johnson", Country = "BE" });

// Add all employees to the Employees entityset
dc.Employees.InsertAllOnSubmit(employeesToAdd);

// Apply changes to database
dc.SubmitChanges();


Q: Django Rest_Framework strange error can't import name SkippError I just started a project and installed django rest framework, then i have added it in settings.py 's installed apps.
then i run the server, it through me this error:

File
  "/home/pyking/.local/lib/python3.6/site-packages/django/template/backends/django.py",
  line 125, in get_package_libraries
      "trying to load '%s': %s" % (entry[1], e) django.template.library.InvalidTemplateLibrary: Invalid template
  library specified. ImportError raised when trying to load
  'rest_framework.templatetags.rest_framework': cannot import name
  'SkipError'

When removing rest_framework from installed apps, the server works nice, but if add rest_framework in settings.py 's installed apps ,it doesn't work, and throw me above error
Note: The project dont have any models, view, serializers file and anything. i new project with new apps,
Can you please tell me why i facing this error?

A: If there's no missprint - there's some dependencies missing. Create isolated virtualenv and install django and djangorestframework (maybe that's the problem you typed pip install django_rest_framework instead of djangorestframework).


Q: Trying to test SAML auth with open/free SAML IDP I am trying to test and debug SAML authentication with my app.  I currently do not have my own SAML IDP so I am trying to test with free/open SAML IDP providers.
Currently I am testing with SSOCircle: https://www.ssocircle.com/
And when testing after I sign in with that provider I get:

Error occurred
Reason: Unable to do Single Sign On or Federation.
Please enable the additional debug option in "My Debug". Detailed
  trace information only available with paid accounts. Check our plans.

Anyone successfully setup SAML auth within their app using SSOCircle. If so can you provide insight into what might be the problem.  I signed up for an account and registered my service provider on their site.
I have also looked around for simple free SAML testing IDPs without much luck.  If anyone has one they are using that is working that would be helpful as well.

A: using http in SSOCircle address instead of https has worked for me


Q: Relative Path to OpenType Font in LyX I am trying to use custom OpenType fonts (using LuaLaTeX and the fontspec package) in a LyX document under version control. The document is potentially accessed by others on different machines, so I decided to ship the .otf files in a subdirectory of the document's folder rather than relying on them being installed on the system. In other words, I just wanted to have the document in a compilable state as soon as it is checked out from version control without the need of installing the otf files.
This is how I wanted to add the fonts in the document's LaTeX Preamble:
\setmainfont{foo}[
    Path = mypath,
    UprightFont = foo-regular.otf,
    BoldFont = foo-bold.otf,
    ItalicFont = foo-it.otf,
    BoldItalicFont = foo-boldit.otf,
]

As long as mypath is an absolute path, everything works fine. As soon as I want to use a relative path here (because absolute paths don't make sense for files under version control) the fonts are not found any more.
Is there any solution to either (a) make a relative path work here or (b) somehow determine the absolute path of the current folder (not LyX's temporary folder where the document is actually compiled) and plug it in at mypath? Or is there any other obvious solution that I have overlooked?

A: Here is how I could solve it (thanks to the help of G.M.). Suppose the otf files are in a subdirectory called "fonts" that lies under the directory that contains the main LyX file:
\setmainfont{foo}[
    Path           = \input@path,
    UprightFont    = fonts/foo-regular.otf,
    BoldFont       = fonts/foo-bold.otf,
    ItalicFont     = fonts/foo-it.otf,
    BoldItalicFont = fonts/foo-boldit.otf,
]

As G.M. explained, \input@path refers to the original directory (i.e. not the temporary directory where everything will be compiled).
Update:
In my original solution, I had everything surrounded with \makeatletter and \makeatother. However, as G.M. also mentioned, LyX's LaTeX Preamble already provides this. So this is not necessary here and might indeed even cause trouble.


Q: How could i use flags to select which func i want to call Hello this is my first actually stab at writing an actual Go command line program so please forgive the appearance I also pulled some of this code off the Internet. What I am actually trying to do is have the ability to choose when i want to encrypt or decrypt while still being able to choose the src file and dest file. Thanks in advance for any help. I couldn't find anything solid explaining this or at least nothing i could make out.
package main

import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"io"
"io/ioutil"
"log"
"os"
)

func decrypt(key, ciphertext []byte) (plaintext []byte, err error) {

  var block cipher.Block

  if block, err = aes.NewCipher(key); err != nil {
      return
 }

  if len(ciphertext) < aes.BlockSize {
    err = errors.New("ciphertext too short")
    return
 }

  iv := ciphertext[:aes.BlockSize]
  ciphertext = ciphertext[aes.BlockSize:]

  cfb := cipher.NewCFBDecrypter(block, iv)
  cfb.XORKeyStream(ciphertext, ciphertext)

  plaintext = ciphertext

   return
 }

func encrypt(key, text []byte) (ciphertext []byte, err error) {

  var block cipher.Block

  if block, err = aes.NewCipher(key); err != nil {
      return nil, err
 }

  ciphertext = make([]byte, aes.BlockSize+len(string(text)))

  iv := ciphertext[:aes.BlockSize]
  if _, err = io.ReadFull(rand.Reader, iv); err != nil {
      return
 }

  cfb := cipher.NewCFBEncrypter(block, iv)
  cfb.XORKeyStream(ciphertext[aes.BlockSize:], text)

  return
 }

func encryptFileData(srcFile, destFile string) {
  if len(os.Args) > 1 {
      srcFile = os.Args[1]
  }
  if len(os.Args) > 2 {
      destFile = os.Args[2]
 }
  var cipherText, plainText []byte
  var err error

  key := []byte("abcdefg123456789")

  plainText, _ = ioutil.ReadFile(srcFile)
  if cipherText, err = encrypt(key, plainText); err != nil {
      log.Fatal(err)
  }
  ioutil.WriteFile(destFile, cipherText, 0755)

   return
  }

func decryptFileData(srcFile, destFile string) {
  if len(os.Args) > 1 {
      srcFile = os.Args[1]
  }
  if len(os.Args) > 2 {
      destFile = os.Args[2]
  }
  var cipherText, plainText []byte
  var err error

  key := []byte("abcdefg123456789")

  cipherText, _ = ioutil.ReadFile(srcFile)
  if plainText, err = decrypt(key, cipherText); err != nil {
      log.Fatal(err)
  }
  ioutil.WriteFile(destFile, plainText, 0755)

  return
  }

func main() {
  encryptFileData(os.Args[1], os.Args[2])
  decryptFileData(os.Args[1], os.Args[2])
}

A: Use the flag package. For example:
func main() {
    encrypt := flag.Bool("encrypt", false, "encrypt file")
    decrypt := flag.Bool("decrypt", false, "decrypt file")
    flag.Parse()

    srcFile, destFile := flag.Arg(0), flag.Arg(1)
    if *encrypt {
        encryptFileData(srcFile, destFile)
    }

    if *decrypt {
        decryptFileData(srcFile, destFile)
    }
}


Q: Is there literature on non-computable numbers that can't be even be identified? It seems to me that most real numbers can't be calculated by any finite set of instructions, even if we make use of non-computable functions.
First, assume that we have an oracle that will provide the digits of any specified non-computable number to arbitrary precision. So, for example, if we state a particular instance of Chaitin's constant, then our oracle can gives us this value to arbitrary precision. This would allow us to perform operations on non-computable numbers. And by extension, we could even specify non-computable operations on non-computable numbers, so long as the result is also some real number, which our oracle can then provide to arbitrary precision.
Any such specification will consist of a finite set of instructions, some of which could include non-computable functions, the outputs of which will be provided by our oracle.
Note that the set of all such instructions is countable, since any language in which we express the instructions will necessarily be finite. It follows that even if we allow for the use and resolution of non-computable functions, we can only specify a countable subset of the reals using any particular language.
It follows that not only are most of the real numbers non-computable, they're incapable of articulation using a finite language.
Note that this is distinct from defining a particular real number. Instead, I am pointing out that even if we make use of non-computable functions, it does not seem possible to construct a one-to-one map from (A) the set of statements that define a computation to (B) the set of real numbers.
As a result, it does not appear to be possible to calculate the set of real numbers by making use of a finite set of non-computable functions.
In short, most real numbers can't even be calculated using a finite set of non-computable functions.
Is there a known set of functions that are capable of generating all real numbers?

A: Essentially, it sounds like you're looking for computability theory, and specifically the theory of the Turing degrees. You already understand the notion of relative (= oracle) computability; the Turing degrees are the resulting equivalence classes. Each real $a$ (or function from naturals to naturals, or set of naturals, or [naturally equivalent object]) generates a Turing degree $$deg(a)=\{b: b\equiv_Ta\}.$$ Here "$x\equiv_Ty$" means "$x\le_Ty$ and $y\le_Tx$," as expected. The Turing degrees form a partial order - denoted $\mathcal{D}$ - with respect to $\le_T$: for Turing degrees ${\bf a},{\bf b}$ we say ${\bf a}\le_T{\bf b}$ if every element of ${\bf a}$ is $\le_T$ every element of ${\bf b}$ (note that we can replace "every" with "some" without affecting the meaning).
The (correct) observation you've made amounts to the statement that the Turing degrees have the countable predecessor property - for each ${\bf a}$, there are at most countably many ${\bf b}\le_T{\bf a}$ - and hence no single Turing degree (or finite set of degrees, or even countable set of degrees) "covers" everything. This is just the start of things, though - one of the major topics in computability theory is the study of the structural features of $\mathcal{D}$. Some basic questions:

*

*Is $\mathcal{D}$ linearly ordered? (No.)

*

*Note that this doesn't follow immediately from your observation: there are uncountable linear orders with the countable predecessor property, such as the first uncountable ordinal $\omega_1$. However, the countable predecessor property does imply that $\mathcal{D}$ isn't linearly unless CH holds; it turns out that we can then use a couple bits of heavy set-theoretic machinery (here and here) to give a very silly proof of non-linearity.

*Does every pair of Turing degrees have a least upper bound? (Yes.) Greatest lower bound? (No.)

*Does every countable set of Turing degrees have an upper bound? (Yes.) A least upper bound? (No - in fact, basically never!)

*Does $\mathcal{D}$ have any nontrivial automorphisms? (Open, and maybe THE major open question!)

*EDIT: In response to "is there a known set of functions that are capable of generating all real numbers?," here is a very cute fact. Say that a Turing degree is minimal if it is nonzero (= doesn't consist of computable sets) but isn't strictly above anything nonzero. One might think that there are very few minimal degrees, and perhaps be surprised they exist in the first place; after knowing they exist, one might still reasonably think that there isn't much "strength" to be found in the minimal degrees. This turns out to be false, however: every Turing degree is below the least upper bound of some pair of minimal degrees. Rephrasing that, the set of functions of minimal Turing degree lets you compute every real!
There are also "local" questions. E.g. we can look at the substructure $\mathcal{R}$ consisting of Turing degrees of computably enumerable sets, and ask similar questions. Local problems are generally more complicated than global problems; for example, the nonlinearity of $\mathcal{D}$ was proved a decade before the nonlinearity of $\mathcal{R}$, and the proof of the latter required a fundamental new insight (the idea that different "requirements" in a construction can wind up interfering with each other, and how to manage this; this interference is called "injury" and proofs which deal with it are called "priority arguments").

A final side note: there's nothing in the argument you've rediscovered that needs computability specifically. Rather, there is a general fact that any specific reasonable notion of definability fails to capture all the reals (here "reasonable" means that definitions must be "finitary").
It turns out, however, that there are surprising subtle limits to this principle: most drastically, there are models of ZFC where every real is first-order definable (assuming ZFC is consistent in the first place, of course). The issue here is that first-order definability over the whole set-theoretic universe is far less well-behaved than computability, which in some sense is "local." So the obvious argument (which the linked article above calls the "math-tea argument") only applies to "concrete" situations. This isn't worth diving into deeply until you have a good understanding of basic computability theory and set theory, but it's good to know it exists down the road.

A: A finite set of oracles can only compute a countable set of real numbers, because there are only a countable number of algorithms. So, because the entire set of real number is uncountable, no finite set of oracles can compute (even with different algorithms) the entire set of real numbers.


Q: How to make sure there will be a fixed DB server across multiple deployments in Cloud Foundry? I am a newbie with CF microservices and I am trying to deploy a service multiple times. As far as I understood, each time I deploy into a space the application is getting a different database server and schema. Is there a way to tell the Cloud Foundry to use only a fixed DB server all the times across multiple deployments in one environment?

A: The keyword for your case is 'Service Instance'
You can create a service instance of database server within the environment specific for your application and bind it via application manifest.
e.g.
cf create-service rabbitmq small-plan myapplication-rabbitmq-instance

As long as you have a binding to myapplication-rabbitmq-instance in your application manifest it would be preserved/be the same between application deployments within this space.
e.g. in your application manifest:
---
...
  services:
   - myapplication-rabbitmq-instance

More on https://docs.cloudfoundry.org/devguide/services/


Q: how do you convert string into uppercase c++ I am not allowed to use toupper()
these are my functions, one function has to pass the string by reference.
void Uppercase(string x)
{
int y = 0;
while (y < x.length)
{
    x[y] = x[y] - 32;
    y++;
}
}

void uppercase(string &x)
{
int y = 0;
while (y < x.length)
{
    x[y] = x[y] - 32;
    y++;
}

Do I at least have the right idea?
I get this error when I build it....
Error   5   error C2446: '<' : no conversion from 'unsigned int (__thiscall std::basic_string,std::allocator>::* )(void) throw() const' to 'int'  c:\users\edwingomez\documents\visual studio 2013\projects\homework\homework\homework6.cpp   18  1   Homework

A: Since the restriction from using toupper strikes me as silly and counterproductive, I'd probably respond to such an assignment in a way that followed the letter of the prohibition while side-stepping its obvious intent, something like this:
#include <locale>
#include <iostream>

struct make_upper : private std::ctype < char > {
    void operator()(std::string &s){
        do_toupper(&s[0], &s[0]+s.size());
    }
};

int main() {
    std::string input = "this is some input.";
    make_upper()(input);
    std::cout << input;
}

This, of course, produces the expected result:
THIS IS SOME INPUT.

Unlike the other answers I see posted here, this still gains all the normal advantages of using toupper, such as working on a machine that uses EBCDIC instead of ASCII encoding.
At the same time, I suppose I should admit that (for one example) when I was in fifth grade I was once told to do something like "write 'I will not talk in class', 50 times." so I turned in a paper containing one sentence that read "I will not talk in class 50 times." Sister Mary Ellen (yes, Catholic schools) was not particularly pleased.

A: The std::transform function with a lambda expression is one way to do it:
std::string s = "all uppercase";
std::transform(std::begin(s), std::end(s), std::begin(s),
    [](const char& ch)
    { return (ch >= 'a' && ch <= 'z' ? ch - 32 : ch) });
std::cout << s << '\n';

Should output
ALL UPPERCASE

But only if the system is using the ASCII character set (or the ch - 32 expression will give unexpected results).

A: This is correct. But you should take care to add checks on the input. You could check if the characters are lowercase alphabets.
if (x[y] <= 'z') && (x[y] >= 'a')
    x[y] = x[y] - 32;

For readability, you should replace 32 by 'a' - 'A'.
Also, your first function does nothing. It creates a copy of the string. Does the required actions on it. And then discards it because you are not returning it, and the function ends.

A: Sample Code:

*

*With correct checks of the range.

*With C++11 version (using range-for-loop).

Note: the production version should be using toupper. But the OP specifically state that can't used.
Code:
#include <iostream>

const char upper_difference = 32;

void uppercaseCpp11(std::string& str) {
    for (auto& c : str) {
        if (c >= 'a' && c <= 'z')
            c -= upper_difference;
    }
}

std::string UppercaseCpp11(std::string str) {
    uppercaseCpp11(str);
    return str;
}

void uppercase(std::string& x) {
    for (unsigned int i = 0; i < x.size(); ++i) {
        if (x[i] >= 'a' && x[i] <= 'z')
            x[i] -= upper_difference;
    }
}

std::string Uppercase(std::string x) {
    uppercase(x);
    return x;
}

int main() {
    std::cout << Uppercase("stRing") << std::endl;
    std::string s1("StrinG");
    uppercase(s1);
    std::cout << s1 << std::endl;

    std::cout << UppercaseCpp11("stRing") << std::endl;
    std::string s2("StrinG");
    uppercaseCpp11(s2);
    std::cout << s2 << std::endl;

    return 0;
}

A:     string x = "Hello World";
    char test[255];
    memset(test, 0, sizeof(test));
    memcpy(test, x.c_str(), x.capacity());
    for (int i = 0; i < x.capacity(); i++)
    {
        if (test[i] > 96 && test[i] < 123)
            test[i] = test[i] - 32;
    }

    x.assign(test);


Q: Docker failing to add repository Universe I'm trying to add universe as a repository in my docker image:
RUN add-apt-repository "deb http://archive.ubuntu.com/ubuntu $(lsb_release -sc) universe"

RUN apt-get update

it errors with this output:
Step 4/24 : RUN add-apt-repository "deb http://archive.ubuntu.com/ubuntu $(lsb_release -sc) universe"
 ---> Running in 4c924d1455ed
Removing intermediate container 4c924d1455ed
 ---> b472a493f90c
Step 5/24 : RUN apt-get update
 ---> Running in d4e292c43bad
Ign:1 http://deb.debian.org/debian stretch InRelease
Hit:2 http://security.debian.org/debian-security stretch/updates InRelease
Hit:3 http://deb.debian.org/debian stretch-updates InRelease
Hit:4 http://deb.debian.org/debian stretch Release
Ign:5 http://archive.ubuntu.com/ubuntu stretch InRelease
Ign:6 http://archive.ubuntu.com/ubuntu stretch Release
Ign:8 http://archive.ubuntu.com/ubuntu stretch/universe all Packages
Ign:9 http://archive.ubuntu.com/ubuntu stretch/universe amd64 Packages
Ign:8 http://archive.ubuntu.com/ubuntu stretch/universe all Packages
Ign:9 http://archive.ubuntu.com/ubuntu stretch/universe amd64 Packages
Ign:8 http://archive.ubuntu.com/ubuntu stretch/universe all Packages
Ign:9 http://archive.ubuntu.com/ubuntu stretch/universe amd64 Packages
Ign:8 http://archive.ubuntu.com/ubuntu stretch/universe all Packages
Ign:9 http://archive.ubuntu.com/ubuntu stretch/universe amd64 Packages
Ign:8 http://archive.ubuntu.com/ubuntu stretch/universe all Packages
Ign:9 http://archive.ubuntu.com/ubuntu stretch/universe amd64 Packages
Ign:8 http://archive.ubuntu.com/ubuntu stretch/universe all Packages
Err:9 http://archive.ubuntu.com/ubuntu stretch/universe amd64 Packages
  404  Not Found [IP: 91.189.88.142 80]
Reading package lists...
W: The repository 'http://archive.ubuntu.com/ubuntu stretch Release' does not have a Release file.
E: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/stretch/universe/binary-amd64/Packages  404  Not Found [IP: 91.189.88.142 80]
E: Some index files failed to download. They have been ignored, or old ones used instead.
ERROR: Service 'api' failed to build: The command '/bin/sh -c apt-get update' returned a non-zero code: 100

My Docker file uses FROM python:2.7-slim as a base.
What am I doing wrong?

Results of cat /etc/os-release:
PRETTY_NAME="Debian GNU/Linux 9 (stretch)"
NAME="Debian GNU/Linux"
VERSION_ID="9"
VERSION="9 (stretch)"
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"

A: Since you're using debian as base OS image, then you cannot add ubuntu's repository as mentioned by Tarun Lalwani in comments.


Q: Regarding MATLAB slice function
This image represents my 3D array shown by using 'slice' function
My question is:

*

*As you can see from the image, there are 8 images in my 3D array (1mm~8mm)

however, each picture actually represents damage at 0 mm (surface) to 7 mm (z-axis)
So, how do I make z-axis value 0 to 7? instead of 1 to 8?
In the image I attached, you see 0 mm because I set:
    zlim([0 8])

However, there are still 8 images corresponding to 1mm to 8mm
Thank you!

A: As shown in the slice documentation:
[x,y,z] = meshgrid(-2:.2:2,-2:.25:2,-2:.16:2);
v = x.*exp(-x.^2-y.^2-z.^2);
xslice = [-1.2,.8,2];
yslice = 2;
zslice = [-2,0];
slice(x,y,z,v,xslice,yslice,zslice)
colormap hsv

You can pass the coordinate system as the first three arguments to slice, then express the slice locations in this coordinate system, so in your case:
[x,y,z] = meshgrid(0:100,0:100,0:7);
slice(x,y,z,xslice,yslice,zslice)

Where you'd express zslice in the range [0,7] when defining your desired slice locations.


Q: a separable hilbert space and closed hyperplan let $H$ be a separable hilbert space of infinite dimension and let $K$ a closed hyperplan .
I want to show that $H$ is homeomorphic to $K$ .

A: $K$ is an infinite dimensional separable Hilbert space, endowed with the restriction of the scalar product of $H$. The completeness follows from the fact that $K$ is closed.
There exists a bijective isometry between any infinite dimensional separable Hilbert space and $l^2$. Therefore there exists a bijective isometry between $H$ and $K$.


Q: How to use Swashbuckle to generate global parameters in the resulting Swagger file? There are currently ways to add parameters to every path via Swashbuckle. Some such way can be found here.
Let's say I want to add a parameter to every path called 'api-version'. Then this parameter will appear in every path in the Swagger file.
I want Swashbuckle to generate a single global parameter. For example, instead of this
{
    "swagger": "2.0",
    "paths": {
      "/something": {
        "post": {
          "operationId": "something_do",
          "parameters": [
            {
              "name": "api-version",
              "in": "query",
              "description": "The API version.",
              "required": true,
              "type": "string"
            }
          ],
          "responses": {
            "200": {
              "description": "Something got done.",
              "schema": {
                "type": "string"
              }
            }
          }
        }
      }
    }
  }

, I want
{
    "swagger": "2.0",
    "paths": {
        "/something": {
            "post": {
                "operationId": "something_do",
                "responses": {
                    "200": {
                        "description": "Something got done.",
                        "schema": {
                            "type": "string"
                        }
                    }
                }
            }
        }
    },
    "parameters": {
        "ApiVersionParameter": {
            "name": "api-version",
            "in": "query",
            "required": true,
            "type": "string",
            "description": "The API version."
        }
    }
}

with the parameter set globally, and not under every path. I'm unable to find anything under SwaggerGenOptions that produces this.

A: Thank you Helder. The IDocumentFilter works.
public class GlobalParameterDocumentFilter : IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            if (swaggerDoc != null && swaggerDoc.Components != null)
            {
                swaggerDoc.Components.Parameters.Add(ApiConstants.ApiVersionGlobalParamName, new OpenApiParameter
                {
                    Name = "api-version",
                    In = ParameterLocation.Query,
                    Required = true,
                    Schema = new OpenApiSchema { Type = "string" },
                    Description = "The API version"
                });
            }
        }
    }

The path parameter can then reference this global parameter via an IOperationFilter.
    public class OperationFilter : IOperationFilter
        {
            public void Apply(OpenApiOperation operation, OperationFilterContext context)
            {
                _ = operation ?? throw new ArgumentNullException(nameof(operation));
                _ = context ?? throw new ArgumentNullException(nameof(context));

                if (operation.Parameters == null)
                {
                    operation.Parameters = new List<OpenApiParameter>();
                }

                operation.Parameters.Add(
                    new OpenApiParameter
                    {
                        Reference = new OpenApiReference { Id = "parameters/api-version", ExternalResource = "" }
                    });
            }
}


Q: Making a symbolic function callable -- sympy I'd like to calculate the derivative, then solve for when it is zero.
I am using the sympy module to do this.
r = somefunction(x1,x2)

Using this function, I'd like to be able to call these two matrices.
r_grad = [r.diff(x1), r.diff(x2)]
r_hess = [[r.diff(x1,x1), r.diff(x1,x2)],[r.diff(x2,x1), r.diff(x2,x2)]]

I'd then like to solve for when r_grad[0] and r_grad[1] == 0, and plug that into the hessian.
How can I make these .diff() symbols callable?

A: SymPy has a lambdify module for these purposes:
from sympy.utilities.lambdify import lambdify

func = lambdify((x1, x2), r.diff(x1))

func(1, 2) # evaluate the function efficiently at (1, 2)


Q: Overwriting lines in text file I want to overwrite lines in a file without losing the data. The program starts by writing data separated by tabs into a "students2.txt" file.
filename = "students2.txt"
file_write = open(filename, "a")

num_of_students = int(input("Enter number of students: "))
for i in range(1, num_of_students + 1):
    print("Student", i)
    first_name = input("Enter your first name: ")
    last_name = input("Enter your last name: ")
    matric_no = input("Enter your matric number: ")
    print("Input attendance")
    mar_4 = int(input())
    mar_11 = int(input())
    mar_18 = int(input())
    mar_25 = int(input())
    file_write.write(first_name.title() + "\t")

    file_write.write(last_name.title() + "\t")
    file_write.write(matric_no.upper() + "\t")
    file_write.write(str(mar_4) + "\t")
    file_write.write(str(mar_11) + "\t")
    file_write.write(str(mar_25) + "\t")
    file_write.write(str(mar_18) + "\t" + "\n")
file_write.close()

Then it reads from that file and performs some calculations
file_read = open("students2.txt", "r")
file_write = open("students2.txt", "a")
for i in file_read.readlines():
    i = i.strip().split()
    std_sum = int(i[3]) + int(i[4]) + int(i[5]) + int(i[6])
    std_attd_percent = (std_sum/4) * 100
    file_write.write(str(std_attd_percent))

I want to write the std_attd_percent to each line of the "student2.txt" but it just writes it all to the end of the line.


Q: Efficient tree-based dialogue system? I'm working on a simple tree based dialogue system. its a basic game of click to advance the story, with different choice to choose, leading player to a different story path.
What I did was, I create a plethora of gameObject called Convo. Each Convo contain Text(Component) , and Children to determine which character is on screen, and a tag in those child to display their inflection(ex. sad happy etc.).
Ex

*

*A-0-1 (Text: " John: Hey, what's going on?") (with tag "Choice" if it's the last convo)

*

*John(with tag "Idle")

*Jane(with tag "Irritated")

Story path picture
There's 2 variable: CurrentDialogue(string) and DialogueTracking(int).
On each click, I check if current convo has tag "Choice". If there isn't, I use CurrentDialogue(string) to find gameobject with exact name and display it's text. then increase DialogueTracking by one,
then I modified CurrentDialogue(string) from  A-0-1 to A-0-2 and so on using DialogueTracking, and When there's tag "choice" (Ex.A-0-4) , DialogueTracking(int) get reset to one, so it's A-1-1 instead of A-1-5 after player choose a choice.
Here's the problem, after a lot of convo and many story path, I realize my newbie mistake. The code turn into big o' if/else,(the comparing of which choice go which path)
I'm quite new to programming and unity, If anyone could guide me in the right direction on ways to help me learn how to create this system to be clean and efficient , that would be really great!
Thank you!

A: I would suggest making DialogueManager Component that will hold all of your dialogues and each of these should hold reference to other dialogues. Then after displaying dialogue you can check if it has multiple children or just one ( or none ) and display some dialog/popup to choose from keys of these.
In code example it would be like :
[Serializable]
public class Dialogue
{
    [SerializeField]
    Dictionary<string, Dialogue> _dialogues;

    [SerializeField]
    string _dialogueText;

    public Dialogue(string text)
    {
        _dialogues = new Dictionary<string, Dialogue>();
        _dialogueText = text;
    }

    public string GetText() { return _dialogueText; }

    public bool HasManyPaths() { return _dialogues.Count > 1; }

    public string[] GetKeys() { return _dialogues.Keys; }

    public Dialogue GetDialogue(string key) { return _dialogues[key]; }
}

Now you should fill this within your Unity inspector and make DialogueManager Component to manage your Dialogues :
public class DialogueManager
    : Component
{
    [SerializeField]
    Dialogue _currentDialogue;

    public void InitializeDialogue()
    {
        string text = _currentDialogue.GetText();
        // display the text
        if ( _currentDialogue.HasManyPaths() )
        {
            string[] keys = _currentDialogue.GetKeys();
            // display keys;
            string selected_key = // user input here
            _currentDialogue = _currentDialogue.GetDialogue(selected_key);
        }
        else
        {
            string key = _currentDialogue.GetKeys()[0];
            _currentDialogue = _currentDialogue.GetDialogue(key);
        }
    }
}

Using this method you can simply make your dialogues inside Unity editor and add MonoBehaviour script with something like this :
public void Start()
{
    GetComponent<DialogueManager>().InitializeDialogue();
}

Simple example of making dialogue tree would be :
{ currentDialogue [ "hello! choose 1 or 2" ]
    1.{ dialogue [ "you've chosen 1" ]
        . { dialogue [ "this ends dialogue" ] }
    }
    2. { dialogue [ "you've chosen 2" ]
        . { dialogue [ "now choose another number between 3 and 4" ]
            3. { dialogue [ "you've chosen 3" ] }
            4. { dialogue [ "you've chosen 4" ] }
         }
     }
}


Q: Cakephp3 sending mails - no result I'm trying to send email via cakephp3.
This is my app email config:
'EmailTransport' => [
    'default' => [
        'className' => 'Mail',
        // The following keys are used in SMTP transports
        'host' => 'localhost',
        'port' => 25,
        'timeout' => 30,
        'username' => 'user',
        'password' => 'secret',
        'client' => null,
        'tls' => null,
    ],
],

And this is controller :
public function index() {
    $this->autoRender = false;
    $email = new Email('default');

    if (
    $email->from(['mymail@gmail.com' => 'My Site'])
        ->to('mymail@gmail.com')
        ->subject('About')
        ->send('My message')) {
        print 'ok';
    }
}

And now, if i run this function, result is printed 'ok' on monitor.
But no mail is on my testing email box, even span, nothing.
My question is, why cakephp tells me that sending was done, but no mail is present on my box ?
Thank You.

A: Your configuration is incorrect. cakePHP attempts to send the e-mail via smtp to your localhost.
Most likely you do not have an MTA (ie. exim, dovecot) installed locally and the request gets dropped. This should be visible as an error in you logs (if enabled).
An easy solution is to change the configuration to a working email service for testing, for example Gmail.
Example:
Email::configTransport('gmail', [
  'host' => 'smtp.gmail.com',
  'port' => 587,
  'username' => 'my@gmail.com',
  'password' => 'secret',
  'className' => 'Smtp',
  'tls' => true
]);

Note that the host and port point to Gmail. This example is indicative and was taken from the official documentation.
More information on configuring email transports in cakePHP 3.0 here: http://book.cakephp.org/3.0/en/core-libraries/email.html#configuring-transports


Q: Rx sliding windows - proper cleanup? I've been trying to build a circuit breaker that can be configured to trip with compound rules like:

*

*2 timeout exceptions within 45 seconds; or

*50 of any other type of exception within 5 minutes

so figured the best way to do this was with sliding windows (or time-buffers whatever you want to call them).
Based on what I could find online and piece together myself I wrote this simple console app:
static IEnumerable<ConsoleKeyInfo> KeyPresses()
{
    ConsoleKeyInfo key;
    do
    {
        key = Console.ReadKey();
        yield return key;
    } while (key.Key != ConsoleKey.Escape);
}

static IObservable<int> TimeLimitedThreshold<T>(IObservable<T> source, TimeSpan timeLimit, int threshold)
{
    return source.Window(source, _ => Observable.Timer(timeLimit))
        .Select(x => x.Count())
        .Merge()
        .Where(count => count >= threshold)
        .Take(1);
}

static void Main(string[] args)
{
    Console.WriteLine("Starting");

    var timeLimit = TimeSpan.FromSeconds(5);
    const int threshold = 3;
    var keys = KeyPresses().ToObservable(Scheduler.Default).Publish().RefCount();

    var thresholdHit = TimeLimitedThreshold(keys, timeLimit, threshold);
    thresholdHit.Subscribe(count => Console.WriteLine("THRESHOLD BREACHED! Count is: {0}", count));

    // block the main thread so we don't terminate
    keys.Where(key => key.Key == ConsoleKey.Escape).FirstAsync().Wait();
    Console.WriteLine("Finished");
}

(If I should put that in a gist or pastebin instead of in the question please just say so)
Now this seems to do what I want, if I press any key 3 or more times within 5 seconds the "THRESHOLD BREACHED!!!" is printed once and nothing more happens.
My questions are:

*

*Is the TimeLimitedThreshold function at a sensible level of abstraction for when working with Rx.Net?

*Should I be injecting the scheduler to use when creating the Observable.Timer()?

*What cleanup am I missing if any? Memory usage when it comes to Rx.NET really baffles me.

A: I would probably write the threshold function the following way, taking advantage of the Timestamp combinator.
    public static IObservable<U> TimeLimitedThreshold
        <T,U>
        ( this IObservable<T> source
        , int count
        , TimeSpan timeSpan
        , Func<IList<T>,U> selector
        , IScheduler scheduler = null
        )
    {
        var tmp = scheduler == null
            ? source.Timestamp()
            : source.Timestamp(scheduler);

        return  tmp
             .Buffer(count, 1).Where(b=>b.Count==count)
             .Select(b => new { b, span = b.Last().Timestamp - b.First().Timestamp })
             .Where(o => o.span <= timeSpan)
             .Select(o => selector(o.b.Select(ts=>ts.Value).ToList()));
    }

As an added convenience when the trigger is fired the complete buffer that satisfies the trigger is provided to your selector function.
For example
 var keys = KeyPresses().ToObservable(Scheduler.Default).Publish().RefCount();
 IObservable<string> fastKeySequences = keys.TimeLimitedThreshHold
     ( 3
     , TimeSpan.FromSeconds(5)
     , keys => String.Join("", keys)
     );

The extra IScheduler parameter is given as the Timestamp method has an extra overload which takes one. This might be useful if you want to have a custom scheduler which doesn't track time according to the internal clock. For testing purposes using an historical scheduler can be useful and then you would need the extra overload.
and here is a fully working test showing the use of a schedular. ( using XUnit and FluentAssertions for the Should().Be(..) )
public class TimeLimitedThresholdSpec  : ReactiveTest
{

    TestScheduler _Scheduler = new TestScheduler();
    [Fact]
    public void ShouldWork()
    {
        var o = _Scheduler.CreateColdObservable
            ( OnNext(100, "A")
            , OnNext(200, "B")
            , OnNext(250, "C")
            , OnNext(255, "D")
            , OnNext(258, "E")
            , OnNext(600, "F")
            );

        var fixture = o
            .TimeLimitedThreshold
                (3
                , TimeSpan.FromTicks(20)
                , b => String.Join("", b)
                , _Scheduler
                );

        var actual = _Scheduler
            .Start(()=>fixture, created:0, subscribed:1, disposed:1000);
        actual.Messages.Count.Should().Be(1);
        actual.Messages[0].Value.Value.Should().Be("CDE");

    }

}

Subscribing and is the following way
IDisposable subscription = fastKeySequences.Subscribe(s=>Console.WriteLine(s));

and when you want to cancel the subscription ( clean up memory and resources ) you dispose of the subscription. Simply.
subscription.Dispose()

A: Here's an alternative approach that uses a single delay in favour of buffers and timers. It doesn't give you the events - it just signals when there is a violation - but it uses less memory as it doesn't hold on to too much.
public static class ObservableExtensions
{
    public static IObservable<Unit> TimeLimitedThreshold<TSource>(
        this IObservable<TSource> source,
        long threshold,
        TimeSpan timeLimit,
        IScheduler s)
    {
        var events = source.Publish().RefCount();
        var count = events.Select(_ => 1)
                        .Merge(events.Select(_ => -1)
                                    .Delay(timeLimit, s));
        return count.Scan((x,y) => x + y)
                    .Where(c => c == threshold)
                    .Select(_ => Unit.Default);
    }
}

The Publish().RefCount() is used to avoid subscribing to the source more than one. The query projects all events to 1, and a delayed stream of events to -1, then produces a running total. If the running total reaches the threshold, we emit a signal (Unit.Default is the Rx type to represent an event without a payload). Here's a test (just runs in LINQPad with nuget rx-testing):
void Main()
{
    var s = new TestScheduler();
    var source = s.CreateColdObservable(
        new Recorded<Notification<int>>(100, Notification.CreateOnNext(1)),
        new Recorded<Notification<int>>(200, Notification.CreateOnNext(2)),
        new Recorded<Notification<int>>(300, Notification.CreateOnNext(3)),
        new Recorded<Notification<int>>(330, Notification.CreateOnNext(4)));

    var results = s.CreateObserver<Unit>();

    source.TimeLimitedThreshold(
        2,
        TimeSpan.FromTicks(30),
        s).Subscribe(results);

    s.Start();

    ReactiveAssert.AssertEqual(
        results.Messages,
        new List<Recorded<Notification<Unit>>> {
            new Recorded<Notification<Unit>>(
                330, Notification.CreateOnNext(Unit.Default))
        });
}

Edit
After Matthew Finlay's observation that the above would also fire as the threshold is passed "on the way down", I added this version that checks only for threshold crossing in the positive direction:
public static class ObservableExtensions
{
    public static IObservable<Unit> TimeLimitedThreshold<TSource>(
        this IObservable<TSource> source,
        long threshold,
        TimeSpan timeLimit,
        IScheduler s)
    {
        var events = source.Publish().RefCount();
        var count = events.Select(_ => 1)
                        .Merge(events.Select(_ => -1)
                                    .Delay(timeLimit, s));

        return count.Scan((x,y) => x + y)
                    .Scan(new { Current = 0, Last = 0},
                          (x,y) => new { Current = y, Last = x.Current })
                    .Where(c => c.Current == threshold && c.Last < threshold)
                    .Select(_ => Unit.Default);
    }
}


Q: Descending Sorting of an ArrayList of Object I need to sort this ArrayObject :
public ArrayList<WPPost> posts;

on descending :
posts.get(i).getRating()

I have tried with HashMaps, LinkedHashMaps, I haven't found anything. What's the best solution ?

A: I think that one of the best solutions is the use of Collections.sort
    Collections.sort(posts, new Comparator<WPPost>() {
        @Override
        public int compare(WPPost o1, WPPost o2) {
            return o2.getRating() - o1.getRating();
        }
    });

In some implemetations Collectios sort use merge sort algorithm, that will give you a O(log n) complexity.


Q: Flex box how to specify the column for item placement I have a software which creates the repeatable blocks. They use flexbox. Currently, they align based on the position of the repeatable block, stacked below each item. Say in the image below if the repeatable blocks are item1, item2, item3, item4. It will render the column with the same order.
But I want to allow the user to have a multi-column option. I can use the grid and considering it is something dynamic I cant use that. Say I can assign the grid-item property to item 1 as firstone and create  grid-template-areas:"firstone secondone" but assigning the item2, item3 with grid-item secondone will have content placed one over each other.
grid-template-areas:"firstone secondone" "firstone secondone" "firstone secondone" will do the trick but I don't have a method to generate this CSS there can be more than 4 items.
Any possible solution? Alternatives?

A: Using a grid for these problems is the right choice! What you are trying to achieve is a bit more complex than the use case of flexbox.
By using grid-template-columns instead of grid-template-areas, and the :first-child selector, it it possible to achieve what you describe.
Given this example HTML:

Item 1

Item 2

Item 3

Item 4

You can use this CSS:
div {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

article {
  grid-column: 2;
}

article:first-child {
  grid-column: 1;
}

Have a look at this fiddle to see an example.
https://jsfiddle.net/h9k5x7uf/
If you want to make this more dynamic or server rendered, replace :first-child with some helper classes instead.
.pull-left { grid-column: 1; }
.pull-right { grid-column: 2; }


Q: In app purchase with hosted content does not work when live Recently I have published application with in-app purchase to App Store. In-app purchase contains hosted content. This purchase item was fully tested with sandbox users and with beta testers as well. But when we go live this item does not work. Payments for this purchase was withdrawn, but content is still locked. I can fetch selected product and his price in App Store build.
Also, I am wondering that all works great using sandbox user, works for all beta and internal testers, but does not work in app downloaded from App Store. This even works after switching back to sandbox.
In-app purchase is approved, content inside is valid, application is ready for sale.
Are there some differences between in-app purchase configuration for App Store build and TestFlight/installed from Xcode one?
Thanks for your time.

A: This appears to be an issue on Apple's servers that started a few days ago. See this forum thread:
https://forums.developer.apple.com/thread/80546
Apple's server team is said to be addressing it now. Here's a quote from an Apple staff member on that thread:
"I've forwarded all of these bug reports to the Apps Ops Engineering QA team for thei review. For everyone else, by all means submit bug reports, but at this point, I'm not going verify that the bug reports are passed on to Apps Ops Engineering QA. The server team's attention is now on this issue."


Q: Directions to the Algebra Zoo? Is there a good resources that lists known algebraic structures? I'm thinking of something like Scott Aaronson's Complexity Zoo or the OEIS, both of which have entries for various complexity classes/integer sequences, their properties, and relationships among them. You can cobble together something like this from the Wikipedia page on Algebraic Structures, but I was hoping there was something more comprehensive.
To clarify, I'm looking for something that has lots of specific examples of rings, groups, lattices, etc, not just a list of the various kinds.

A: It only applies to groups, but Groupprops ("The Group Properties Wiki") records numerous properties for a large selection of important groups.


Q: How to preserve Client IP Address with GKE Ingress controller on Kubernetes? I would like to catch the Client IP Address inside my .NET application running behind GKE Ingress Controller to ensure that the client is permitted.
var requestIpAddress = request.HttpContext.Connection.RemoteIpAddress.MapToIPv4();

Instead of getting Client IP Address I get my GKE Ingress IP Address, due to The Ingress apply some forwarding rule.
The GKE Ingress controller is pointing to the Kubernetes service of type NodePort.
I have tried to add spec to NodePort service to preserve Client IP Address but it doesn't help. It is because the NodePort service is also runng behind the Ingress
externalTrafficPolicy: Local

Is it possible to preserve Client IP Address with GKE Ingress controller on Kubernetes?
NodePort Service for Ingress:
apiVersion: v1
kind: Service
metadata:
  name: api-ingress-service
  labels:
    app/name: ingress.api
spec:
  type: NodePort
  externalTrafficPolicy: Local
  selector:
    app/template: api
  ports:
  - name: http
    protocol: TCP
    port: 80
    targetPort: http

Ingress:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress
  namespace: default
  labels:
    kind: ingress
    app: ingress
  annotations:
    networking.gke.io/v1beta1.FrontendConfig: frontend-config
spec:
  tls:
  - hosts:
    - '*.mydomain.com'
    secretName: tls-secret
  rules:
  - host: mydomain.com
    http:
      paths:
      - path: /*
        pathType: ImplementationSpecific
        backend:
          service:
            name: api-ingress-service
            port:
              number: 80

A: Posted community wiki for better visibility. Feel free to expand it.

Currently the only way to get the client source IP address in GKE Ingress is to use X-Forwarded-For header. It's known limitation for all GCP HTTP(s) Load Balancers (GKE Ingress is using External HTTP(s) LB).
If it does not suit your needs, consider migrating to a third-party Ingress Controller which is using an external TCP/UDP network LoadBalancer, like NGINX Ingress Controller.


Q: history.push not working in wait or sync until button click I try to navigate page without refresh using "history.push()" It only work, when it clicked by human via button. It won't work programmatically . It is is only updating url but not navigating in browser.
//Index.js
ReactDOM.render(<Router history={history}><App /></Router>, document.getElementById('root'));

//App.js
      <Switch>
          <Route path="/" exact strict component={Login}/>
          <Route  path="/Homepage" exact strict component={Homepage}/>
      </Switch>

//History.js
import {createBrowserHistory} from 'history'
export default createBrowserHistory();

Working fine, When clicked directly using button.
//Working
  function btnClick(){
      history.push('/Homepage');
      }

Not working, When it is inside sync or wait function.
//Not Working
  const wait=ms=>new Promise(resolve => setTimeout(resolve, ms));
     wait(4*1000).then(() => {
      history.push('/Homepage');
      });

A: You aren't setting the history on your Router correctly
<Router history={history} />


Q: pass string array out of function in c I have a function that I'm using to build a string array. Inside the function i can print the array no worries however the program returns from the called function, the array (arr) remains NULL.
How do I get the data out of the array ?
Thanks.
main(){
  char **arr = NULL;
  funct(arr);
  printf("%s\n", arr[2];
}

funct(char **arr){
  arr = malloc(10*sizeof(char *));
  arr[1...n] = calloc(SIZE, sizeof(char));
  // Add data to array
}

A: I can see several problemens in your code:

*

*in the line   printf("%s\n", arr[2]; you forgot a closing )

*Your arr variable local to the main function is never initialized. In C, parameters are passed by value meaning that you are passing the NULL pointer to your function and inside this function, the local pointer arr is allocated but not the one of the main function.

The solution is to allocate the array in the main function and pass a pointer to the array and the size to the function that fills it:
main(){
  char **arr = malloc(10*sizeof(char *));
  funct(arr, 10);
  printf("%s\n", arr[2]);
}

funct(char **arr, int size){
  // Add data to array
  arr[0] = "first data";
  ....
  arr[size -1] = "last data";
}


Q: Programmatically grant a user the ability to log on using remote desktop I have several Windows Server 2022 hosts that I need to manage the user rights assignment through automation.
When I manually grant a domain user SeRemoteInteractiveLogonRight rights, they cannot log on using remote desktop, they receive an error stating they are not authorized. If I grant them membership in the local Remote Desktop Users group, they can log on successfully.
The Remote Desktop Users group is granted the SeRemoteInteractiveLogonRight right, but no other rights.
What other permission has that group been granted that I would also need to grant to individual users to enable the ability?

A: SeRemoteInteractiveLogonRight is a Privilege (you can grant this privilege with the following policy: Allow log on through Remote Desktop Services). As the documentation says:

This policy setting determines which users or groups can access the
logon screen of a remote device through a Remote Desktop Services
connection[...]

Great! However, as you saw it, the users still receives an error message unless they are members of Remote Desktop Users. That's documented too:

To use Remote Desktop Services to successfully log on to a remote
device, the user or group must be a member of the Remote Desktop Users
or Administrators group and be granted the Allow log on through Remote
Desktop Services right.[...]

Well, this is because there are (at least) two layers:

*

*The Remote Desktop Service security descriptor: Remote Desktop service has its own access list.

*The SeRemoteInteractiveLogonRight privilege

The order is relevant here: The user connects to Remote Desktop Services first, and if this is allowed, then Windows will check that the user's token holds the SeRemoteInteractiveLogonRight before opening the user's session.
You can see the Remote Desktop Service security descriptor in the Win32_TSPermissionsSetting WMI class (StringSecurityDescriptor for RDP-Tcp). For example, you can give the StringSecurityDescriptor to the Powershell cmdlet ConvertFrom-SddlString to see its content in a prettier format :
$sddl = Get-WmiObject -class win32_tspermissionssetting -Namespace root\cimv2\terminalservices | where {$_.TerminalName -eq "RDP-Tcp"} |select StringSecurityDescriptor

ConvertFrom-SddlString -Sddl $sddl.StringSecurityDescriptor | select -ExpandProperty DiscretionaryAcl

The output will show you that the Remote Desktop Users group is allowed by default:
[...]
Remote Desktop Users: AccessAllowed
[...]

Basically, granting SeRemoteInteractiveLogonRight will not add the user/group to the Remote Desktop security descriptor, so, Remote Desktop Services denies the logon before Windows even had to check if the SeRemoteInteractiveLogonRight was granted.
You can manually add users or groups in the Remote Desktop Services security descriptor with the AddAccount method: the SDDL will be modified and you'll see your account/group in it. If you granted the SeRemoteInteractiveLogonRight privilege, then you should be able to log on (unless other restrictions are effective on this computer or user, of course).
Now, what happens if you add a user in the Remote Desktop Service security descriptor, without granting SeRemoteInteractiveLogonRight? Well, Remote Desktop Services will accept the connection, but you'll see an error when Windows tries to open your session, and as you can see, this is not an error thrown by the RDP client, the graphics channel is opened and the error is shown by the remote computer:

And that's what the security auditing logs tells us in this case (if you are auditing):

You'll not see this event if the user is not allowed to connect according to the Remote Desktop Service security descriptor because the logon operation fails before Windows had a chance to check privileges.
I strongly recommend you to use the Remote Desktop Users group, because this group is present by default in the Remote Desktop service security descriptor, and is allowed to use the SeRemoteInteractiveLogonRight privilege (unless the server is a DC). You should not need to fiddle with the RDS security descriptor.


Q: Way to disable count query from PageRequest for getting total pages? We are using Spring Data with the PageRequest and hitting a significantly large set of data.  All queries perform optimally except the query being executed to get the total number of pages.  Is there a way to disable this feature or would we most likely have to implement our own Pageable?
http://static.springsource.org/spring-data/data-commons/docs/1.3.2.RELEASE/api/org/springframework/data/domain/PageRequest.html
http://static.springsource.org/spring-data/data-commons/docs/1.3.2.RELEASE/api/org/springframework/data/domain/Pageable.html
Edit:  After further analysis I believe the only way around this problem is to not use Spring Data and use EntityManager as it allows setting of start row and number of records to return.  We only need whether next page is available so we just retrieve one extra record.  We also need a dynamic query which doesn't seem possible in Spring Data.
Edit 2: And it would seem I just didn't wait long enough for some responses.  Thanks guys!!!

A: The way to achieve this is simply by using List as return value. So for example for a repository defined like this:
interface CustomerRepository extends Repository<Customer, Long> {

  List<Customer> findByLastname(String lastname, Pageable pageable);
}

The query execution engine would apply the offset and pagesize as handed in by the Pageable but not trigger the additional count query as we don't need to construct a Page instance. This also documented in the relevant sections of the reference documentation.
Update: If you want the next page / previous page of Page but still skip the count query you may use Slice as the return value.

A: I was able to avoid the count performance degradation in a dynamic query (using Spring Data Specifications) with the base repository solution indicated in several post.
public class ExtendedRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements ExtendedRepository<T, ID> {

    private EntityManager entityManager;

    public ExtendedRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
        super(entityInformation, entityManager);
        this.entityManager = entityManager;
    }

    @Override
    public List<T> find(Specification<T> specification, int offset, int limit, Sort sort) {
        TypedQuery<T> query = getQuery(specification, sort);
        query.setFirstResult(offset);
        query.setMaxResults(limit);
        return query.getResultList();
    }

}

A query to retrieve 20 record slices, from a 6M records dataset, takes milliseconds with this approach. A bit over the same filtered queries run in SQL.
A similar implementation using Slice<T> find(Specification<T> specification, Pageable pageable) takes over 10 seconds.
And similar implementation returning Page<T> find(Specification<T> specification, Pageable pageable) takes around 15 seconds.

A: I had recently got such a requirement and the latest spring-boot-starter-data-jpa library has provided the out-of-box solution. Without count feature pagination can be achieved using org.springframework.data.domain.Slice interface.
An excerpt from blog

Depending on the database you are using in your application, it might become expensive as the number of items increased. To avoid this costly count query, you should instead return a Slice. Unlike a Page, a Slice only knows about whether the next slice is available or not. This information is sufficient to walk through a larger result set.
  Both Slice and Page are part of Spring Data JPA, where Page is just a sub-interface of Slice with a couple of additional methods. You should use Slice if you don't need the total number of items and pages.

@Repository
public interface UserRepository extends CrudRepository<Employee, String> {

    Slice<Employee> getByEmployeeId(String employeeId, Pageable pageable);

}

Sample code-snippet to navigate through larger result sets using Slice#hasNext. Until the hasNext method returns false, there is a possibility of data presence for the requested query criteria.
        int page = 0;
        int limit = 25;
        boolean hasNext;
        do {
            PageRequest pageRequest = PageRequest.of(page, limit );
            Slice<Employee> employeeSlice = employeeRepository.getByEmployeeId(sourceId, pageRequest);
            ++page;
            hasNext = employeeSlice .hasNext();
        } while (hasNext);