text:
Q: Fibonacci code for loop not returning values I'm trying to make a code where you input a number n and the code returns you the number in the Fibonacci sequence.
Example:
When inputting n = 1 the code returns 1, and when you input n = 2 the code returns 1, and when you input n = 3 the code returns 2, and so on.
I'm quite a beginner with javascript so I don't know exactly how to do this.
<html>
<body>
    <script type="text/javascript">
    function fibonacci(){
    var a, b, n, result;
    a = 0;
    b = 1;
    for (var i = 0; i <= n; i++)
    {
        if(n == 1)
        {
            return 1;
        }
        if(n == 0)
        {
            return 0;
        }
        result = a + b;
        a = b;
        b = result;

    }
    document.getElementById("result").value = result;
    }
    </script>
    <form>
        <input id="n" type="number" placeholder="N">
        <input id="result" type="number" placeholder="Result" readonly="">

        <input id="calculate" type="button" value="Calculate" onclick="fibonacci()">
        <input type="reset" value="Clear">
    </form>
</body>
</html>

A: You didn't initialized n, right?
Add this line before for loop.
n =  document.getElementById("n").value

Check your browser console for errors, it shows this kind of errors correctly..

A: *

*You should initialize n.

*Then remove n==0 and n==1 from for loop block.

*Update your code following,

<html>
<body>
    <script type="text/javascript">
    function fibonacci(){
    var n = document.getElementById("n").value;
    var result;
    var a = 0;
    var b = 1;
    if(n == 0 || n == 1)
    {
        result = n;
    }
    else{
      for (var i = 2; i <= n; i++)
      {
          result = a + b;
          a = b;
          b = result;

      }
    }
    document.getElementById("result").value = result;
    }
    </script>
    <form>
        <input id="n" type="number" placeholder="N">
        <input id="result" type="number" placeholder="Result" readonly="">

        <input id="calculate" type="button" value="Calculate" onclick="fibonacci()">
        <input type="reset" value="Clear">
    </form>
</body>
</html>


text:
Q: 17.10 seahorse-nautilus mime association for "decrypt file", getting really frustrated at the ubuntu way I'm a proficient linux user, just recently I've been learning how to deploy server with ansible+vagrant so I just spent an entire week on centOS and various other flavour of linux getting a complex network to work.
I require to encrypt decrypt from nautilus context menu, I installed seahorse-nautilus and everything went fine, I created a key and everything is working, then I accidentally opened a .pgp file with textedit selecting open with from nautilus and this changed the mime association.
I cant't figure where does ubuntu actually stores mime association and I can't even find anymore decent documentation and specs about everything that ubuntu does its own way.
can't find where it changed it now, looked at all the usual places for mime associations and couldn't find the added association between pgp and textedit. I uninstalled seahorse-nautilus and reinstalled it (including a nautilus -q) but no luck, the text edit mime association stays.
can somebody please explain to me where does ubuntu adds mime association made with nautilus when you click open with application and how to either prevent that from happening or change it afterwards?
I'm getting really frustrated at ubuntu in recent years, seems like it's not even linux anymore and this might really be the last drop, might go to real linux like arch in the next couple days and forget this bloatware that ubuntu has become.
I checked
/usr/share/applpications/ etc. etc.
$HOME/.local/share/ etc.
/usr/share/gdm/greeter etc.
found many different config file holding mime association but nothing regarding pgp.
please help

A: Did you check ~/.config/mimeapps.lst ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Probability of red cards A Person takes 26 cards at random from a 52-card deck, and He give those to and asks me to draw out 2 cards in a row without replacement . What is the probability that the both cards I draw will be the red cards?

A: The same as when you pick the two cards from the original 52 cards. Taking the 26 cards is irrelevant.
So the answer is $26 / 52 \cdot 25 / 51 = 25 / 102.$ Note that $26 / 52 = 1/2$ is the probability that the first card is red, and $25 / 51$  is the probability that the second card is red, given that the first was, as 25 of the remaining 51 cards are red.


text:
Q: PGFPlots: How to sort the bars based on y values? I have a bar chart that looks like this:

Here is the code that I used to generate the plot:
\begin{tikzpicture}
\begin{axis}[
    enlarge x limits=0.03,
    every axis plot post/.style={/pgf/number format/fixed},
    ybar=1pt,
    ylabel=F1 Score,
    xlabel=objects,
    bar width=10pt,
    x=0.45cm,
    ymin=0,
    axis on top,
    ymax=1,
    xtick= \empty,
    xticklabel style={rotate=-90,  xshift=0.2cm},
   symbolic x coords={barkely hide bones,
cherokee easy tee-shirt,
clorox utility brush,
cloud b plush bear,
command hooks,
cool shot glue sticks,
crayola 24 ct,
creativity chenille stems ,
dasani water bottle,
dove beauty bar,
dr browns bottle brush,
easter turtle sippy cup ,
elmers washable no run school glue ,
expo dry erase board eraser ,
fiskars scissors red,
fitness gear 3lb dumbbell,
folgers classic roast coffee,
hanes tube socks,
i am a bunny book,
jane eyre dvd,
kleenex paper towels,
kleenex tissue box,
kyjen squeakin eggs plush puppies,
laugh out loud joke book,
oral b toothbrush green,
oral b toothbrush red,
peva shower curtain liner,
platinum pets dog bowl,
rawlings baseball,
rolodex jumbo pencil cup,
safety first outlet plugs,
scotch bubble mailer,
scotch duct tape,
soft white lightbulb,
staples index cards,
ticonderoga 12 pencils,
up glucose bottle,
womens knit gloves,
woods extension cord
},
    visualization depends on=rawy\as\rawy, % Save the unclipped values
    after end axis/.code={ % Draw line indicating break
            \draw [ultra thick, white, decoration={snake, amplitude=2pt}, decorate] (rel axis cs:0,1.05) -- (rel axis cs:1,1.05);
        },
    nodes near coords={%
            \pgfmathprintnumber{\rawy}% Print unclipped values
        },
every node near coord/.append style={font=\tiny, inner sep=1pt,rotate=90,xshift=0.3cm},
    axis lines*=left,
    clip=false
    ]
\addplot coordinates {
(barkely hide bones,0.8780)
(cherokee easy tee-shirt,0.8210)
(clorox utility brush,0.8210)
(cloud b plush bear,0.8360)
(command hooks,0.8770)
(cool shot glue sticks,0.7930)
(crayola 24 ct,0.8110)
(creativity chenille stems ,0.7610)
(dasani water bottle,0.7960)
(dove beauty bar,0.7400)
(dr browns bottle brush,0.9400)
(easter turtle sippy cup ,0.8790)
(elmers washable no run school glue ,0.8380)
(expo dry erase board eraser ,0.8240)
(fiskars scissors red,0.4780)
(fitness gear 3lb dumbbell,0.7630)
(folgers classic roast coffee,0.8980)
(hanes tube socks,0.8890)
(i am a bunny book,0.9060)
(jane eyre dvd,0.8930)
(kleenex paper towels,0.8880)
(kleenex tissue box,0.9420)
(kyjen squeakin eggs plush puppies,0.8600)
(laugh out loud joke book,0.8940)
(oral b toothbrush green,0.7460)
(oral b toothbrush red,0.6790)
(peva shower curtain liner,0.9160)
(platinum pets dog bowl,0.9170)
(rawlings baseball,0.8580)
(rolodex jumbo pencil cup,0.9260)
(safety first outlet plugs,0.8340)
(scotch bubble mailer,0.8940)
(scotch duct tape,0.8100)
(soft white lightbulb,0.8410)
(staples index cards,0.8470)
(ticonderoga 12 pencils,0.9500)
(up glucose bottle,0.7860)
(womens knit gloves,0.8870)
(woods extension cord,0.8880)
};

\end{axis}
\end{tikzpicture}

I want the bars to be sorted automatically based on the y value. Could someone please help in figuring this out?


text:
Q: A random number generator that can get different numbers in < a second I'm in need of a C++ (pseudo, i don't care) random number generator that can get me different numbers every time I call the function. This could be simply the way I seed it, maybe there's a better method, but every random generator I've got doesn't generate a new number every time it's called. I've got a need to get several random numbers per second on occasion, and any RNG i plug in tends to get the same number several times in a row.
Of course, I know why, because it's seeded by the second, so it only generates a new number every second, but I need to, somehow, get a new number on every call. Can anyone point me in the right direction?

A: You only need to seed the generator once with srand() when you start, after that just call the rand() function. If you seed the generator twice with the same seed, you'll get the same value back each time.

A: You should only seed the PRNG once.

A: Boost.Random has a variety of pretty good random number generators.

A: Sounds like you do it like this:
int get_rand() {
    srand(time(0));
    return rand();
}

Which would explain why you get the same number within one second. But you have to do it like this:
int get_rand() {
    return rand();
}

And call srand once at program startup.

A: If you're generating a large number of random numbers, you could try an XORShift generator. For longs (8 bit):
// initial setup
unsigned long x = ... init from time etc ...
// each time we want a random number in 'x':
x ^= x << 21;
x ^= x >> 35;
x ^= x << 4;

A: This code generates a  unique random number only once.
#include <ctime>
# include <iostream>
using namespace std;

int main()
{

      int size=100;
      int random_once[100];
      srand(time(0));

      for (int i=0;i<size;i++)  // generate unique random number only once
      {
          random_once[i]=rand() % size;
          for(int j=0;j<i;j++) if (random_once[j]==random_once[i]) i--;
      }

      for ( i=0;i<size;i++) cout<<" "<<random_once[i]<<"\t";

  return 0;


text:
Q: Fetch data from multiple unrelated tables Consider these 2 tables:
Product1
----------
id
created

Product2
---------
id
created

How can I get all products from Product1 and Product2 ordered by created?
NB: Product1 and Product2 tables are only examples to explain my case, they do not reflect the reality. Please do not debate about that.

A: You can Combining Result Sets by Using MySQL UNION
SQLFiddle
SELECT * FROM (select p1.id, p1.created from product1 p1
UNION ALL
select p2.id, p2.created from product2 p2) A
order by created

OR
(select p1.id, p1.created from product1 p1)
UNION ALL (select p2.id, p2.created from product2 p2)
ORDER BY created

A: assuming both tables have an identical structure you could try this
SELECT
    'Product1' AS FromTable
    ,id
    ,created
FROM
    Product1
UNION
SELECT
    'Product2' AS FromTable
    ,id
    ,created
FROM
    Product2
ORDER BY created

A: Use cross join (also known as Cartesian join) select product1.*, product2.* from product1 cross join product2; just be cautions that what the cross join does it multiplies the records. Here is an answer for that mysql cross join, but without duplicated pair?


text:
Q: Not able to Log only my project logs using Log4j in Java This is my log4j.properties file.
log4j.rootLogger=DEBUG, stdout, file

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# Redirect log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
#outputs to Tomcat home
log4j.appender.file.File=${catalina.home}/logs/myapp.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p

%c{1}:%L - %m%n
This is loading bunch of logs which are related to the framework etc.
I tried to put
log4j.rootLogger=DEBUG only to load only my logs.

I want my log file to have only my project logs. Where should I need to change?
The way I'm logging my statements are
private Logger logger = Logger.getLogger(MyClass.class);
logger.debug("bla bla");

A: You should configure logger as per  your application package name.
Suppose, your application package name is test.example then add below line in your log4j.properties -
log4j.logger.test.example = DEBUG, stdout, file
log4j.additivity.test.example = false

It will enable debug logs in classes which are present in test.example package as well as in sub packages.
For removing framework related logs, change rootLogger log level to ERROR or WARN -
log4j.rootLogger=ERROR, stdout, file

It will display only errors which are related to framework classes or classes which are not present in above package test.example and its subpackages.

A: log4j.rootLogger=INFO,myproject

#My logger option
log4j.logger.com.myproject=ERROR
log4j.appender.myproject=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myprojectapp.File=${catalina.home}/logs/myproject.log
log4j.appender.myproject.DatePattern='.'yyyy-MM-dd
log4j.appender.myproject.layout=org.apache.log4j.PatternLayout
log4j.appender.myproject.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L -%M - %m%n
log4j.appender.myproject.Threshold=DEBUG

#to not add myproject logs to other logger
log4j.additivity.com.myproject=false


text:
Q: Computing the order of elements in a non abelian exterior square of a finite group If we have an explicit group $G$, and we pick two elements $g,h \in G$, could we find the order of the element $g \wedge h \in G \wedge G$?
The best thing I could find is Theorem 1.1 in Ellis' Book (http://link.springer.com/article/10.1023%2FA%3A1008652316165), which tells us that for any finite group $G$, $H_2(G)$ is a finite abelian group with exponent $e$ dividing the order of $G$.


text:
Q: Google Cloud Functions randomly retrying on success I have a Google Cloud Function triggered by a PubSub. The doc states messages are acknowledged when the function end with success.
link
But randomly, the function retries (same execution ID) exactly 10 minutes after execution. It is the PubSub ack max timeout.

I also tried to get message ID and acknowledge it programmatically in Function code but the PubSub API respond there is no message to ack with that id.
In StackDriver monitoring, I see some messages not being acknowledged.

Here is my code : main.py
import base64
import logging
import traceback

from google.api_core import exceptions
from google.cloud import bigquery, error_reporting, firestore, pubsub

from sql_runner.runner import orchestrator

logging.getLogger().setLevel(logging.INFO)

def main(event, context):

    bigquery_client = bigquery.Client()
    firestore_client = firestore.Client()
    publisher_client = pubsub.PublisherClient()
    subscriber_client = pubsub.SubscriberClient()

    logging.info(
        'event=%s',
        event
    )
    logging.info(
        'context=%s',
        context
    )
    try:
        query_id = base64.b64decode(event.get('data',b'')).decode('utf-8')
        logging.info(
            'query_id=%s',
            query_id
        )

        # inject dependencies
        orchestrator(
            query_id,
            bigquery_client,
            firestore_client,
            publisher_client
        )

        sub_path = (context.resource['name']
            .replace('topics', 'subscriptions')
            .replace('function-sql-runner', 'gcf-sql-runner-europe-west1-function-sql-runner')
        )

        # explicitly ack message to avoid duplicates invocations
        try:
            subscriber_client.acknowledge(
                sub_path,
                [context.event_id]  # message_id to ack
            )
            logging.warning(
                'message_id %s acknowledged (FORCED)',
                context.event_id
            )
        except exceptions.InvalidArgument as err:
            # google.api_core.exceptions.InvalidArgument: 400 You have passed an invalid ack ID to the service (ack_id=982967258971474).
            logging.info(
                'message_id %s already acknowledged',
                context.event_id
            )
            logging.debug(err)

    except Exception as err:
        # catch all exceptions and log to prevent cold boot
        # report with error_reporting
        error_reporting.Client().report_exception()
        logging.critical(
            'Internal error : %s -> %s',
            str(err),
            traceback.format_exc()
        )

if __name__ == '__main__':  # for testing
    from collections import namedtuple  # use namedtuple to avoid Class creation
    Context = namedtuple('Context', 'event_id resource')
    context = Context('666', {'name': 'projects/my-dev/topics/function-sql-runner'})

    script_to_start = b' '   # launch the 1st script
    script_to_start = b'060-cartes.sql'

    main(
        event={"data": base64.b64encode(script_to_start)},
        context=context
    )

Here is my code : runner.py
import logging
import os

from retry import retry

PROJECT_ID = os.getenv('GCLOUD_PROJECT') or 'my-dev'

def orchestrator(query_id, bigquery_client, firestore_client, publisher_client):
    """
    if query_id empty, start the first sql script
    else, call the given query_id.

    Anyway, call the next script.
    If the sql script is the last, no call

    retrieve SQL queries from FireStore
    run queries on BigQuery
    """
    docs_refs = [
        doc_ref.get() for doc_ref in
        firestore_client.collection(u'sql_scripts').list_documents()
    ]

    sorted_queries = sorted(docs_refs, key=lambda x: x.id)

    if not bool(query_id.strip()) :  # first execution
        current_index = 0
    else:
        # find the query to run
        query_ids = [ query_doc.id for query_doc in sorted_queries]
        current_index = query_ids.index(query_id)

    query_doc = sorted_queries[current_index]

    bigquery_client.query(
        query_doc.to_dict()['request'],  # sql query
    ).result()

    logging.info(
        'Query %s executed',
        query_doc.id
    )

    # exit if the current query is the last
    if len(sorted_queries) == current_index + 1:
        logging.info('All scripts were executed.')
        return

    next_query_id = sorted_queries[current_index+1].id.encode('utf-8')

    publish(publisher_client, next_query_id)

@retry(tries=5)
def publish(publisher_client, next_query_id):
    """
    send a message in pubsub to call the next query
    this mechanism allow to run one sql script per Function instance
    so as to not exceed the 9min deadline limit
    """
    logging.info('Calling next query %s', next_query_id)

    future = publisher_client.publish(
        topic='projects/{}/topics/function-sql-runner'.format(PROJECT_ID),
        data=next_query_id
    )

    # ensure publish is successfull
    message_id = future.result()
    logging.info('Published message_id = %s', message_id)

It looks like the pubsub message is not ack on success.
I do not think I have background activity in my code.
My question : why my Function is randomly retrying even when success ?

A: Cloud Functions does not guarantee that your functions will run exactly once.  According to the documentation, background functions, including pubsub functions, are given an at-least-once guarantee:

Background functions are invoked at least once. This is because of the
  asynchronous nature of handling events, in which there is no caller
  that waits for the response. The system might, in rare circumstances,
  invoke a background function more than once in order to ensure
  delivery of the event. If a background function invocation fails with
  an error, it will not be invoked again unless retries on failure are
  enabled for that function.

Your code will need to expect that it could possibly receive an event more than once.  As such, your code should be idempotent:

To make sure that your function behaves correctly on retried execution
  attempts, you should make it idempotent by implementing it so that an
  event results in the desired results (and side effects) even if it is
  delivered multiple times. In the case of HTTP functions, this also
  means returning the desired value even if the caller retries calls to
  the HTTP function endpoint. See Retrying Background Functions for more
  information on how to make your function idempotent.


text:
Q: what does [1] mean in model.evaluate(X, Y)[1] The following codes are from a textbook called 'Deeplearning for everybody' and it is to predict diabetes based on the data from Pima indians. I wonder what the [1] at the end of the codes mean.
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import numpy
import tensorflow as tf

np.random.seed(3)
tf.random.set_seed(3)

dataset = np.loadtxt('.\dataset\pima-indians-diabetes.csv', delimiter=',')

X = dataset[:, 0:8]
Y = dataset[:, 8]

model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.fit(X, Y, epochs=200, batch_size=10)

print('\n Accuracy: %.4f' % (model.evaluate(X, Y)[1]))    # <---------

A: In Keras model.evaluate() returns a list of aggregated metric values. Say you want to measure the loss, the accuracy, F1 score on your test data, then you would compile your model something like this: model.compile(optimizer, loss, metrics=['accuracy', custom_f1_function], .. ) . Then these will be calculated for every sample (or batch) in the dataset and then reduced usually by taking the average. In the end you will get a list that has three elements: aggregated loss, aggregated accuracy, aggregated F1 score. In your code you are accessing the second element of this list, namely the accuracy.
(The order in `metrics=[..] determines the order in the output list!)


text:
Q: Parameters missing or not sent as an JSON array with PHP CURL The error:
{"jsonrpc":"2.0","id":0,"error":{"code":1,"message":"Parameters missing or not sent as an JSON array. "}}

My code:
<?php

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Accept: text/plain, */*; q=0.01"));
curl_setopt($ch, CURLOPT_URL, 'http://example.com/rpc/ClientApi?_session=XX');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('method' => 'AdsApi.giveAdLifeByCategory','params' => '["Ads4Life"]', 'id' => '0')));
curl_setopt($ch, CURLOPT_POST, 1);
$result = curl_exec($ch);

?>

I'm trying to emulate this request:
[{"method":"AdsApi.giveAdLifeByCategory","params":["Ads4Life"],"id":0}]

Correct Response:
[{
     "jsonrpc": "2.0",
     "id": 0,
     "result": {
         "status": true,
         "timeStamp": 0
     }
}]

What could be the problem?

A: Wrong bracketing:
... 'AdsApi.giveAdLifeByCategory','params' => '["Ads4Life"]', 'id' => '0')));
                                               ^---       ^--

your "emulated" sample has braockets around that, but you're embedding them in your array key definition, so when the JSON is produced, it'll actually be:
... "params": "[\"Ads4Life\"]" ...

with the [" and "] embedded within the string.
Probably should be just
... 'AdsApi.giveAdLifeByCategory','params' => array('Ads4Life'), 'id' => '0')));
                                                   ^^^^^^^^^^


text:
Q: Wordpress Plugin Generating PDF and Xls Documents I'm writing a web application for a client that needs to be packaged in a wordpress plugin. The application is built on top of a soap api that returns an array of results that I need to output to a pdf and/or excel document. I'm using two third party libraries to generate the pdf and excel files (tcpdf and phpexcel), but Wordpress won't allow them to modify the header from inside of the plugin to return different types of content. Does anyone know how I can generate and return a pdf/excel document from inside of a Wordpress plugin?

A: Please refer following TCPDF exmaple link...this will show you how to create pdf using TCPDF.
http://www.tcpdf.org/examples.php

You can also refer post2pdf-converter wordpress plugin which will show you how to convert posts to pdf.
http://wordpress.org/extend/plugins/post2pdf-converter/


text:
Q: Are weights and trainable variables the same in Keras? That's all, I need to know if they are the same or correspond to different concepts.
When I use the model.summary() method, it gives me the amount of trainable variables, I need to know if they are the same as the weights

A: "Almost".
In most cases, yes, they are. But there are layers that use non-trainable weights for other purposes.
For instance, a BatchNormalization layers has four weight variables:

*

*mean: not trainable with backpropagation, but learnable from taking statistics from the data

*variance: not trainable with backpropagation, but learnable from taking statistics from  the data

*scale: trainable with backpropagation

*offset: trainable with backpropagation


text:
Q: Accelerometer to detect when product has been picked up by user I have a 3-axis accelerometer on my board and i was hoping to use it to detect when a user lifts the device up.
I would like to avoid false triggers when the table shakes or when the user nudges the device slightly.
I thought this would be a straightforward case of getting the magnitude from all 3 axis (which should on average give me around 1g acceleration) and then low pass filtering it to remove any high frequency noise. Leaving behind the low frequency content of gravity + the motion of lifting the device up. However, it seems a nudge creates a spread of frequncies some of which overlap in the region i am interested in (0Hz - 2 Hz). Any standard filters for accelerometer data?
Can accelerometers be used for such detection? Must i use a different sensor?


text:
Q: Querying on nested document in MongoDB I have a complex document structure like below -
{
    "Application": {
        "DEF": {
            "Year": {
                "2018": {
                    "Quarter": {
                        "Q1": {
                            "Microservice": [ "A", "B" ]
                        },
                        "Q2": {
                            "Microservice": [ "C", "D" ]
                        },
                        "Q3": {
                            "Microservice": [ "E" ]
                        },
                        "Q4": {
                            "Microservice": [ "F", "G" ]
                        }
                    }
                },
                "2019": {
                    "Quarter": {
                        "Q1": {
                            "Microservice": [ "A", "C" ]
                        },
                        "Q2": {
                            "Microservice": [ "D" ]
                        },
                        "Q3": {
                            "Microservice": [ "E", "F" ]
                        },
                        "Q4": {
                            "Microservice": [ "G" ]
                        }
                    }
                }
            }
        }
    },
    "Product Name": "XYZ"
}

I am trying to query all the records where Application is DEF, Year is 2018 and all Quarters. I have tried the DOT(.) notation like below --
db.productsTest.find({"Application.DEF.Year.2018": {$exists: true}})

The above returns results for all Years (2018 and 2019) instead of just returning the Year, Quarter and Microservice combination for only 2018. This could also be because of the JSON structure and I can't filter by Year (since they are nested). Basically I am looking for the query which returns this --
{
    "Application": {
        "DEF": {
            "Year": {
                "2018": {
                    "Quarter": {
                        "Q1": {
                            "Microservice": [ "A", "B" ]
                        },
                        "Q2": {
                            "Microservice": [ "C", "D" ]
                        },
                        "Q3": {
                            "Microservice": [ "E" ]
                        },
                        "Q4": {
                            "Microservice": [ "F", "G" ]
                        }
                    }
                }
            }
        }
    },
    "Product Name": "XYZ"
}

Is that result even possible given my JSON structure?

A: The following query gets the job done:
db.productsTest.find({
    "Application.DEF.Year.2018": { $exists: true } // exclude documents from the result that do not contain the subdocument that we are interested in
}, {
    "_id": 0, // we do not want the _id field in the result document
    "Product Name" : 1, // but the "Product Name" should be included
    "Application.DEF.Year.2018": 1 // and so should be the subdocument we are interested in
})

Basically, that's just a standard query with a projection.
$exists is an element operator which checks if a property exists or not.

A: You can use the $exists operator to find documents that contain a specified field! This works for me using the test data you provided:
db.productsTest.findOne({"Application.DEF.Year.2018.Quarter.Q1":{$exists:true}})

and returns the test document you provided.
As a side note: Unless you have a good reason to use this deeply of a nested structure flattening your documents can help readability.


text:
Q: Pass N-D array by reference to variadic function I'd like to make the function multi_dimensional accept a multidimensional array by reference.
Can this be done with a variation of the syntax below which works for three_dimensional?
#include <utility>

// this works, but number of dimensions must be known (not variadic)
template <size_t x, size_t y, size_t z>
void three_dimensional(int (&nd_array)[x][y][z]) {}

// error: parameter packs not expanded with '...'
template <size_t... dims>
void multi_dimensional(int (&nd_array)[dims]...) {}

int main() {
    int array[2][3][2] = {
        { {0,1}, {2,3}, {4,5} },
        { {6,7}, {8,9}, {10,11} }
    };
    three_dimensional(array); // OK
    // multi_dimensional(array); // error: no matching function
    return 0;
}

A: The main problem is that you cannot make the number of array dimensions itself variadic. So whichever way you go, you will almost certainly need a recursive approach of some sort to deal with the individual array layers. What exactly such approach should look like will mainly depend on what exactly you're planning to do with the array once it's been given to you.
If really all you want is a function that can be given any multi-dimensional array, then just write a function that can be given anything but only exists as long as that anything is an array:
template <typename T>
std::enable_if_t<std::is_array_v<T>> multi_dimensional(T& a)
{
    constexpr int dimensions = std::rank_v<T>;

    // ...
}

However, this by itself will most likely not get you very far. To actually do anything meaningful with the array you've been given, you will most likely need some recursive walking through subarrays. Unless you really just want to look at the topmost layer of the structure.
Another approach is to use a recursive template to peel back the individual array levels, for example:
// we've reached the bottom
template <typename T, int N>
void multi_dimensional(T (&a)[N])
{
    // ...
}

// this matches any array with more than one dimension
template <typename T, int N, int M>
void multi_dimensional(T (&a)[N][M])
{
    // peel off one dimension, invoke function for each element on next layer
    for (int i = 0; i < N; ++i)
        multi_dimensional(a[i]);
}

I would, however, suggest to at least consider using std::array<> instead of raw arrays as the syntax and special behavior of raw arrays tends to turn everything into a confusing mess in no time. In general, it might be worth to implement your own multi-dimensional array type, like an NDArray<int, 2, 3, 2> which internally works with a flattened representation and just maps multi-dimensional indices to a linear index. One advantage of this approach (besides the cleaner syntax) would be that you can easily change the mapping, e.g., to switch from row-major to column-major layout, e.g., for performance optimization…
To implement a general nD array with static dimensions, I would introduce a helper class to encapsulate the recursive computation of a linear index from an nD index:
template <std::size_t... D>
struct row_major;

template <std::size_t D_n>
struct row_major<D_n>
{
    static constexpr std::size_t SIZE = D_n;

    std::size_t operator ()(std::size_t i_n) const
    {
        return i_n;
    }
};

template <std::size_t D_1, std::size_t... D_n>
struct row_major<D_1, D_n...> : private row_major<D_n...>
{
    static constexpr std::size_t SIZE = D_1 * row_major<D_n...>::SIZE;

    template <typename... Tail>
    std::size_t operator ()(std::size_t i_1, Tail&&... tail) const
    {
        return i_1 + D_1 * row_major<D_n...>::operator ()(std::forward<Tail>(tail)...);
    }
};

And then:
template <typename T, std::size_t... D>
class NDArray
{
    using memory_layout_t = row_major<D...>;

    T data[memory_layout_t::SIZE];

public:
    template <typename... Args>
    T& operator ()(Args&&... args)
    {
        memory_layout_t memory_layout;
        return data[memory_layout(std::forward<Args>(args)...)];
    }
};

NDArray<int, 2, 3, 5> arr;

int main()
{
    int x = arr(1, 2, 3);
}


text:
Q: R: Extract JSON Variable Info I'm trying to download NBA player information from Numberfire and then put that information into a data frame. However I seem to be running into a few issues
The following snippet downloads the information just fine
require(RCurl)
require(stringr)
require(rjson)

#download data from numberfire
nf <- "https://www.numberfire.com/nba/fantasy/fantasy-basketball-projections"
html <- getURL(nf)

Then there is what I assume to be a JSON data structure
#extract json variable (?)
pat <- "NF_DATA.*}}}"
jsn <- str_extract(html, pat)
jsn <- str_split(jsn, "NF_DATA = ")
parse <- newJSONParser()
parse$addData(jsn)

It seems to add data OK as  it doesn't throw any errors, but if there is data in that object I can't tell or seem to get it out!
I'd paste in the jsn variable but it's way over the character limit. Any hints as to where I'm going wrong would be much appreciated

A: Adding the final line gets a nice list format that you can transform to a data.frame
require(RCurl); require(stringr); require(rjson)

#download data from numberfire
nf <- "https://www.numberfire.com/nba/fantasy/fantasy-basketball-projections"
html <- getURL(nf)

#extract json variable (?)
pat <- "NF_DATA.*}}}"
jsn <- str_extract(html, pat)
jsn <- str_split(jsn, "NF_DATA = ")
fromJSON(jsn[[1]][[2]])


text:
Q: What exactly are the effects of Aiming Down Sights in apex legends? Scoping = ADS bellow:

*

*Does the accuracy change (i.e. is not scoping in any way less accurate than the exact same aim/tracking with a scoping?)

*Does the spread change?

*Does the recoil change?"

*Are there other changes (except markings, zoom, thermal)?

*To which weapons do whatever changes (if any) apply?

If the answer to the above is no to everything, then are people seriously crippling movement just to get a mark on their screen!? I am asking because I generally hate scoping, except when totally necessary... but sometimes, I feel like I'm aiming great, but I'm not hitting anything without scoping, wondering if there are specific weapons which genuinely become inaccurate without scoping?

A: Scoping, more commonly known as Aiming Down Sights or ADS, gives you the following benefits:

*

*Significantly tighter spread on all weapons

*Zoom

*More Control for most weapons

However it has trade-offs, in the form of:

*

*Your mobility is lowered

*Less awareness as you are now focusing on a single direction

*Some Weapons, like SMGs without stabilizers/stocks become a bit wild

If you are using anything other than an SMG, you will hit more if you ADS. Even shotguns benefit greatly with ADS. The Peacekeeper with the choke hop-up, for example, tightens its spread so much it nearly becomes a rifle. Scout and Sniper Rifles pretty much require ADS to be effective. ARs and LMGs can go either way, but they are more effecting when ADS a majority of the time.
If you do not like to use the ADS mechanic, Apex probably isn't for you.

A: I assume by scoping you mean ADSing, so right-clicking before shooting? Because scope, or no scope, the effects seem to be similar, at least as far as shotguns are concerned (I only tested shotguns).
In case of shotguns the pattern remains the same (triangle for mozambique, 5-star for peacekeeper, 8 shape for EVA-8, two parallel horizontal lines for mastiff), but in ADS is tighter, so you will hit more pellets when shooting at range and you should not ADS in close combat as you're risking missing with all your pellets.
I also distinctly remember Longbow being useless without ADS. It doesn't matter what scope you've got, if you can compensate you will still shoot your target, but if you try to hipfire, it will just shoot in random direction.


text:
Q: Generalization of integral using special function Is it possible to find a closed formula for the following integrals for any $k\in \mathbb{N}^{*}$:
$$
I=\int_{0}^{1} \left[\ln\left(\frac{p}{1-p}\right)\right]^{k}p^{2}dp
,\quad
J=\int_{0}^{1} \left[\ln\left(\frac{p}{1-p}\right)\right]^{k}pdp
,\quad K=\int_{0}^{1} \left[\ln\left(\frac{p}{1-p}\right)\right]^{k}dp.
$$
I know that $I,J,K$ exist because the function is well defined and can be extended to $0$ and $1$ by continuity.
My question: is it possible to write $I,J,K$ as function of some special function like gamma or beta function? if yes can you give my the right expression.

A: I realized that using beta function is not a good idea. Here is an alternate solution:
Use the substitution $u = \frac{p}{1-p}$. Then $p = \frac{u}{1+u}$ and $dp = \frac{du}{(1+u)^{2}}$. So we have
\begin{align*}
\int_{0}^{1} p^{\nu-1} \log^{k} \left( \frac{p}{1-p} \right) \, dp
&= \int_{0}^{\infty} \frac{u^{\nu-1}\log^{k} u}{(1+u)^{\nu+1}} \, du \\
&= \int_{0}^{1} \frac{u^{\nu-1}\log^{k} u}{(1+u)^{\nu+1}} \, du + \int_{1}^{\infty} \frac{u^{\nu-1}\log^{k} u}{(1+u)^{\nu+1}} \, du.
\end{align*}
For the second integral, we use the substitution $u \mapsto u^{-1}$ to obtain
\begin{align*}
\int_{0}^{1} p^{\nu-1} \log^{k} \left( \frac{p}{1-p} \right) \, dp
&= \int_{0}^{1} \frac{u^{\nu-1}\log^{k} u}{(1+u)^{\nu+1}} \, du + (-1)^{k} \int_{0}^{1} \frac{\log^{k} u}{(1+u)^{\nu+1}} \, du.
\end{align*}
Plugging $u = e^{-t}$ and utilizing the following generalized binomial series,
$$ \frac{1}{(1 + z)^{\beta+1}} = \sum_{j=0}^{\infty} \binom{j+\beta}{j} (-1)^{j} z^{j}, $$
it follows that
\begin{align*}
\int_{0}^{1} p^{\nu-1} \log^{k} \left( \frac{p}{1-p} \right) \, dp
&= (-1)^{k}\int_{0}^{\infty} \frac{t^{k}e^{-\nu t} }{(1+e^{-t})^{\nu+1}} \, dt + \int_{0}^{\infty} \frac{t^{k} e^{-t}}{(1+e^{-t})^{\nu+1}} \, dt \\
&= \sum_{j=0}^{\infty} \binom{j+\nu}{j} (-1)^{j} \left\{ (-1)^{k}\int_{0}^{\infty} t^{k}e^{-(\nu+j) t} \, dt + \int_{0}^{\infty} t^{k} e^{-(1+j)t} \, dt \right\} \\
&= \sum_{j=0}^{\infty} \binom{j+\nu}{j} (-1)^{j} \left\{ \frac{(-1)^{k} k!}{(j+\nu)^{k+1}} + \frac{k!}{(j+1)^{k+1}} \right\} \\
&= \frac{k!}{\nu!} \sum_{j=0}^{\infty} (-1)^{j} (j+1)_{\nu} \left\{ \frac{(-1)^{k}}{(j+\nu)^{k+1}} + \frac{1}{(j+1)^{k+1}} \right\}, \\
\end{align*}
where
$$ (x)_{n} = \frac{\Gamma(x+n)}{\Gamma(x)} $$
stands for the Pochhammer symbol. If $\left[{n\atop k}\right]$ denotes the (unsigned) Stirling's number of the first kind, then we have the following identity
$$ (x)_{n} = \sum_{k=0}^{n} \left[{n\atop k}\right] x^{k} $$ and hence
\begin{align*}
\int_{0}^{1} p^{\nu-1} \log^{k} \left( \frac{p}{1-p} \right) \, dp
&= \frac{k!}{\nu!} \left\{ (-1)^{k} \sum_{j=1}^{\infty} (-1)^{j-1} \frac{(j)_{\nu}}{(j+\nu-1)^{k+1}} + \sum_{j=1}^{\infty} (-1)^{j-1} \frac{(j)_{\nu}}{j^{k+1}} \right\} \\
&= \frac{k!}{\nu!} \left\{ (-1)^{k+\nu+1} \sum_{j=1}^{\infty} (-1)^{j-1} \frac{(j-\nu+1)_{\nu}}{j^{k+1}} + \sum_{j=1}^{\infty} (-1)^{j-1} \frac{(j)_{\nu}}{j^{k+1}} \right\} \\
&= \frac{k!}{\nu!} \sum_{l=0}^{\nu} \left[ {\nu \atop l} \right] \{ 1 + (-1)^{k-l+1} \} \eta(k-l+1),
\end{align*}
where $\eta(z) = (1 - 2^{1-z}) \zeta(z)$ is the Dirichlet eta function. Since the only terms with $k - l + 1$ even survives, we can even write it as a rational combination of even powers of $\pi$.
You can check this numerically by the following code in Mathematica:
Eta[z_] := If[z == 1, Log[2], (1 - 2^(1 - z)) Zeta[z]];

{k, n} = {3, 4};
NIntegrate[p^(n - 1) Log[p/(1 - p)]^k, {p, 0, 1}] // Chop
N[k!/n! Sum[
    Abs[StirlingS1[n, l]] (1 + (-1)^(k - l + 1)) Eta[k - l + 1],
    {l, 0, n}]]
Clear[n, k];


text:
Q: How to download the picture made by html5 canvas? And the picture can be a round-corner rectangle rather than just a rectangle? Picture 1 is the picture created out of canvas. Picture 2 is the picture I downloaded. I don't know why the shape of the picture changes back to a rectangle. I hope it can be the same shape as the one I see on the web page (picture 1).  Thank you for any help!!!!
Picture 1
Picture 2
Here are the codes I used to draw pictures on canvas and convert canvas to an image.

<!DOCTYPE html>

        <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">

        Hello

Canvas:

      <canvas id="myCanvas" width="240" height="297"
    style="border-radius: 15px;">
        Your browser does not support the HTML5 canvas tag.
        </canvas>


text:
Q: Hash navigation between two HTML pages in phonegap android Hi i am hitting my head on wall for two days for this.I am learning jQuery and phonegap and facing following issue in developing an application.
I have a simple scenario in phonegap application.
I have two HTML pages say index.html and page2.html.
index.html is having two or more divs with data-role="page" for ex.

and

page2.html is a list for ex.

go to main

So here problem is when i click on this it is crashing with dialog
Application Error.

A Network Error occurred. (file:///android_asset/www/index.html#main)

And here is my log cat output.
**

11-30 01:01:33.296: D/DroidGap(25758):
  onMessage(onPageStarted,file:///android_asset/www/index.html#main)
  11-30 01:01:33.296: D/Cordova(25758):
  CordovaWebViewClient.onReceivedError: Error code=-1 Description=A
  network error occurred. URL=file:///android_asset/www/index.html#main
  11-30 01:01:33.296: D/DroidGap(25758):
  onMessage(onReceivedError,{"errorCode":-1,"url":"file:///android_asset/www/index.html#main","description":"A
  network error occurred."})

**
I have tried window.location , window.location.href,onPageChange() of jquery etc...
But nothing works.
Any solution to achieve this ??


text:
Q: Deploy finished laravel project on localhost for Client - laravel I am very new to laravel and i have a finished product for a client. I want to know the steps on how to deploy this application for my client who is requesting to use the application on localhost on his computer.
I have been looking for steps to do this. Any help please?
PS: This is my first time handling such deployment in programming.

A: Here you have documenation: https://laravel.com/docs/5.6/deployment
Just remember to use:
Get dependencies:
composer install

Clear cache in configuration:
php artisan config:cache

Clear route cache:
php artisan route:cache

Clear view cache:
php artisan view:clear

All those operations must be done on production server.
If you do not know how to send files from localhost to production server - read about GIT.
Good luck!

A: Install all necessary components on his computer to use laravel.

*

*Install Web Server (e.g. WAMP, XAMPP, MAMP).

*Install Composer.

*Copy the project to his computer.

*Export the database (if any), then import it on his computer.

*Open terminal/cmd, locate to the project folder, run: composer update.

*After that, run: composer dump-autoload.

*Visit it in the browser.

*Grab some drink, and relax. That should do it.

NOTE: This is only work on local (localhost/on his computer).


text:
Q: How to generate a GET request Swagger API Doc in Laravel 5.8 API? I'm using L5-Swagger framework to generate an API Doc for my Laravel 5.8 project.
Here is the code I have created so far:
 /**
 * @OA\GET(
 *     path="/api/articles",
 *     tags={"articles"},
 *     summary="Returns articles with limit and offset",
 *     description="Description by Chanaka",
 *     operationId="sampleFunctionWithDoc",
 * )
 * @OA\Parameter(
 *    description="limit",
 *    in="path",
 *    name="limit",
 *    required=true,
 *    example="1",
 * )
 * @OA\Response(
 *    response="default",
 *    description="successful operation"
 * )
 *
 */
public function showAllArticles($limit, $offset)
{
    return response()->json(Article::skip($offset)->take($limit)->get());
}

This is an endpoint with limit and offset. I added limit as a parameter here just to check. But it is not generating. Only the endpoint with path is available in the Swagger UI.

Please tell me what is the issue with my syntax.
Is there another way to implement this.
Thank you in advance.

A: I believe annotations should be like this:
/**
 * @OA\GET(
 *     path="/api/articles",
 *     tags={"articles"},
 *     summary="Returns articles with limit and offset",
 *     description="Description by Chanaka",
 *     operationId="sampleFunctionWithDoc",
 *     @OA\Parameter(
 *       description="limit",
 *       in="path",
 *       name="limit",
 *       required=true,
 *       example="1",
 *    ),
 *    @OA\Response(
 *       response="default",
 *       description="successful operation"
 *    )
 *  )
 *
 */

So basically your parameters and response definitions should be another line in the root of the GET path "/api/articles" declaration.


text:
Q: jQuery $.ajax call for obtaining RESTful API from cross domain URL but it doesn't work The error message is

Console Error: "Uncaught SyntaxError: Unexpected token :"
STATUS: parseerror,
ERROR: jQuery1110072177085862495_1399027696440 was not called

My ajax call is:
$.ajax({
   crossDomain: true,
   url: "54.225.213.167/developer-assessment/api",
   dataType:"jsonp",
   type: "GET"
})
  .done(function(data, status, xhr){
       console.log(data);
})
  .fail(function(xhr, status, error){
       console.log(status);
       console.log(error);
);

Even if the result calling the url directly is a JSON obj.


text:
Q: How to get state item in canvas I am looking to get only the items having a 'normal state', I traced different line with different states (hidden and normal),
Actually I use :
foreach itemId [.c find all]
...

I tried like this but It does'nt work
set state [.c itemcget $tag state]
set state [$itemId cget state]

thank you

A: An item in a canvas can have three difference states, namely normal, disabled or hidden. That's true, except that the state for an item created without specifying the state, in the sense that this item does not have any state.
If you create an item with state normal, you would do:
.c create item -state normal

Let's say that this item has the ID 1. Doing .c itemcget 1 -state would give you normal.
If you create another item without specifying the state...
.c create item

and supposing it has ID 2, then doing .c itemcget 1 -state will give you an empty string.
Essentially, normal and 'nothing' are the same. You can see all the options of a particular item with:
.c itemconfigure tagOrId

And for the case of item 1, you would notice that you have -state {} {} {} {normal} and for item 2, you would have -state {} {} {} {}.
In conclusion, to get a list of all item IDs with normal state, you could do:
set normalItems [list]
foreach itemId [.c find all] {
    set state [.c itemcget $itemId -state]
    if {$state eq "" || $state eq "normal"} {
        lappend normalItems $itemId
    }
}

Or use $state in {"" "normal"} if you want to make the if condition shorter.
Note: pathName cget state is used to get the state of the canvas, not the item within the canvas.


text:
Q: NHibernate cascade update/insert I have a Case class which exposes a Person object as follows:
public class Case
{
  public virtual Person Deceased {get;set;}
}

I have a PersonalAsset class which also exposes a Person:
public class PersonalAsset
{
  public virtual Person Owner {get;set;}
}

Assuming I write the following code within an ISession:
Case case = new Case();
Person deceased = new Person();
case.Deceased = deceased;
PersonalAsset asset = new PersonalAsset();
asset.Owner = deceased;
session.SaveOrUpdate(case);

Is there any mapping configuration which will save the PersonalAsset automatically? Or do I need to call session.Save(asset) as well?
Thanks
David

A: Without a reference between them you would need to save things manually.  From a modeling point of view are you maybe missing an aggregate root that owns both of these things?


text:
Q: Unable to locate Element is coming for dojo page I am getting an error like:

org.openqa.selenium.NoSuchElementException: Unable to locate element:
  {"method":"xpath","selector":"//*[@id='xwt_widget_notification_ValidationTextBox_6']"}

but the path which I mentioned is correct, the issue is my web page looks like the image which I shared.
It has got only one frame but it is a dojo page, I am able to perform all other operations except filling up the the value in the text box.

A: id attribute value of the element looks dynamically generated, so you should try using following-sibling axes of the xpath with WebDriverWait to wait until it's getting visible as below :-
WebElement textBox = new WebDriverWait(driver,10).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(.//td[contains(text(),'Display Name*')]/following-sibling::td)[1]//div[contains(@class, 'dijitInputField')]/input")));

Edited:- This element present inside an iframe with title Universal Device Template Configuration, try to switch that iframe before finding element as below :-
WebDriverWait wait = new WebDriverWait(driver,10);

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[title = 'Universal Device Template Configuration']")));

//now find the desire element
WebElement textBox = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(.//td[contains(text(),'Display Name*')]/following-sibling::td)[1]//div[contains(@class, 'dijitInputField')]/input")));


text:
Q: Elasticsearch exclude association of multiple terms I need to exclude from my search an association of different terms. Is there any clever way to do this kind of multi-term-exclusion?
Example: say I want to get all users Except the ones whose (last name is Doe) and (first name is John or Annie or without any first name value).
Expected results example:
first_name | last_name | Search result
--------------------------------------
Bob        | Doe       | appears
--------------------------------------
Annie      | Doe       | excluded
--------------------------------------
(null)     | Doe       | excluded
--------------------------------------
John       | Foo       | appears
--------------------------------------
(null)     | Foo       | appears

So far the best I did was the following request, but it does not work: in our example this request will exclude everyone whose last name is Doe, whatever the first name… and I cannot understand why?
GET user/_search
{
  "query": {
    "bool": {
      "must_not": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "last_name": "Doe"
                }
              }
            ]
          }
        },
        {
          "bool": {
            "should": [
              {
                "bool": {
                  "must": [
                    {
                      "terms": {
                        "first_name": [
                          "John",
                          "Annie"
                        ]
                      }
                    }
                  ]
                }
              },
              {
                "bool": {
                  "must_not": {
                    "exists": {
                      "field": "first_name"
                    }
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

Any help of an Elastic-sharp-eye on this will be much appreciated!

A: In must_not array document must not match any of the clause.
Your query basically translates to don't consider a document if last_name is Doe OR (first_name is annie or john or doesn't exists)
To work as AND place your query in bool
{
  "query": {
    "bool": {
      "must_not": [
        {
          "bool": {
            "must": [
              {
                "match": {
                  "last_name": "Doe"
                }
              },
              {
                "bool": {
                  "should": [
                    {
                      "terms": {
                        "first_name.keyword": [
                          "John",
                          "Annie"
                        ]
                      }
                    },
                    {
                      "bool": {
                        "must_not": {
                          "exists": {
                            "field": "first_name"
                          }
                        }
                      }
                    }
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
}


text:
Q: No notifications on iPhone 4 running jailbroken iOS 6.1.2 I have recently been given an unlocked iPhone 4 GSM, upon which I have installed a jailbroken (but not hacktivated) iOS 6.1.2 using snowbreeze. Calling seems to work fine, as does everything except notifications. They appear to be turned on in the notification centre settings, but I never get any.  I am not using the Apple Mail app, but I have Gmail, Facebook, Twitter installed and connected.  Can anyone suggest how I might fix this?

A: It appears that this was caused by restoring an iCloud backup from a previous install which had been hacktivated. Notifications will not work with a hacktivated iPhone, and it seems as though they won't work with a restored iCloud backup of a hacktivated iPhone either.
The solution is therefore to restore the jailbroken image and set it up as a new phone. This will then activate with Apple's servers and notifications will work.


text:
Q: Swagger 2.0 - Inconsistent Results From Swagger Source Swagger source below. When I run the swagger-tools validator, I receive no errors. When I load this in the editor, I see output but it is incorrect - it shows wrong types, and an incomplete Member object. When I try to use the code generator cli java tool, I get the following errors:

711 [main] ERROR io.swagger.models.properties.PropertyBuilder - no property for null, null
    712 [main] WARN io.swagger.util.PropertyDeserializer - no property from null, null, {ENUM=null, TITLE=null, DESCRIPTION=null, DEFAULT=null, PATTERN=null, DESCRIMINATOR=null, MIN_ITEMS=null, MAX_ITEMS=null, MIN_PROPERTIES=null, MAX_PROPERTIES=null, MIN_LENGTH=null, MAX_LENGTH=null, MINIMUM=null, MAXIMUM=null, EXCLUSIVE_MINIMUM=null, EXCLUSIVE_MAXIMUM=null, UNIQUE_ITEMS=null, EXAMPLE=null, TYPE=null, FORMAT=null}
    822 [main] ERROR io.swagger.codegen.DefaultCodegen - unexpected missing property for name null
    822 [main] WARN io.swagger.codegen.DefaultCodegen - skipping invalid property {
      "type" : "array"
    }

    {
  "swagger": "2.0",
  "info": {
    "title": "V1 Inmar CRM API",
    "description": "CRM API",
    "version": "1.0.0"
  },
  "produces": ["application/json"],
  "basePath": "/v1",
  "paths": {

    "/member": {
      "get": {
        "x-swagger-router-controller": "member",
        "tags": ["member"],
        "operationId": "GetMember",
        "parameters": [
          { "$ref": "#/parameters/x-inmar-rest-api-key" },
          { "$ref": "#/parameters/x-inmar-memberID" }
        ],
        "responses": {
          "200": {
            "description": "success",
            "schema": { "$ref": "#/definitions/Member" }
          }
        }
      },
      "post": {
        "x-swagger-route-controller": "member",
        "tags": ["member"],
        "operationId": "PostMember",
        "parameters": [
          { "$ref": "#/parameters/x-inmar-rest-api-key" },
          { "$ref": "#/parameters/x-inmar-memberID" },
          { "$ref": "#/parameters/member" }
        ],
        "responses": {
          "200": { "$ref": "#/responses/generic-200" }
        }
      }
    }
  },

  "parameters": {
    "x-inmar-rest-api-key": {
      "name": "X-Inmar-REST-API-Key",
      "description": "API Access Key.",
      "in": "header",
      "required": true,
      "type": "string"
    },
    "x-inmar-memberID": {
      "name": "X-Inmar-MemberID",
      "description": "Unique ID for member.",
      "in": "header",
      "required": true,
      "type": "string"
    },
    "member": {
      "description": "member object",
      "in": "body",
      "name": "body",
      "required": true,
      "schema": {
        "$ref": "#/definitions/Member"
      }
    }
  },

  "responses": {
    "generic-200": {
      "description": "Success"
    }
  },

  "definitions": {
    "Member": {
      "description": "member",
      "type": "object",
      "properties": {
        "active": {
          "type": "boolean",
          "default": true
        },
        "identity": {
          "type": "object",
          "required": [
            "user_id"
          ],
          "properties": {
            "user_id": {
              "type": "string",
              "maxLength": 50,
              "format": "email"
            },
            "password": {
              "type": "string",
              "minLength": 8,
              "maxLength": 20
            },
            "proxy_id": {
              "type": "integer"
            }
          }
        },
        "pii": {
          "type": "object",
          "description": "personally_identifiable_information.",
          "properties": {
            "alt_email": {
              "type": "string",
              "description": "Secondary email addresses that may or may not match the id.",
              "format": "email"
            },
            "first_name": {
              "type": "string",
              "minLength": 1,
              "maxLength": 25
            },
            "last_name": {
              "type": "string",
              "minLength": 1,
              "maxLength": 25
            },
            "primary_address_one": {
              "type": "string",
              "minLength": 1,
              "maxLength": 47
            },
            "primary_address_two": {
              "type": "string",
              "minLength": 1,
              "maxLength": 47
            },
            "primary_address_city": {
              "type": "string",
              "minLength": 1,
              "maxLength": 47
            },
            "primary_address_state": {
              "type": "string",
              "minLength": 2,
              "maxLength": 2,
              "description": "US states and US territories and Canadian provinces.",
              "enum": [
                "AA",
                "AB",
                "AE",
                "AK",
                "AL",
                "AP",
                "AR",
                "AS",
                "AZ",
                "BC",
                "CA",
                "CO",
                "CT",
                "DC",
                "DE",
                "FL",
                "FM",
                "GA",
                "GU",
                "HI",
                "IA",
                "ID",
                "IL",
                "IN",
                "KS",
                "KY",
                "LA",
                "MA",
                "MB",
                "MD",
                "ME",
                "MH",
                "MI",
                "MN",
                "MO",
                "MP",
                "MS",
                "MT",
                "NB",
                "NC",
                "ND",
                "NE",
                "NH",
                "NJ",
                "NL",
                "NM",
                "NS",
                "NT",
                "NU",
                "NV",
                "NY",
                "OH",
                "OK",
                "ON",
                "OR",
                "PA",
                "PE",
                "PR",
                "PW",
                "QC",
                "RI",
                "SC",
                "SD",
                "SK",
                "TN",
                "TX",
                "UK",
                "UT",
                "VA",
                "VI",
                "VT",
                "WA",
                "WI",
                "WV",
                "WY",
                "YT"
              ]
            },
            "primary_address_postal_code": {
              "type": "string",
              "minLength": 5,
              "maxLength": 10
            },
            "primary_address_country": {
              "type": "string",
              "enum": [
                "US",
                "CA"
              ]
            },
            "birthdate": {
              "type": "string"
            },
            "language_preference": {
              "type": "string"
            },
            "gender": {
              "type": "string",
              "enum": [
                "male",
                "female"
              ]
            }
          }
        },
        "profiles": {
          "type": "array",
          "items": {
            "properties": {
              "site_id": {
                "type": "integer"
              },
              "survey_data": {
                "type": "object",
                "required": [
                  "survey_id",
                  "survey_responses"
                ],
                "properties": {
                  "survey_id": {
                    "type": "integer",
                    "description": "Unique identifier of a profile survey."
                  },
                  "survey_responses": {
                    "type": "array",
                    "items": {
                      "required": [
                        "question_id",
                        "response_id",
                        "free_form_value"
                      ],
                      "properties": {
                        "question_id": {
                          "type": "integer",
                          "description": "Unique identifier of a profile survey question."
                        },
                        "response_id": {
                          "type": "integer",
                          "description": "Unique identifier of a profile question response.",
                          "default": 0
                        },
                        "free_form_value": {
                          "type": "string",
                          "description": "Consumer free form response",
                          "default": ""
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        },

        "optins": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/OptIn"
          }
        }
      }
    },

    "OptIn": {
      "description": "survey response",
      "type": "object",
      "properties":{
        "optin_id": {
          "type": "integer",
          "description": "Unique identifier of an opt in question/choice. e.g. newsletter"
        },
        "optin_value": {
          "type": "integer",
          "enum": [ 0, 1 ],
          "description": "Optin Response of 0=Optout and 1=Optin"
        }
      },
      "required": [
        "optin_id",
        "optin_value"
      ]
    }
  }
}


text:
Q: TreeViewItem.ItemContainerGenerator.ContainerFromItem inconsistent results I have a TreeView on my page.  It's bound to a collection of clients containing contracts, like:
public class Client
{
  public int ClientID { get; set; }
  public string Name { get; set; }
  public List<Contract> Contracts { get; set; }
}

public class Contract
{
  public int ContractID { get; set; }
  public int ClientID { get; set; }
  public string Name { get; set; }
}

The XAML for my TreeView is as follows:
<sdk:TreeView x:Name="tvClientContract" ItemsSource="{Binding ClientContracts}">
  <sdk:TreeView.ItemTemplate>
    <sdk:HierarchicalDataTemplate ItemsSource="{Binding Path=Contracts}">
      <TextBlock Text="{Binding Path=Name}" />
    </sdk:HierarchicalDataTemplate>
  </sdk:TreeView.ItemTemplate>
</sdk:TreeView>

Where ClientContracts is a List<Clients>.  The binding works fine and I have a hierarchical grid.
The issue that I'm having is when opening the form with the TreeView on it I want to select the current Client, I currently use the following code:
TreeViewItem client = (TreeViewItem)tvClientContract.ItemContainerGenerator.ContainerFromItem(aClient);

or
TreeViewItem client = (TreeViewItem)tvClientContract.ItemContainerGenerator.ContainerFromIndex(tvClientContract.Items.IndexOf(aClient));
client.IsSelected = true;

but this returns inconsistent results, for example I open the form when client 'ABC' is selected and client will be null.  I open it again when client 'ABC' is selected and it returns the correct TreeViewItem.  Has anyone came across this before or know anything I can look at to help solve the issue?
I run the above code within the Loaded event of the TreeView.

A: I figured out what's happening here, the clue is in the MSDN documentation for the return value of ItemContainerGenerator.ContainerFromItem():

A UIElement that corresponds to the
  given item. Returns null if the item
  does not belong to the item
  collection, or if a UIElement has not
  been generated for it.

It looks like when null is returned, a UIElement hasn't been created for the item yet.
I got round this by using
tvClientContract.UpdateLayout();
to update the layout and ensure a UIElement exists before calling
ItemContainerGenerator.ContainerFromItem()

A: I think that there could be some condition where "UpdateLoayout will not work":
if the TreeView is in recycling mode and the item is not in the visible portion and/or also in a "add" operation where the TreeViewItem is created on another thread.
The solution is to use similar solution as I describe in:
WPF: Select TreeViewItem broken past the root level


text:
Q: Set a field to be editable by list owners only I have a list that has field A and field B that is set to ReadOnly by PowerShell. Now, these fields are ReadOnly for everyone. I would like these fields to be editable only for the list owners. Is there any PowerShell commands that will let these fields be editable only for the owners?

A: To put it simply, no. SharePoint does not have a concept for column-level security, which is what you're asking for. Either you may contribute to a list/list item and all columns belonging to that list/list item, or you cannot.
The way people often accomplish this is by exposing the list in such a way that hides the columns on the New/Edit forms or by extracting the list away entirely (e.g. creating New/Edit forms in PowerApps) and selectively displaying fields as required.
This doesn't remove an individual's ability to go to the back end list and modify the data directly, including the column you don't want to modify it, but in my personal experience, abstracting/modifying the new/edit forms is usually "good enough".

A: As it is mentioned by No SharePoint list can do this but There are two aspects You can take as a workaround. I am Assuming You have Access to PowerApps and MS-Flow
Solution one: Using Custom Form
You need to create a Custom Form for that specific List. The fields should not be read-Only
In your custom Form, You need to define Admin/Owner as Variable. If a none admin user whats to edit the form Make the field Disable or Hiden.
Solution Two: Hide the field(column)
This is a lot easier.
Change that Read-only field to editable field(Let's call it Field B) and Add this to the views only accessible by Admin(owner)
then create a calculated column which reads from Field B. We call this Field C
Don't Let the User Create View or edit list setting(give this permission only to Owner/ Admin)
create custom form in Powerups/info Path without Field B
Solution three: Using MS Flow
In this aspect we let every user change the field But update the list only if the user is an admin/Owner
Change those fields to Read-Write Field
Enable version History on the list
Enable Append comment on the field
Create a flow which prevents the field from being updated if the user who changed it is not the owner. This flow updates the field with previous value if the user who changed it is not Owner


text:
Q: Acumatica Inventory Summary Inquiry all items via REST APi I need to retrieve the inventory summary for all Stock Items so that I can update an external site's inventory according to the "Available For Shipment" field on the inventory summary.  I have attempted running the inventory summary via the rest API using the following method after logging in:
URL: https://mycompany.acumatica.com/entity/Default/6.00.001/InventorySummaryInquiry

Method: PUT

Request Body:
{
    "InventoryID": "CW-500-MC-30"
}

However I receive this response:
{
    "message": "The request is invalid.",
    "modelState": {
        "": [
            "Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path 'InventoryID', line 2, position 30."
        ]
    }
}

If there is a way to run the inquiry and have it return ALL stock items in an array, that would be ideal.
If that's not possible, what do I need to change to get the individual stock item inventory summary to work?
UPDATE:
After modifying my request body as @samol518 suggested, the request worked, but returned a very limited set of data (below).  I'm looking to get to the "quantity available for shipment".  Do I need to provide additional parameters to get more data returned?
{
    "id": "bf8e0bbc-63dc-4491-802d-090367af203a",
    "rowNumber": 1,
    "note": null,
    "ExpandByLotSerialNumber": {},
    "InventoryID": {
        "value": "CW-500-MC-30"
    },
    "LocationID": {},
    "WarehouseID": {},
    "custom": {},
    "files": []
}

A: If I am not mistaken the correct structure for the Request Body should resemble the following :
Request Body :
{
    "InventoryID": {"value": "CW-500-MC-30"}
}

Though if you want to retrieve all Stock Item, you could try and customize the inquiry in order to do so.
Update:
in order to retrieve all record, you might notice that the result fields are in a sub entity in the endpoint definition on the Web Service Endpoint screen (SM207060).
in order to return the data for these detail type sub entities, you must add the expand key word to your URL in the following format.
$expand=results
So your final URL should look like :
https://mycompany.acumatica.com/entity/Default/6.00.001/InventorySummaryInquiry?$expand=Results


text:
Q: How to concatenate 2 arrays by index order? Im trying to figure out how to use highcharts with the dates. Im doing an API call and have in one variable clicks and in another variable the dates. I want to concatenate these 2 arrays but following the index.
For example
array1 = [timestamp1 , timestamp2, timestamp3]
array2 =[ clicks1, clicks2, clicks3 ]

I want to have then an array that is
data =  0: [timestamp1, click1],
        1: [timestamp2, click2],
        2: [timestamp3, click3]

I tried doing var data = array1.concat(array2);
but it concatenates in order
data = [timestamp1 , timestamp2, timestamp3 , clicks1, clicks2, clicks3 ]

my original code looks like this:

    getChartData(){
            axios.get("http://localhost:3003/desktop").then(api =>{
                const data = api.data;
              // console.log(data)

            var date =[];
                var clicks = []
                var impressions =[]

                for ( var i in data)
                {
                    date.push(data[i].Date)
                    clicks.push(data[i].Clicks)
                    impressions.push(data[i].Impressions)
                }

                var cd = date.concat(clicks);
                console.log(cd)

                 this.setState({
                    clicks:clicks,
                    date:date,
                    impressions:impressions,
                    cd: cd
                 })
            });

        }

This might be a very basic question, but I'm a beginner and could not find anything related.Any help would be appreciated.

A: You could parse all the keys of one of your array and then retrieve the value from both array using that key. Ex:
let output = []
Object.keys(array1).forEach((key) => {
    output.push(array1[key], array2[key]);
});

Here i'm using the forEach array function but you could achieve the same goal using a normal foreach loop.
Please note that this code is untested, it is just to show you the basic idea.

A: Assuming that both arrays are the same length you could use something like this. You can do the iteration a variety of ways.

const arr1 = ['a', 'b', 'c'];
const arr2 = ['A', 'B', 'C'];

const arrPaired = arr1.map((ent, i) => [ent, arr2[i]]);

console.log(arrPaired);


text:
Q: How to dynamically add indexes values of an array in C#? I have an array where the first two smallest values have to be added, and consequently the result has to be added to next smallest and so on until it reaches the end of the array to give a final total.
However, how can I dynamically modify the method/function so if the values changes and I have 6 vehicles and 6 specs values in the array, the return of the method/function total is not restricted to just 4 indexes.
The array values are unsorted, so in order to add the first smallest, it has to be sorted. Once that's done it adds the values of the new array.
Here's what I've tried:
public static int vehicles = 4;
public static int[] specs = new int[] { 40, 8, 16, 6 };

public static int time(int vehicles, int[] specs)
{
    int newValue = 0;

    for (int i = 1; i < vehicles; i++)
    {
        newValue = specs[i];
        int j = i;

        while (j > 0 && specs[j - 1] > newValue)
        {
            specs[j] = specs[j - 1];
            j--;
        }
        specs[j] = newValue;
    }

    // How can I dynamically change this below:
    int result1 = specs[0] + specs[1];
    int result2 = result1 + specs[2];
    int result3 = result2 + specs[3];
    int total = result1 + result2 + result3;

    return total; // Returns 114
}

Here's the idea of how it works:
4, [40, 8, 16, 6] = 14 --> [40, 14, 16] = 30 --> [40, 30] = 70 ==>> 14 + 30 + 70 = 114
6, [62, 14, 2, 6, 28, 41 ] = 8 --> [62, 14, 8, 28, 41 ] --> 22 [62, 22, 28, 41 ] --> 50
   [62, 50, 41 ] --> 91 [62, 91 ] --> 153 ==> 8 + 22 + 50 + 91 + 153 = 324

A: First off, if you are not restricted to arrays for some weird reason use List<int> and your life will be easier.
List<int> integers = { 14, 6, 12, 8 };

integers.Sort();

integers.Reverse();

while( integers.Count > 1 )
{
    int i = integers[integers.Count - 1];
    int j = integers[integers.Count - 2];
    integers[integers.Count - 2] = i + j;
    integers.RemoveAt(integers.Count - 1);
}

var result = integers[0];

P.S.: This can be easily modified to operate on the array version, you can't RemoveAt() from an array but can separately maintain a lastValidIndex.

A: I would use Linq.
Enumerable.Range(2, specs.Length - 1)
    .Select(i => specs
        .Take(i)
        .Sum())
    .Sum();

Explanation:

*

*We take a range starting from 2 ending with specs.Length.

*We sum the first i values of specs where i is the current value in the range.

*After we have all those sums, we sum them up as well.

To learn more about linq, start here.
This code only works if the values have been sorted already.
If you want to sort the values using linq, you should use this:
IEnumerable<int> sorted = specs.OrderBy(x => x);

Enumerable.Range(2, sorted.Count() - 1)
    .Select(i => sorted
        .Take(i)
        .Sum())
    .Sum();

The OrderBy function needs to know how to get the value it should use to compare the array values. Because the array values are the values we want to compare we can just select them using x => x. This lamba takes the value and returns it again.

A: See comments in code for explanation.
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        //var inputs = new [] { 40, 8, 16, 6 }; // total = 114
        var inputs = new[] { 62, 14, 2, 6, 28, 41 }; // total = 324

        var total = 0;
        var query = inputs.AsEnumerable();
        while (query.Count() > 1)
        {
            // sort the numbers
            var sorted = query.OrderBy(x => x).ToList();
            // get sum of the first two smallest numbers
            var sumTwoSmallest = sorted.Take(2).Sum();
            // count total
            total += sumTwoSmallest;
            // remove the first two smallest numbers
            query = sorted.Skip(2);
            // add the sum of the two smallest numbers into the numbers
            query = query.Append(sumTwoSmallest);
        }
        Console.WriteLine($"Total = {total}");

        Console.WriteLine("Press any key...");
        Console.ReadKey(true);
    }
}

I benchmark my code and the result was bad when dealing with large dataset. I suspect it was because of the sorting in the loop. The sorting is needed because I need to find the 2 smallest numbers in each iteration. So I think I need a better way to solve this. I use a PriorityQueue (from visualstudiomagazine.com) because the elements are dequeued based on priority, smaller numbers have higher priority in this case.
long total = 0;
while (pq.Count() > 0)
{
    // get two smallest numbers when the priority queue is not empty
    int sum = (pq.Count() > 0 ? pq.Dequeue() : 0) + (pq.Count() > 0 ? pq.Dequeue() : 0);
    total += sum;
    // put the sum of two smallest numbers in the priority queue if the queue is not empty
    if (pq.Count() > 0) pq.Enqueue(sum);
}

Here's some benchmark results of the new (priority queue) code and the old code in release build. Results are in milliseconds. I didn't test the 1 million data with the old code because it's too slow.
+---------+----------+-------------+
|  Data   |   New    |     Old     |
+---------+----------+-------------+
|   10000 |   3.9158 |   5125.9231 |
|   50000 |  16.8375 | 147219.4267 |
| 1000000 | 406.8693 |             |
+---------+----------+-------------+

Full code:
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;

class Program
{
    static void Main()
    {
        const string fileName = @"numbers.txt";
        using (var writer = new StreamWriter(fileName))
        {
            var random = new Random();
            for (var i = 0; i < 10000; i++)
                writer.WriteLine(random.Next(100));
            writer.Close();
        }

        var sw = new Stopwatch();

        var pq = new PriorityQueue<int>();
        var numbers = File.ReadAllLines(fileName);
        foreach (var number in numbers)
            pq.Enqueue(Convert.ToInt32(number));

        long total = 0;
        sw.Start();
        while (pq.Count() > 0)
        {
            // get two smallest numbers when the priority queue is not empty
            int sum = (pq.Count() > 0 ? pq.Dequeue() : 0) + (pq.Count() > 0 ? pq.Dequeue() : 0);
            total += sum;
            // put the sum of two smallest numbers in the priority queue if the queue is not empty
            if (pq.Count() > 0) pq.Enqueue(sum);
        }
        sw.Stop();
        Console.WriteLine($"Total = {total}");
        Console.WriteLine($"Time = {sw.Elapsed.TotalMilliseconds}");

        total = 0;
        var query = File.ReadAllLines(fileName).Select(x => Convert.ToInt32(x));
        sw.Restart();
        while (query.Count() > 0)
        {
            // sort the numbers
            var sorted = query.OrderBy(x => x).ToList();
            // get sum of the first two smallest numbers
            var sumTwoSmallest = sorted.Take(2).Sum();
            // count total
            total += sumTwoSmallest;
            // remove the first two smallest numbers
            query = sorted.Skip(2);
            // add the sum of the two smallest numbers into the numbers
            if (query.Count() > 0)
                query = query.Append(sumTwoSmallest);
        }
        sw.Stop();
        Console.WriteLine($"Total = {total}");
        Console.WriteLine($"Time = {sw.Elapsed.TotalMilliseconds}");

        Console.WriteLine("Press any key...");
        Console.ReadKey(true);
    }
}

PriorityQueue code:
using System;
using System.Collections.Generic;

// From http://visualstudiomagazine.com/articles/2012/11/01/priority-queues-with-c.aspx
public class PriorityQueue<T> where T : IComparable<T>
{
    private List<T> data;

    public PriorityQueue()
    {
        this.data = new List<T>();
    }

    public void Enqueue(T item)
    {
        data.Add(item);
        int ci = data.Count - 1; // child index; start at end
        while (ci > 0)
        {
            int pi = (ci - 1) / 2; // parent index
            if (data[ci].CompareTo(data[pi]) >= 0)
                break; // child item is larger than (or equal) parent so we're done
            T tmp = data[ci];
            data[ci] = data[pi];
            data[pi] = tmp;
            ci = pi;
        }
    }

    public T Dequeue()
    {
        // assumes pq is not empty; up to calling code
        int li = data.Count - 1; // last index (before removal)
        T frontItem = data[0];   // fetch the front
        data[0] = data[li];
        data.RemoveAt(li);

        --li; // last index (after removal)
        int pi = 0; // parent index. start at front of pq
        while (true)
        {
            int ci = pi * 2 + 1; // left child index of parent
            if (ci > li)
                break;  // no children so done
            int rc = ci + 1;     // right child
            if (rc <= li && data[rc].CompareTo(data[ci]) < 0) // if there is a rc (ci + 1), and it is smaller than left child, use the rc instead
                ci = rc;
            if (data[pi].CompareTo(data[ci]) <= 0)
                break; // parent is smaller than (or equal to) smallest child so done
            T tmp = data[pi];
            data[pi] = data[ci];
            data[ci] = tmp; // swap parent and child
            pi = ci;
        }
        return frontItem;
    }

    public T Peek()
    {
        T frontItem = data[0];
        return frontItem;
    }

    public int Count()
    {
        return data.Count;
    }

    public override string ToString()
    {
        string s = "";
        for (int i = 0; i < data.Count; ++i)
            s += data[i].ToString() + " ";
        s += "count = " + data.Count;
        return s;
    }

    public bool IsConsistent()
    {
        // is the heap property true for all data?
        if (data.Count == 0)
            return true;
        int li = data.Count - 1; // last index
        for (int pi = 0; pi < data.Count; ++pi)
        { // each parent index
            int lci = 2 * pi + 1; // left child index
            int rci = 2 * pi + 2; // right child index

            if (lci <= li && data[pi].CompareTo(data[lci]) > 0)
                return false; // if lc exists and it's greater than parent then bad.
            if (rci <= li && data[pi].CompareTo(data[rci]) > 0)
                return false; // check the right child too.
        }
        return true; // passed all checks
    }
    // IsConsistent
}
// PriorityQueue

Reference:

*

*https://visualstudiomagazine.com/articles/2012/11/01/priority-queues-with-c.aspx

*https://en.wikipedia.org/wiki/Priority_queue

A: I would go with the simplest version of a one line solution using LINQ:
Array.Sort(specs);
int total = specs.Select((n, i) => specs.Take(i + 1).Sum()).Sum() - (specs.Length > 1 ? specs[0] : 0);

A: You can simply sort it using Array.Sort(), then get the sums in a new array which starts with the smallest value and add each next value to the most recent sum, the total will be the value of the last sum.
public static int time(int vehicles, int[] specs)
{
    int i, total;
    int[] sums = new int[vehicles];
    Array.Sort(spec);
    sums[0] = specs[0];
    for (i = 1; i < vehicles; i++)
        sums[i] = sums[i - 1] + spec[i];
    total = sums[spec - 1];
}


text:
Q: treat 0x00 as NULL I have a large file (over 1gb) containing lots of music data, and I want to read this file using the COPY command. It is one large table. with a lot of tracks.
However, at row 372032 there are a few tracks that have no genre, but a 0x00 character instead. After some googling I found out the 0x00 character is a NULL symbol, but postgresql is having problems reading this.
What I would like is that postgresql treats 0x00 as NULL. Looking at the postgresql documentation for COPY, and saw the copy command has an option for reading specific strings as NULL. I tried this, but couldn't get it by adding the option NULL '\0x00' (I also tried '\x00', '0x00', 'x00'). I think this is because postgresql first wants to be able to read something, before it can replace.
I ran the following script
COPY music
FROM 'mw_spotify_labels.csv'
WITH DELIMITER '    '
NULL '\0x00'
encoding 'latin1';

This gives me the following error message
ERROR:  invalid byte sequence for encoding "LATIN1": 0x00
CONTEXT:  COPY music, line 372032
********** Error **********

ERROR: invalid byte sequence for encoding "LATIN1": 0x00
SQL state: 22021
Context: COPY music, line 372032

I tried using a few different encodings (did not work). I also tried FART that replaces 0x00 with a space, but I couldn't find a nice way to define 0x00.
Does anybody know a way to either get the NULL working, setting up a replace 0x00 with ' ' or an other solution that makes it possible for me to import this file?

A: Edit file by Vim, and replace all \0x00 to ''. That works.
:%s/\%x00//g


text:
Q: Deploy only a javadoc My project uses asciidoclet to generate javadocs. Turns out that with Java 9 the Javadoc API has changed so much that the asciidoclet used by Maven's javadoc-plugin was never ported to Java 9+. So the only way to generate the Javadoc is by running it under Java 8.
I can exclude creating the Javadoc when deploying to maven central. But how can I just release the Javadoc to sonatype?

A: It is simple
mvn javadoc:jar deploy:deploy

My mistake was that I used javadoc:javadoc. Stupid me.
So compile and deploy under Java 9+ with -Dmaven.javadoc.skip=true and then run under java 8 again with javadoc and deploy. Works for now.


text:
Q: if statements with different regular expression parameters Hi I am trying to read tags on a list of words, the list has words like (TMConnects(MEN) what(WP) happened(VB) to(TO) your(ADV) my(ADV) tm(N) website(N) i(N) can(ADV) access(N) to(TO) view(N) my(ADV) bills(N) ) I am trying to use if statements and regular expressions to read each tag so I can categorise the words appropriately.
Here is the code I tried
 foreach (string word in tokensList)
        {
            //Verbs
            Match match_verb = Regex.Match(word, @"[a-zA-Z]+\(vb\)");
            if (match_verb.Success)
            {
                Console.WriteLine(word + "v");
                Verbs.Add(word);
            }
            else
            {
                //Nouns
                Match match_noun = Regex.Match(word, @"[a-zA-Z]+\(n\)");
                if (match_noun.Success)
                {
                    Console.WriteLine(word + "n");
                    Nouns.Add(word);
                }
                else
                {
                    //Adverb(Ad)
                    Match match_adverb = Regex.Match(word, @"[a-zA-Z]+\(adv\)");
                    if (match_adverb.Success)
                    {
                        Console.WriteLine(word + "adv");
                        Adverbs.Add(word);
                    }
                    else
                    {
                        //Adjective(Adj)
                        Match match_adj = Regex.Match(word, @"[a-zA-Z]+\(adj\)");
                        if (match_adj.Success)
                        {
                            Console.WriteLine(word + "adj");
                            Adjectives.Add(word);
                        }
                        else
                        {
                            //Mention(Men)
                            Match match_men = Regex.Match(word, @"[a-zA-Z]+\(men\)");
                            if (match_men.Success)
                            {
                                Console.WriteLine(word + "men");
                                Mentions.Add(word);
                            }
                            else
                            {
                                //Object(KNK)
                                Match match_obj = Regex.Match(word, @"[a-zA-Z]+\(knk\)");
                                if (match_obj.Success)
                                {
                                    Console.WriteLine(word + "obj");
                                    Objects.Add(word);
                                }
                                else
                                {
                                    //Features(KT)
                                    Match match_feature = Regex.Match(word, @"[a-zA-Z]+\(kt\)");
                                    if (match_feature.Success)
                                    {
                                        Console.WriteLine(word + "ft");
                                        Features.Add(word);
                                    }
                                    else
                                    {
                                        //break;
                                    }
                                }
                            }
                        }
                    }
                }

Please help me.

A: If I was to lowercase all of the text between the brackets from the list you've provided, I get all the correct results back. So, I'm going to assume the problem is as Mark suggested: you have a problem with your regex being case sensitive and to fix that all you have to do is provide the RegexOptions.IgnoreCase option.
So instead of Regex.Match(word, @"[a-zA-Z]+\(vb\)")
it would be something like this Regex.Match(word, @"[a-z]+\(vb\)", RegexOptions.IgnoreCase).
However, following Marks suggestions once more, you are most likely approaching the problem in a way that's catered too much for a specific solution. That is, instead of having an if-else statement for each condition (attempting to perform a regular expression match each time), you could perform a single match using a more generic regular expression and utilize the tools .NET provides to come up with a more flexible solution.
    foreach (var match in
        tokensList.Select(
            word =>
                // Two capturing groups: "word" (unnecessary in your case) and "type",
                // where "word" contains the word only (e.g. TMConnects) and "type" contains the type only (e.g. MEN).
                Regex.Match(
                    word,
                    // Match any letters appearing one or more times followed by an opening bracket ('('), anything that
                    // isn't a closing bracket and a closing bracket (')').
                    @"^(?<word>[a-z]+)\((?<type>[^\)]+)\)$",
                    // Tell the regular expression engine to ignore the casing.
                    RegexOptions.IgnoreCase))
                    // Filter out words that don't match the regular expression.
                    .Where(match => match.Success))
    {
        // The whole word (including the type.
        var word = match.Value;
        // The type lower-cased, for convenience.
        var type = match.Groups["type"].Value.ToLowerInvariant();
        switch (type)
        {
            case "vb":
                Console.WriteLine(word + "v");
                Verbs.Add(word);
                break;
            case "n":
                Console.WriteLine(word + "n");
                Nouns.Add(word);
                break;
            case "adv":
                Console.WriteLine(word + "adv");
                Adverbs.Add(word);
                break;
            case "adj":
                Console.WriteLine(word + "adj");
                Adjectives.Add(word);
                break;
            case "men":
                Console.WriteLine(word + "men");
                Mentions.Add(word);
                break;
            case "knk":
                Console.WriteLine(word + "obj");
                Objects.Add(word);
                break;
            case "kt":
                Console.WriteLine(word + "ft");
                Features.Add(word);
                break;
        }
    }


text:
Q: how to get an input from the keyboard without interrupting code? i.e. checking keyboard status currently i am using int 16,1. for some reason in my code, the second time i use int 16,1(in a game loop), it stays on the same value i pressed the first time, regardless if it still pressed or not. i have given up and i am asking if there is another way to get keyboard status without stopping the code.
i have tried debugging it for multiple hours, running turbo debugger, ran it through multiple teachers, no source for the problem.
this is a gist for the full code if needed
https://gist.github.com/yuvyuv2005/09ab20fd321c70ce598d6bb4151990cf#file-nole-asm
    Proc Get_Input

    xor ax, ax
    mov ah, 1h
    int 16h
    jz noInp

    push ax
    call Check_Input
    noInp:

    ret
    endp Get_Input

    Key_Pressed EQU [bp+4]
    Proc Check_Input
    push bp
    mov bp, sp
    mov [RightMole], 0

    mov ax, Key_Pressed
    mov [Num_Pressed], al

    Num7:
    mov al, [Num_Pressed]
    sub al, "0"

    cmp al, 7
    JNE Num4

    cmp [MoleHole], 0
    JNE Num4

    push [word ptr MoleHole]
    call Remove_Mole
    inc [Scorearr+6]
    mov [RightMole], 1

    Num4:
    mov al, [Num_Pressed]
    sub al, "0"
    cmp al, 4
    JNE Num1

cmp [MoleHole], 1
JNE Num1
push [word ptr MoleHole]
call Remove_Mole
inc [Scorearr+6]
mov [RightMole], 1

Num1:
mov al, [Num_Pressed]
sub al, "0"
cmp al, 1
JNE Num8

cmp [MoleHole], 2
JNE Num8
push [word ptr MoleHole]
call Remove_Mole
inc [Scorearr+6]
mov [RightMole], 1

Num8:
mov al, [Num_Pressed]
sub al, "0"
cmp al, 8
JNE Num5

cmp [MoleHole], 3
JNE Num5
push [word ptr MoleHole]
call Remove_Mole
inc [Scorearr+6]
mov [RightMole], 1

Num5:
mov al, [Num_Pressed]
sub al, "0"
cmp al, 5
JNE Num2

cmp [MoleHole], 4
JNE Num2
push [word ptr MoleHole]
call Remove_Mole
inc [Scorearr+6]
mov [RightMole], 1

Num2:
mov al, [Num_Pressed]
sub al, "0"
cmp al, 2
JNE Num9

cmp [MoleHole], 5
JNE Num9
push [word ptr MoleHole]
call Remove_Mole
inc [Scorearr+6]
mov [RightMole], 1

Num9:
mov al, [Num_Pressed]
sub al, "0"
cmp al, 9
JNE Num6

cmp [MoleHole], 6
JNE Num6
push [word ptr MoleHole]
call Remove_Mole
inc [Scorearr+6]
mov [RightMole], 1

Num6:
mov al, [Num_Pressed]
sub al, "0"
cmp al, 6
JNE Num3

cmp [MoleHole], 7
JNE Num3
push [word ptr MoleHole]
call Remove_Mole
inc [Scorearr+6]
mov [RightMole], 1

Num3:
mov al, [Num_Pressed]
sub al, "0"
cmp al, 3
JNE finish

cmp [MoleHole], 8
JNE finish
push [word ptr MoleHole]
call Remove_Mole
inc [Scorearr+6]
mov [RightMole], 1

actual game loop
Game_Loop:

    call DrawMole

    ; push offset Scorearr
    ; push 0
    ; push 2
    ; call Print_str
    ; add [Scorearr+6], "0"

    ;cx is how many times i want to wait 0.55 seconds before the player loses. the number here is very high for debugging reasons, ususally its a lot lower.
    mov cx, 640

    KeyPressLoop:
        push cx

        call Get_Input
        cmp [RightMole], 1
        JE Game_Loop
        pop cx
        push 1
        call Delay

    Loop KeyPressLoop
    jmp GameOver

this is the delay function, might be something wrong with it too although from what i know its perfectly fine.
    proc delay
    push bp
    mov bp, sp
    push ax
    push cx
    push es

    ticks equ [bp + 4]
    clock equ es:6Ch

    mov ax, 40h
    mov es, ax
    mov ax, [clock]

    mov cx, ticks
    delayLoop:
        mov ax, [clock]
    tick:
            cmp ax, [clock]
            je tick
        loop delayLoop

    pop es
    pop cx
    pop ax
    pop bp
    ret 2
    endp delay

this is code for a whac a mole game, hence all the mole related ints.
this code is the one checking the input of the user, using numpad. from what ive read int 16, 1 puts the ASCII value of the number pressed in AL. (the game is played using numpad) if you are running the code, turn on numlock only after opening the emulator. on dosbox the numlock only applies after opening dosbox. the first time a mole should be whacked, the program works. the moment the second mole shows up, the code goes into an infinite loop in the last button pressed in the Check Input command. i found that out using a debug_rect proc. how the game should actually work is if the player pressed the right number on the numpad, the game removes that mole and draws a new one randomly.
it works for the first mole, but gets stuck in an infinite loop somewhere after drawing the second one.