text:
Q: Kernel restarting running Ipython + PyMC I'm getting an error in the Ipython Notebook saying The kernel appears to have died. It will restart automatically. when I run the following code:
from sklearn.datasets import load_boston
import numpy as np
import pymc as pm
import pandas as pd

boston = load_boston()
features = ['INDUS', 'NOX', 'RM', 'TAX', 'PTRATIO', 'LSTAT']
df = pd.DataFrame(boston.data, columns=boston.feature_names)
X = np.array(df.ix[:, features])
y = boston.target

gamma = pm.Binomial('gamma', 1, 0.5, size=len(features))
var = pm.Lambda('var', lambda gamma=gamma: (1-gamma)*0.001 + gamma*10)
prec = pm.Lambda('prec', lambda var=var: 1.0/var)
b = pm.Normal('b', 0, prec)
int_ = pm.Normal('int_', 0, 0.01)
taue = pm.Gamma('taue', 0.1, 0.1)
mu = int_ + X[:,0]*b[0] + X[:,1]*b[1] + X[:,2]*b[2] + X[:,3]*b[3] + X[:,4]*b[4] + X[:,5]*b[5]
observed = pm.Normal('obs', mu, taue, observed=True, value=y)
M = pm.MCMC([observed, mu, int_, b, prec, var, gamma])
M.sample(10000, 500, 5)

pm.Matplot.plot(M)

In case it is relevant, I'm trying to reproduce an example of Bayesian variable selection from this page (WinBUGS code, page 14). Sometimes the kernel fails when I run M.sample() but most of the times the error appears when running pm.Matplot.plot(M)
I also tried to use ipython qtconsole but the result is the same. In ipython, it causes a segmentation fault. I'm using a conda environment with ipython 2.3.0, matplotlib 1.4.0, pandas 0.14.1, scikit-learn 0.15.2, pymc 2.3.4 and python 2.7.8. I created a new environment with ipython 3.0.0, but this issue remains.
Can anyone reproduce this issue?
UPDATE:
I tried this example in an EC2 instance using a fresh Anaconda environment and this is the only example I could find that gives errors. The only piece of code I needed to add was the following:
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt

Therefore, I was basically running this in ipython:
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
%run model

where model is a file containing exactly the same code I posted initially. The errors change a bit. For example:
IndexError                                Traceback (most recent call last)
/home/ubuntu/model.py in <module>()
     16 int_ = pm.Normal('int_', 0, 0.01)
     17 taue = pm.Gamma('taue', 0.1, 0.1)
---> 18 mu = int_ + X[:,0]*b[0] + X[:,1]*b[1] + X[:,2]*b[2] + X[:,3]*b[3] + X[:,4]*b[4] + X[:,5]*b[5]
     19 observed = pm.Normal('obs', mu, taue, observed=True, value=y)
     20 M = pm.MCMC([observed, mu, int_, b, prec, var, gamma])

IndexError: index 0 is out of bounds for axis 1 with size -4611686018427387904

*** Error in `/home/ubuntu/anaconda/envs/env3/bin/python': double free or corruption (out): 0x00000000028a0b00 ***
Aborted (core dumped)

Another one:
In [5]: %run model
 [-----------------100%-----------------] 10000 of 10000 complete in 17.7 sec/home/ubuntu/anaconda/envs/env3/lib/python2.7/site-packages/numpy/core/fromnumeric.py:2499: VisibleDeprecationWarning: `rank` is deprecated; use the `ndim` attribute or function instead. To find the rank of a matrix see `numpy.linalg.matrix_rank`.
  VisibleDeprecationWarning)
Plotting int_
Plotting prec_0
Plotting prec_1
Plotting prec_2
Plotting prec_3
Plotting prec_4
Plotting prec_5
Plotting var_0
Plotting var_1
Plotting var_2
Plotting var_3
Plotting var_4
Plotting var_5
Plotting gamma_0
Plotting gamma_1
Plotting gamma_2
Plotting gamma_3
Plotting gamma_4
Plotting gamma_5
Plotting b_0
Plotting b_1
Plotting b_2
Plotting b_3
Plotting b_4
Plotting b_5
*** Error in `/home/ubuntu/anaconda/envs/env3/bin/python': double free or corruption (out): 0x00000000023dc940 ***
Aborted (core dumped)

Again, similar to the error above:
In [6]: %run model
 [-----------------100%-----------------] 10000 of 10000 complete in 18.4 secPlotting var_0
*** Error in `/home/ubuntu/anaconda/envs/env3/bin/python': double free or corruption (out): 0x00000000035f0f10 ***
Aborted (core dumped)

This one occurs earlier:
In [13]: gamma = pm.Binomial('gamma', 1, 0.5, size=len(features))
Segmentation fault (core dumped)

And finally:
In [22]: M.sample(10000, 500, 5)
Segmentation fault (core dumped)

At times, the code runs correctly and produces several plots. For comparison, I also ran this example and this one without issues.
This is the list of packages I installed in the conda environment.

A: This runs just fine here, with Python 2.7.6 and IPython 3.0.0-dev. Can you try upgrading/changing your Matplotlib?


text:
Q: Words in common (Python) So I've been having a lot of trouble with this problem. I have to find the words in common from an English.txt and a French.txt.
english.txt:
circle
table
year
competition

french.txt:
bien
competition
merci
air
table

My desired output:
competition
table

However, when I did my code I didn't include french text but got:
competition
table
This is my code:
filenameI = "english.txt"
file = open(filenameI, "r")
for line in file:
   print(line)

A: with open(filenameI) as I:
    contentI = I.read().splitlines()

with open(filenameF) as F:
    contentF = F.read().splitlines()

Then go ahead and loop through contentF and contentI and compare the two, printing when they match
for i in contentI:
    for f in contentf:
        if i == f:
          print(i)

Hope that helps :)

A: Try this:
filenameI = "english.txt"
filename2 = "french.txt"
file = open(filenameI, "r")
file2 = open(filenameI, "r")

list1 = [line for line in file]
list2 = [line for line in file2]

out = set(list1) - (set(list1) - set(list2))

Note that it is better to open file using with.

A: Let me know if this worked out for you or not!
e_words = set(line.strip() for line in open("english.txt")) # speck of sanity check here
f_words = set(line.strip() for line in open("french.txt"))

print e_words & f_words
# please iterate this and do whatevs..

EDIT 1 (BEING CONCISE IS A GOOD THING BUT THIS TIME NO DANGLING FILE HANDLERS)
output = None
with open("english.txt") as e, open("french.txt") as f:
     output = set([line.strip() for line in e.readlines()]) & set([line.strip() for line in f.readlines()])
print output

A: Use a setas it will give you an intersection between two collections.
Also use a with to handle closing the file automatically.
with open('english.txt') as eng, open('french.txt') as fr:
    print(set(x.strip() for x in eng).intersection(x.strip() for x in set(fr)))

Output:
{'table', 'competition'}

A: Try this:
file1 = open("english.txt", "rb+")
file2 = open("french.txt", "rb+")

list1 = [line for line in file1]
list2 = [line for line in file2]

common1 = (set(list1).intersection(list2))

A: This is my answer:
e = set(open("english.txt"))
f = set(open("french.txt"))
for c in e & f:
print(c, end="")

I just make two sets out of the two texts. Then use a loop where for every common word (using "e & f") it lists them out on each line.
p.s.
end=""

just makes sure there isn't an extra line between each word.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't Post data containing $ in a key to Firebase I'm attempting to post some data into Firebase (relative part of the URL is /messages.json). The following request content:
{"gsx$enddate":"sometime"}

Gives the following error:

Invalid data; couldn't parse JSON object, array, or value. Perhaps you're using invalid characters in your key names.

This is valid JSON however. What am I doing wrong?

A: It's supposed to be a valid JSON but it seems like it's a limitation for FireBase
From FireBase Documentation:

Character Set Limitations
Note that URLs used to construct Firebase references may contain any
unicode characters except:

*

*. (period)

*$ (dollar sign)

*[ (left square bracket)

*] (right square bracket)

*# (hash or pound sign)

*/ (forward slash)


text:
Q: How to get the current height of a BottomSheetDialogFragment programmatically? Or are there any default values for the different states? I want to change a view size based on the current size of the BottomSheetDialogFragment programmatically, but I don't know how to get or calculate it. I need this information in the onStateChanged callback.

A: On sliding of BottomSheetDialogFragment you can get the height by a little calculation using locationOnScreen of the BottomSheetDialogFragment.

view.getLocationOnScreen(int[] outLocation): Computes the coordinates of this view on
the screen. The argument must be an array of two integers. After the
method returns, the array contains the x and y location in that order.

bottomSheetBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
                    override fun onStateChanged(bottomSheet: View, newState: Int) {
                        if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
                         //your code here
                        } else if (newState == BottomSheetBehavior.STATE_EXPANDED) {
                         //your code here
                        }
                    }

                    override fun onSlide(bottomSheet: View, slideOffset: Float) {

                           var locationOnScreen: IntArray = intArrayOf(0, 0)
                           bottomSheet.getLocationOnScreen(locationOnScreen)

                           // coordinates of bottomsheet when sliding up/down
                           val (x, y) = locationOnScreen

                    }
                })


text:
Q: Replacement for context.showDocument() in JavaWebStart application I'm migrating an old legacy application from in browser applet to a JFrame based JWS application started via JNLP.
In the applet base application I used the context.showDocument() to open Browser windows of any size and configured to not show bars (menu bar, status-bar, scroll bar) and not resizable (viawith Javascript ()).
But now this is not working.
Is there a workaround for that that I can do in a JavaWebStart/JNLP application?
I would need to open a HTML page and display the contend in a sized window without the usual bars.
When I use the showDocument() form JNLP basicServices now I can not do this (no JavaScript).

A: It should normally be possible to preview the html file inside a javafx webview, as it is with a normal java application. I am not sure about the jnlp  permissions required for this operation though:
private void previewHtml(String url) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            JFrame fr = new JFrame();
            final JFXPanel fxPanel = new JFXPanel();
            fr.add(fxPanel);
            fr.setSize(1000, 600);
            fr.setVisible(true);

            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    final Group  rootGroup  =  new  Group();
                    final Scene scene = new Scene(rootGroup, 1000, 600, Color.WHITE);
                    final WebView webView = WebViewBuilder.create().prefHeight(600).prefWidth(1000).build();
                    webView.getEngine().load(url);
                    rootGroup.getChildren().add(webView);
                    fxPanel.setScene(scene);
                    fxPanel.show();
                }
            });
        }
    });

}

//You can add the following code to a button actionListener:

//prevew html from classpath:
previewHtml(getClass().getResource("/classpath-file.html").toExternalForm());

//prevew html from url:
previewHtml("https://stackoverflow.com/");


text:
Q: Exibir miniaturas de arquivos Alguém conhece algum plugin que permita a pré-visualização de arquivos TXT, PDF, DOC, e XLS para exibir numa página Web?
Na imagem exemplo, está sendo exibido um PDF e uma imagem

A: Cara, existe o Bootstrap File Input:
HTML 5 para Bootstrap 3.x com pré visualização para vários arquivos, oferece a seleção múltipla, e muito mais. O plugin permite-lhe uma maneira simples de configurar um controle selecionador de arquivo/upload avançado construído para trabalhar especialmente com estilos Bootstrap CSS3. Ele melhora a funcionalidade de entrada de arquivo ainda mais, oferecendo suporte para pré-visualizar uma grande variedade de arquivos, ou seja, imagens, texto, html, vídeo, áudio, flash e objetos. Além disso, ele inclui uploads baseados AJAX, drag-drop de arquivos, vendo o progresso do upload, e seletivamente a visualização, adicionar ou excluir arquivos. :
http://plugins.krajee.com/file-input
Outra opção seria utilizar essa robusta API:
http://filepreviews.io/
Começando
O serviço FilePreviews.io é composto de uma API muito simples organizado voltada para REST.
Pode ser usado para solicitar uma pré-visualização, que acontece de forma assíncrona. Os resultados retornados são úteis para diferentes cenários, permitindo que você visualize os metadados solicitados e verificar se estão disponíveis, ou utilize webhooks.
JSON será devolvido em todas as respostas a partir da API, incluindo erros.
Exemplo basico:
Código:
import FilePreviews from 'filepreviews'

const fp = new FilePreviews({
  debug: true,
  apiKey: 'XXXX-YOUR-SERVER-KEY-HERE-XXXX',
  apiSecret: 'XXXX-YOUR-SERVER-SECRET-KEY-HERE-XXXX'
})

const options = {
  pages: "all",
  format: "png"
}

fp.generate('https://www.filepicker.io/api/file/asTSNPAiR4qnknj7UgAP', options (err, result) => {
  if (err) throw new Error(err)
  console.log(result)
})

Resultado:
{
  "id": "46d6fbcf-83be-47ee-9eb1-2579f1d1a306",
  "url": "https://api.filepreviews.io/v2/previews/46d6fbcf-83be-47ee-9eb1-2579f1d1a306/",
  "status": "success",
  "preview": {
    "url": "https://s3.amazonaws.com/demo.filepreviews.io/dcc8ad4e46ffecf17474466cba8fa9de9c7beda2fb0518d8fe5440b4ee38db81/46d6fbcf-83be-47ee-9eb1-2579f1d1a306_original_1.png",
    "size": {
      "height": "842",
      "width": "595"
    },
    "page": 1,
    "original_size": {
      "height": "842",
      "width": "595"
    },
    "requested_size": "original",
    "resized": false
  },
  "thumbnails": [
    {
      "url": "https://s3.amazonaws.com/demo.filepreviews.io/dcc8ad4e46ffecf17474466cba8fa9de9c7beda2fb0518d8fe5440b4ee38db81/46d6fbcf-83be-47ee-9eb1-2579f1d1a306_original_1.png",
      "size": {
        "height": "842",
        "width": "595"
      },
      "page": 1,
      "original_size": {
        "height": "842",
        "width": "595"
      },
      "requested_size": "original",
      "resized": false
    }
  ],
  "original_file": {
    "metadata": {
    },
    "encoding": "binary",
    "name": "JSday Recife",
    "extension": "pdf",
    "total_pages": 1,
    "size": 39736,
    "type": "application",
    "mimetype": "application/pdf"
  },
  "user_data": null
}


text:
Q: Objective-C : access properties outside of main UI Thread When programming GUI on iOS, properties often declares as nonatomic because we often just access those properties on main UI thread (as on Android).
@interface TKDViewController : UIViewController
    @property (nonatomic, strong) NSMutableArray *tableData;
@end

So, my question is: if I change the properties to atomic, so I can access outside of main UI thread, right? If I do so, will I meet some problems?
@interface TKDViewController : UIViewController
    @property (atomic, strong) NSMutableArray *tableData;
@end

thanks :)

A: Atomic and nonatomic mutators on properties affect read/write behavior. With atomic properties each read/write is synchronized (so only one operation at a time is allowed).
You can access nonatomic properties from background thread and in most cases it won't break anything. You have to be careful with changing properties of UI objects. These changes have to be done on main thread to take effect.

A: Using atomic with IBOutlet will give you a thread safe setters, and using nonatomic will give you unsafe setters.
So, my question is: if I change the properties to atomic, so I can access outside of main UI thread, right? If I do so, will I meet some problems?
Yes, you will get some problems, unless you call [view setNeedsDisplay] on the main thread (after doing some changes on the background) to update the UI (or avoid accessing it on a background thread). Atomic is just a mutex lock.


text:
Q: AngularJS: Compiling the output of a directive i have some kind of legacy angularjs code which creates a dynamic table using a directive where the controller can overwrite the behavior of the table (on how to display the data)
It consists of the following setup (simplified):
Directive's controller
.directive('datatable', [function () {
    return {
        scope: {
            items: '=',
            tablemetadata: '=',
            processors: '=?'
        },
        controller: ...
        $scope.processField = function processField(item, data){
        if($scope.processors === undefined){return;}
            for(var i = 0; i < $scope.processors.length; i++){
                if($scope.processors[i].field===field){
                    var newData = $scope.processors[i].processor(item, data);
                    return $sce.trustAsHtml(newData);
                }
            }
            return data;
        };
    ...

Directive's Template

Controller
$scope.myItems = [{id: 2, otherProperty: "text"}];

$scope.tableMetadata = {
    columns: [
        {field: 'id', headerKey: 'object id'},
        {field: 'otherProperty', headerKey: 'some data'},
    ]
};

$scope.tableProcessors = [
    {field: 'id', processor: function(entry, data){ //data = content of object.id
        var retVal = "click me";
        return retVal;
    }}
];

Controller's view
<datatable items="myItems" tablemetadata="tableMetadata" processors="tableProcessors"></datatable>

I need to generate buttons (or other html-elements) for some specific properties, like a link (like shown above).
The Button is displayed but the ng-click handler is not working. This makes sense since it wasn't compiled to the scope.
How do I correctly compile the new element and add it to the table?

A: A simple solution can be to not use an isolated scope.
Change your scope from scope: { ... } to scope: true and use $scope.$eval to evaluate your attributes.
Another solution (most elegant) can be to use angularjs transclusion (see here). But this solution ask to modify your dom representation of your directive.

A: In your link method in the directive you have to use
elem.append( $compile(html)(scope) );

As for separating the concerns cleanly, I would make each  its own directive that inherits what you are currently concatenating as a string in its isolated scope properties. Instead of
var retVal = "click me";

use something like:

/** directive compiles dynamically */

scope: {
  processField: '='
},
link: function(scope, elem, attr, ctrl) {
  var template = `<a ng-click="${ctrl.processField}"></a>`;
  elem.append( $compile(template)(scope) );
}


text:
Q: Process object running Python script doesn't redirect output successfully I'm working on running a simple python script through my c# program via the Process class. Here is the code I'm using to actually run the script:
    public PythonScript (string filePathDir, string args, Action<string> write)
    {
        this.filePathDir = filePathDir;
        this.args = args;
        this.write = write;

        script_thread = new Thread (Run);
        script_thread.Start ();
    }

    private void Run()
    {
        process = new ProcessStartInfo ();
        process.Arguments = args;
        process.FileName = filePathDir;
        process.UseShellExecute = false;
        process.RedirectStandardOutput = true;

        p = Process.Start (process); // p is declared as "Process p;"
        while (true) {
            write ("running");
            string foo = p.StandardOutput.ReadLine ();
            write ("running1");
            write (foo);
        }
    }

The way I'm actually creating my PythonScript object is:
PythonScript py = new PythonScript("python3", "HeartAPI.py", Write)
where Write is my output method (for printing the info). The formatting for this comes from here. (note: i'm calling python3 instead of python.exe or something else because I'm running on a KUbuntu environment)
The problem that I'm running into is that when I run my script (it's a basic api), the api is accessible and usable, yet every time my python script has a print() call, nothing is outputted through my Write function. However, I know that it's not the way I'm passing the method, as the call write("running"); DOES work, and it is displayed.
Does anyone have any idea why my python output stream is NOT going through to my write method? I havent been able to find any other examples online with this issue, so any help would be appreciated!
EDIT: To clarify. My python script DOES run, and completes its operations successfully. However, the output of said script does NOT get redirected appropriately as far as I can tell. The Write(string) method being passed into the PythonScript object does work correctly, as the command write("running"); executes perfectly and displays as it should. Why isn't the Python script's output being redirected into my write() method?
EDIT 2: In response to an answer I tried, I added a script_thread.Join() call under the rest of the code in my PythonScript constructor. Here's the updated code:
    public PythonScript (string filePathDir, string args, Action<string> write)
    {
        this.filePathDir = filePathDir;
        this.args = args;
        this.write = write;

        script_thread = new Thread (Run);
        script_thread.Start ();
        script_thread.Join ();
        Console.WriteLine ("JOINED");
    }

I also added a call to output to the console do indicate when the thread is joined, which never gets output. When trying this code, my GUI window never appears. However I have a logging system in place which WAS written to, and this was the output that should have gone to my GUI console:
 running
11:11:44-  Closing down Heart...
11:11:44-  Goodbye.
11:11:44-  running1
11:11:44-
11:11:44-  running
11:11:44-  running1
11:11:44-
11:11:44-  running
11:11:44-  running1
11:11:44-
11:11:44-  running
11:11:44-  running1
11:11:44-
11:11:44-  running
11:11:44-  running1
11:11:44-
11:11:44-  running
11:11:44-  running1
11:11:44-
11:11:44-  running
11:11:44-  running1

Closing Down Heart... is called when the gui is told to close. So I'm not really sure what's going on here, but that's what the output was with the addition of a Join() call.

A: Can you please put sys.stdout.flush() after you print something in your python script or alternatively print some extra new lines. The reason you are not getting any output might be because of stdout buffer of python3.

A: I don't see a script_thread.Join() call. I suspect the C# process is finishing before the python process prints its first line.
Try this:
public PythonScript (string filePathDir, string args, Action<string> write)
{
    this.filePathDir = filePathDir;
    this.args = args;
    this.write = write;

    script_thread = new Thread (Run);
    script_thread.Start ();
    script_thread.Join ();  // Wait for the thread to terminate.
}


text:
Q: How to check if scanf() worked fine in C? I am trying to see if user enters 3 correct input. If not the loop ask for input again and again until they correct it correctly.
#include <stdio.h>
int main(void) {

        int num1,num2;
        char str;
        int check;

        printf("Enter : ");
        check = scanf("%d,%d, %c", &num1, &num2, &str);

        while (check != 3) {

                 printf("Enter : ");
                 check = scanf("%d,%d, %c", &num1, &num2, &str);
        }

}

Let's say if I entera, 5.4, c we get an infinite loop. Why is it giving an infinite loop?

A: There are far more ways to incorrectly use scanf in a loop that proper ones. The primary issue (aside from input or matching failures that are explained in the man page), is failing to empty the input buffer (stdin when reading from a terminal) after a failed conversion. (There is also the issue that the user must enter something.) When a user enters text and presses [Enter] a newline ('\n') is generated and placed in the input buffer to mark the end of line. When you enter a, 5.4, c, 'a' is fine, but 5.4 is not an int and the processing fails:

If processing of a directive fails, no further input is read, and
  scanf() returns.

When scanf returns, it leaves the remaining characters in stdin and you loop and attempt to read again. scanf attempts to read what is left in stdin, processing again fails, and the loop continues endlessly.
In this situation the only way to prevent the indefinite loop is to manually empty the input buffer after you call to scanf. Something simple will do:
int c;
...
while (...) {
    scanf (...)
    while ((c = getchar()) != '\n' && c != EOF) {}
}

This will insure you start with an empty buffer on the next iteration. For example:
#include <stdio.h>

int main (void) {

    int num1 ,num2, c;
    char str;

    while (printf ("\nEnter : ") &&
           scanf (" %d, %d, %c%*c", &num1, &num2, &str) != 3) {
        printf ("error: invalid input, required: 'int, int, char'\n");

        /* empty remaining chars from input buffer */
        while ((c = getchar()) != '\n' && c != EOF) {}
    }

    printf ("\n num1 : %d\n num2 : %d\n str  : %c\n\n", num1, num2, str);

    return 0;
}

Example Use
$./bin/scanf3

Enter : a
error: invalid input, required: 'int, int, char'

Enter : a, 5.4, c
error: invalid input, required: 'int, int, char'

Enter : 10, 25
error: invalid input, required: 'int, int, char'

Enter : 10, 25, a

 num1 : 10
 num2 : 25
 str  : a

note: this does not protect against the user entering nothing (just pressing [Enter]) and the cursor just sitting there blinking as it waits for input. That is an inherent behavior of scanf, part of which is the reason that line-oriented input methods (fgets or getline) are preferable when taking input.

A: First time  scanf() reads the character then it reads the newline (enter/whitespace character ).This  character is present in the input buffer and is read by the scanf() function.
So clear the buffer before reading the new user input using fflush(stdin).
EDIT : Tested in windows VS2013.Sorry i dont have Linux. Windows and Linux define the behaviour of fflush() in different way.If you are using in Windows platform :
int main(void) {

    int num1, num2;
    char str;
    int check;

    printf("Enter : ");
    check = scanf("%d,%d, %c", &num1, &num2, &str);

    while (check != 3) {

////Flush the input buffer ////

        fflush(stdin);
        printf("Enter : ");
        check = scanf("%d,%d, %c", &num1, &num2, &str);
    }

}
EDIT : this will work in all platforms.
Another simple way is to consume the remaining read line by
while ((c = getchar()) != '\n' && c != EOF);

so now
int main(void) {

    int num1, num2;
    char str,c;
    int check;

    printf("Enter : ");
    check = scanf("%d,%d, %c", &num1, &num2, &str);

    while (check != 3) {

        ////read the remaining char ////
        while ((c = getchar()) != '\n' && c != EOF);

        printf("Enter : ");
        check = scanf("%d,%d, %c", &num1, &num2, &str);
    }
}


text:
Q: Adding correlation coefficients of time series I have computed correlation coefficients for 90 day increments of a time series (i.e., one coefficient for days 0-90, 91-180, etc.). It was computationally very expensive to compute these and I would like to analyze correlations over 6 month periods, 1 year periods etc. Is it possible to some how to combine these coefficients? I.e., can I get the correlation over 180 days as 0.5*c1+0.5*c2?
I know in the general case this cannot be done, but because the coefficients are computed from the same number of samples, is it possible?

A: The sample correlation coefficient is
$$\sum (x_i-\bar{x})(y_i-\bar{y}) / \sqrt{\sum (x_i-\bar{x})^2 \sum(y_i-\bar{y})^2}$$
so the best thing would be to save $\sum(x-\bar{x})(y-\bar{y})$, $\sum(x-\bar{x})^2$ and $\sum(y-\bar{y})^2$ for the different windows.  These could easily be combined, even with different sample sizes in the different windows.
If the denominators are approximately constant across 90 day increments, then you could just take the average of the correlations.
I'm surprised you say that this is computationally expensive.  I wouldn't think it would take much more time than calculating the sample mean.

A: To echo Karl, it's probably symptomatic of a larger problem if that was computationally expensive in any way. You can't get much better than linear time with stuff like this, and that should have been linear time. Perhaps the most productive thing would be to analyze you algorithms and make sure there's nothing obviously wrong there. We'd all be happy to help if you can post a snippet.


text:
Q: How to center pseudo element ::after border in a div? i want to ask you. I'm trying to create a border using pseudo element (after). I want to place a border in the middle of the div box that I have created, without setting (top, bottom) and (left, right). Can it be automated in the middle?
My Codepen

.box{
  height:500px;
  width:300px;
  background-color:red;
  position:relative;

  &::after{
    content:'';
    position:absolute;
    border:2px solid #fff;
    height:90%;
    width:90%;
  }
}

A: Yes it can:

.box {
  width: 500px;
  height: 500px;
  position: relative;
  background-color: blue;
  padding: 10px;
}

.box:after {
  content: '';
  position: absolute;
  display: block;
  width: 95%;
  height: 95%;
  border: 1px solid #FFF;
}

Allthough I don't completely understand why you wouldn't want to use top, right, bottom, left values. With transform, you can't automate it ALWAYS. You'll have to set it to half the height of the box. With a top value, you could just set it to 50%.

A: I've used percentages for the top and left and than correect the positioning with transform: translate(-50%, -50%); so its in the middle

.box{
  height:500px;
  width:300px;
  background-color:red;
  position:relative;

}

.box::after{
    content:'';
    position:absolute;
    border:2px solid #fff;
    height:90%;
    width:90%;
    left: 50%;
    transform: translate(-50%, -50%);
    top: 50%;
  }

A: There are couple of ways....!!
.box{
  height:500px;
  width:300px;
  background-color:red;
  position:relative;

  &::after{
    content:'';
    position:absolute;
    border:2px solid blue;
    height:90%;
    width:90%;
    right: 50%;
    bottom: 50%;
    transform: translate(50%,50%);
  }
}

Another way...without using positions.
.box{
  height:500px;
  width:300px;
  background-color:red;
  display: flex;

  &::after{
    content:'';
    border:2px solid blue;
    height:90%;
    width:90%;
    margin: auto;
  }
}

A:

.box{
  height:500px;
  width:300px;
  background-color:red;
  position:relative;

  }

.box:after {
    content: '';
    position: absolute;
    border: 2px solid #fff;
    top: 3%;
    left: 4%;
    height: 93%;
    width: 90%;
}

A: You can use flexbox on the .box element to center its contents. Just make sure no other position property is set on the ::after pseudo-element:
.box {
  height: 500px;
  width: 300px;
  background-color: red;
  position: relative;

  display: flex;
  align-items: center;
  justify-content: center;
}

.box::after {
  content: '';
  position: absolute;
  border: 2px solid #fff;
  height: 90%;
  width: 90%;
}


text:
Q: Column 'client_id' cannot be null I am trying to run:
php artisan passport:install

And it is returning me this error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'client_id' cannot be null (SQL: insert into
oauth_personal_access_clients (client_id, updated_at,
created_at) values (, 2022-11-0     8 07:58:48, 2022-11-08
07:58:48))

I am on laravel 5.5 with php 7.1. What am I doing wrong here? Passport version is 2.0.4.

A: Please follow the below bullet points according to the documentation instructions for laravel 5:

*

*To get started, install Passport via the Composer package manager:
composer require laravel/passport=~4.0

*The Passport service provider registers its own database migration directory with the framework, so you should migrate your database after registering the provider. The Passport migrations will create the tables your application needs to store clients and access tokens:
php artisan migrate

*Next, you should run the passport:install command. This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create "personal access" and "password grant" clients which will be used to generate access tokens:
php artisan passport:install


text:
Q: Spring MVC Validation not working (Annotation) I'm trying to use annotation validation, but it's not working.
Here's my Service Interface where I'm applying the validation:
package com.tehras.web.service;

import com.tehras.web.annotations.ValidCategory;
import com.tehras.web.models.MenuCategory;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by Taras on 6/17/2014.
 */
@Validated
@Service
public interface IMenuCategoriesService {

    /*
     @Return List<MenuCategory>
     */
    public List<MenuCategory> getMenuCategories();
    /*
    @Return boolean
     */
    public boolean addMenuCategory(@ValidCategory MenuCategory menuCategory);
    /*
    @Return boolean
     */
    public boolean removeMenuCategories(List<MenuCategory> menuCategoryList);

    public boolean containsCategoryName(String categoryName);
}

And here's my Validation class
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {ValidCategoryImpl.class, ValidCategoryNameImpl.class})
public @interface ValidCategory {
        String message() default "This Category Does not Seem to Allowed";

        Class<?>[] groups() default { };

        Class<? extends Payload>[] payload() default { };
}

And finally my Impl class:
@Component
public class ValidCategoryImpl implements ConstraintValidator<ValidCategory, MenuCategory> {

    @Autowired
    IMenuCategoriesService menuCategoriesService;

    @Override
    public void initialize(ValidCategory constraintAnnotation){
    }

    @Override
    public boolean isValid(MenuCategory menuCategory, ConstraintValidatorContext context){
        return menuCategoriesService.containsCategoryName(menuCategory.getTitle());
    }
}

Please help! I've been stuck for this and can't fix it!
When i pass in the menuCategory it doesn't even go into the validation method? please help!
..Can't add a commment, but to answer the why question, this is what i think:
Similar to how @NotNull or @Size is invoked, I created my custom class, where my implementation is this - ConstraintValidator, so when MenuCategory is there it should go into this implementation method since I have @ValidCategory set-up to do so. What's your opinion? How do I make sure that validation happens?


text:
Q: C# Type A cannot be casted to Type B ( InvalidCastException)... Context hell? I'm having a very unpleasant issue with my webapp.
The app is designed as follow :

*

*The root App is loading a Flex SWF, which in turn loads a 3rd party Flex SWF module in a sub app (MagickECB).

*Both Apps reference Albums.dll, dll found in /bin and /MagickECB/bin and both Apps share the same Application Pool in IIS.

EDIT : That's two projects, the root app project and the subapp project. Subapp project reference root app project.
When loading the sub app's flex module from the root app's flex application, we randomly get a cast error as follow :

There was an error getting
configuration of Photobook:
[A]Albums.LocalizationConfiguration
cannot be cast to
[B]Albums.LocalizationConfiguration.
Type A originates from 'Albums,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null' in the context
'Default' at location
'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary
ASP.NET
Files\magickecb\4414db97\126f5aaf\assembly\dl3\cf281292\4a6ecec8_8a7bcb01\Albums.DLL'.
Type B originates from 'Albums,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null' in the context
'LoadFrom' at location
'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary
ASP.NET
Files\magickecb\4414db97\126f5aaf\assembly\dl3\017fab88\a91238d1_7977cb01\Albums.dll'.
at
Albums.LocalizationConfiguration.GetConfig()
at Albums.CGlobal.GetUserLocale(String
userHandle)

Trying to investigate this issue, I found out the GetConfig method causing the cast error returned
return (LocalizationConfiguration)ConfigurationManager.GetSection("Localization/Localization");

The section in the Web.config is declared as follow : (EDIT : root app's web.config)
<sectionGroup name="Localization">
    <section name="Localization" type="Albums.LocalizationConfigurationHandler, Albums"/>
</sectionGroup>

My guess would be that the internal code of GetSection tries to load Albums.dll in the "LoadFrom" context and therefore cause a conflict with the original Albums.dll loaded in the /bin path (see context problematics)
I also note that other dlls in /MagickECB/Bin also reference Albums.dll, so I rebuild all projects so that every DLL reference the same version of Albums.dll
Last, if you check the dll full path in Temporary files, the extensions are different (uppercase vs lowercase)..
Any input on how to solve this problem would be greatly appreciated !!

A: Double-check your references, if you compare your two dll locations they are different (extension upper case vs lower case is not an issue):
Temporary ASP.NET Files\magickecb\4414db97\126f5aaf\assembly\dl3\ cf281292\4a6ecec8_8a7bcb01 \Albums.DLL
Temporary ASP.NET Files\magickecb\4414db97\126f5aaf\assembly\dl3\ 017fab88\a91238d1_7977cb01 \Albums.dll
Probably means you're referencing two different files - maybe referencing one as a project and the other directly as a file. Do you have any warnings when you try building your web application regarding references?
EDIT: __AssemblyInfo__.ini file in above folders will give you path from which Albums.dll had been copied.

A: Without having a explanation for your issue I would suggest to register the assembly at the GAC and use it from there.


text:
Q: Nuxt.js fails to start up with auth module npx create-nuxt-app client and set it up. Run npm run dev and everything works.
I start auth setup with npm install @nuxtjs/auth
add '@nuxtjs/auth' module in nuxt.config.js
add example auth strategy like so
  auth: {
    strategies: {
      local: {
        endpoints: {
          login: { url: '/api/login', method: 'post' },
        },
        tokenRequired: false,
        tokenType: false
      }
    }
  },

Add the example vue store and save it in store/index.js:
export const state = () => ({
  counter: 0
})

export const mutations = {
  increment(state) {
    state.counter++
  }
}

I run npm run dev, everything compiles and init message shows to go to http://localhost:3000/. Trying to load it in the browser, the URL continues to load after initial loading and does not end. Node process starts to use 100% of the CPU and after several minutes prints this and quits:
<--- Last few GCs --->

[34438:0x38ef0c0]   323677 ms: Scavenge 2003.9 (2048.6) -> 2003.2 (2049.1) MB, 10.9 / 0.0 ms  (average mu = 0.209, current mu = 0.192) allocation failure
[34438:0x38ef0c0]   323728 ms: Scavenge 2004.6 (2049.6) -> 2004.0 (2049.9) MB, 12.4 / 0.0 ms  (average mu = 0.209, current mu = 0.192) allocation failure
[34438:0x38ef0c0]   323778 ms: Scavenge 2005.4 (2050.4) -> 2004.8 (2050.6) MB, 10.9 / 0.0 ms  (average mu = 0.209, current mu = 0.192) allocation failure

<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 0x13cf019]
Security context: 0x29f654d808d1 <JSObject>
    1: inspect(aka inspect) [0x32d8b34ca9f9] [internal/util/inspect.js:~240] [pc=0xee1e7f4f44c](this=0x1cbf81fc04b1 <undefined>,0x29f654d98bc1 <JSFunction Boolean (sfi = 0x3f35983d3769)>,0x02b5724d8a71 <Object map = 0x1bc8fcdd6919>)
    2: /* anonymous */ [0x9a2eaaec139] [/home/myUserName/Documents/projectFile/client/node_modules/esm/esm.js:~1] [pc=0xee1e7e6e063](...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 0xa093f0 node::Abort() [node]
 2: 0xa097fc node::OnFatalError(char const*, char const*) [node]
 3: 0xb842ae v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [node]
 4: 0xb84629 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [node]
 5: 0xd30fe5  [node]
 6: 0xd31676 v8::internal::Heap::RecomputeLimits(v8::internal::GarbageCollector) [node]
 7: 0xd3def5 v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [node]
 8: 0xd3eda5 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node]
 9: 0xd4185c v8::internal::Heap::AllocateRawWithRetryOrFail(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [node]
10: 0xd0830b v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationType, v8::internal::AllocationOrigin) [node]
11: 0x1049f4e v8::internal::Runtime_AllocateInYoungGeneration(int, unsigned long*, v8::internal::Isolate*) [node]
12: 0x13cf019  [node]
Aborted

I tried this start to finish with node v10.15.3 and v12.18.3, the same result. Versions from package.json:
  "dependencies": {
    "@nuxtjs/auth": "^4.9.1",
    "@nuxtjs/axios": "^5.12.0",
    "bootstrap": "^4.5.0",
    "bootstrap-vue": "^2.15.0",
    "nuxt": "^2.14.0"
  }

and npx create-nuxt-app --version shows create-nuxt-app/3.2.0 linux-x64 node-v12.18.3. OS is Solus 4.1 Fortitude.
What is going wrong here? If this is a known bug, are there versions/workaround that works?

A: Setting baseURL property under for axios in nuxt.config.js solved my issue:
  axios: {
    baseURL: '/'
  }


text:
Q: Object Cycle Json in SendAsync from HTTPClient at .NET 3.1 I have a service where I'm trying to make a request for a API from RapidAPI. The request works fine at Insomnia, but when in the application it keeps giving me object cycle error. The most strange thing is that the error ocurrs at the request, not when I'm converting the result content from JSON to an Object. Do anyone already see this error in a situation like this?
Error
    System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.
   at System.Text.Json.ThrowHelper.ThrowJsonException_SerializerCycleDetected(Int32 maxDepth)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCoreAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteCore[TValue](JsonConverter jsonConverter, Utf8JsonWriter writer, TValue& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteAsyncCore[TValue](Stream utf8Json, TValue value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,pt;q=0.8
Connection: close
Host: localhost:44345
Referer: https://localhost:44345/swagger/index.html
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36
sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
sec-fetch-site: same-origin
sec-fetch-mode: cors
sec-fetch-dest: empty

Service
using BoxTI.Challenge.CovidTracking.Models.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace BoxTI.Challenge.CovidTracking.Services.Services
{
    public class ExternalCovidService : IExternalCovidService
    {
        private readonly IHttpClientFactory _clientFactory;
        private readonly string covidAPI;

        public ExternalCovidService(IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
            covidAPI = "https://covid-19-tracking.p.rapidapi.com/v1/";
        }

        public async Task<CountryRegistry> getCountryCovidRegistry(string name)
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri(covidAPI + name),
                Headers =
                {
                    {"x-rapidapi-host", "covid-19-tracking.p.rapidapi.com"},
                    {"x-rapidapi-key", "bf20ff3edemsh98ec952149547adp19d3a9jsneace2484e7af"}
                },
            };

            using (var response = await client.SendAsync(request))
            {
                response.EnsureSuccessStatusCode();
                var content = await response.Content.ReadAsStringAsync();
                var registry = JObject.Parse(content);
                var cr = new CountryRegistry
                {
                    Name = registry["Country_text"].ToString(),
                    ActiveCases = registry["Active Cases_text"].ToString(),
                    LastUpdate = DateTime.Parse(registry["Last Update"].ToString()),
                    NewCases = registry["New Cases_text"].ToString(),
                    NewDeaths = registry["New Deaths_text"].ToString(),
                    TotalCases = registry["Total Cases_text"].ToString(),
                    TotalRecovered = registry["Total Recovered_text"].ToString(),
                    TotalDeaths = registry["Total Deaths_text"].ToString(),
                };
                return cr;
            }
        }
    }
}

OBS: I already tried to configure the System.Text.Json at the Startup of the project, like:
services.AddControllers().AddNewtonsoftJson(options =>
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);

Or this
 services.AddMvc()
  .AddJsonOptions(o => {
     o.JsonSerializerOptions
       .ReferenceHandling = ReferenceHandling.Preserve
            });

A: Your Swagger UI is using System.Text.Json instead of Newtonsoft.Json, so it's not picking up on the serializer settings.
In order to add Newtonsoft support to your swagger UI Add the NuGet package:
Swashbuckle.AspNetCore.Newtonsoft

Then, in your startup add the following line after AddSwaggerGen
services.AddSwaggerGenNewtonsoftSupport();

More info here


text:
Q: Capture all scroll events Is there a way to capture all the scrolling events on any elements in the DOM? In a similar way to MutationObserver which tells you about general DOM changes, is there a way to hear about general scroll events (in a roughly cross-browser compliant way)?
Obviously, ideally I don't want to try and attach listeners for scrolling to every element in the DOM manually (both because of the hassle of doing so and the fear that my browser would explode).
Alternatively, I'd be good with a way to detect all DOM elements that currently have visible scrollbars (such that I could then isolate those elements and attach scroll listeners only to them) but I imagine this to be no less complicated.

A: You can use
$("*").on("scroll",function(event){
 // Your code to handle

});

Hope it helps you.


text:
Q: media queries, images, and load times I've got 3 different images that I want to display for 3 different display ports. My question is this. If someone on a cellphone loads up my website, will their device have to download all 3 images at load? Will the device prioritize the image that pertains to their viewport and download that one first?
Essentially, I don't want a user's load time of the page (time to full paint) to be impacted by specifying different bgimages for different viewports.
.bgpattern {
  background-image: url(../images/bg1.jpg);
}

@media (max-width: 1200px) {
  .bgpattern {
     background-image: url(../images/bg2.jpg);
  }
}

@media (max-width: 767px) {
  .bgpattern {
     background-image: url(../images/bg3.jpg);
  }
}

A: It is browser dependent. Chrome and Safari wil only download the applicable background image.
You can test that behaviour  with the Chrome developer tools:

*

*Open the Chrome developer tools (F12)

*In Elements, click Toggle Device Toolbar

*Set your viewport

*Open the Network tab

*Reload your page.

*Check which images were loaded which images were not

This is better explained in this blog post:
https://web.dev/optimize-css-background-images-with-media-queries/


text:
Q: how to combine curve() function with do.call() function? I'm trying to create a graph with curve() with do.call to apply a function to each element in a list but the x argument is not being recognized.
tt <- function(x) {
  list1 <- list(
    option1 <- c(init=600000 + 600000, depr=000000, il=180, per=180,
                 quant=list(c(45)), pre=list(c(330000)), cust=0,
                 cust_un=list(c(0)), sala=1200, num=0, wacc=0.0082,
                 redr=1, tem=69, capa=2000, cap2=60000, cap3=100000,
                 cap4=1000000, custo2=1200, custo3=1600, custo4=5000,
                 chan=0.30, tempo_nal=0, redu_lucr=00, redu_qt=0,
                 aumen_cf=0.3, redu_lucrofinal=0.2, redu_qtdfinal=0.1,
                 aumen_cffi=0.80, final=0000, iniceco=210000,
                 finreco=250000, iniv=40000, fiv=65000, ininda=000,
                 percionario=1, n=80, PV=1300000, i=0.008, temrmal=1,
                 temeio=0, car=x)
  )
  sapply(list1, function(x){do.call(mean, as.list(x))})
}

curve(tt, from=3, to=120)

the x in car argument is not being recognized:
# Error ... unused arguments (car1 = 3, car2 = 4.17, car3 = 5.34, car4 = 6.51,
#  car5 = 7.68, car6 = 8.85, car7 = 10.02, car8 = 11.19, car9 = 12.36,
#  car10 = 13.53, car11 = 14.7, car12 = 15.87,car13 = 17.04, car14 = 18.21,
#  car15 = 19.38, car16 = 20.55, car17 = 21.72, car18 = 22.89, car19 = 24.06,
#  car20 = 25.23, car21 = 26.4, car22 = 27.57, car23 = 28.74, car24 = 29.91,
#  car25 = 31.08, car26 = 32.25, car27 = 33.42, car28 = 34.59, car29 = 35.76,
#  car30 = 36.93, car31 = 38.1, car32 = 39.27, car33 = 40.44, car34 = 41.61,
#  car35 = 42.78, car36 = 43.95, car37 = 45.12, car38 = 46.29, car39 = 47.46,
#  car40 = 48.63, car41 = 49.8, car42 = 50.97, car43 = 52.14, car44 = 53.31,
#  car45 = 54.48, car46 = 55.65, car47 = 56.82, car48 = 57.99, car49 = 59.16,
#  car50 = 6


text:
Q: Code not able to run correctly for even 300 char Inputs This is a code for finding the frequency of digits in an string input.which is char array as in case of c.But it is falling when i tried large inputs.
I know there might be something wrong while the conversion of char into int but i cant understand that at what exactly.I know the different approach which exactly solve this problem but i just wanna know what is wrong with this code as it seems to be fine ig.
int main() {

    char a[1001];
    scanf("%s",a);
    int arr[10];
    for(int i=48;i<=57;i++){
       arr[i]=0;
    }
    int count=0,j=0;
    while(j<strlen(a)){
      //printf("%c",a[j]);
      if(a[j]>='0' && a[j]<='9'){
        arr[a[j]]++;
      }
      j++;
    }
    //printf("\n");
    for(int i=48;i<=57;i++){
       printf("%d ",arr[i]);
    }
    //printf("\n%d",count);
    return 0;
}

A sample input for eg:-->
  1p69436y8983382u3k820p304507ct815505m68m2ot810224tmoh09f2915dxt972mp3fs58mng9w04c211i17z9z3v975awx9281g9973m33z54t4095408wy1851x3756031586732hxg2te09k11l166789qj9366m7uu550en6910i209f6g081d4247uz6f913270g8l9859lrf325660x5d64016d4784j5688gf4560977279r08242191ste332341q7010ra20f505105mhqg35re342er61200083c9cp9u625e2kvq919go1770097ap485428j1046582g0p71v6j34u5146069x750454v6013f19ye864gr5yi00475304o914a608624664170j6d1d0601er4015285j205268k873hw260209n5g093y3jpdr75574tti0h9161792y70816614sl1tarmj9iz3t1280h91u91k1c984r511644t19j1qvnuuku74g68ont9g7775u3gx74169uf477925236z049386uk12h1w011267x2kdyp49czz532263c7d396nw9917ee166e53803co80752008j1q12

EXPECTED OUTPUT:-->56 58 43 37 40 43 47 39 37 48

my code output:-->10 11 10 13 7 12 5 7 12 12

A: You need to separate the array holding the result from the ASCII values of the digits - they are not related. Since for(int i=48;i<=57;i++) writes out of bounds of the array, just forget about using ASCII values. You can zero-initialize the array as intended with a simple int arr[10] = {0};.
Similarly, you can convert from a digit in ASCII format to an integer value by doing a[i] - '0'.
Meaning that your loops can be simplified and reduced to this:
int arr[10] = {0};
int length = strlen(a);
for(int i=0; i<length; i++)
{
  if(a[i]>='0' && a[i]<='9')
  {
    int val = a[i] - '0';
    arr[val]++;
  }
}

The check a[i]>='0' && a[i]<='9' can in turn be replaced with isdigit(a[i]), from ctype.h.

A:
int arr[10];
for(int i=48;i<=57;i++){
   arr[i]=0;
}

Oops ... arr[48] does not exist. The indexes of arr go from 0 (including 0) to 9 (excluding 10)
Try
 int arr[10];
 for(int i=48;i<=57;i++){
    arr[i-48]=0;
 }

and remember to adjust your code at all places that need adjustment (check all array accesses)

A: Solution 1
Just changing the size of array solves the problem. As it was mentioned before, arr[48] does not exist. So, just create array with size of 60 (for ex.): int arr[60]
Solution 2
In order to conserve memory(i.e. not to waste 45 slots of array) you can do the following:
int arr[10];

for(int i = 0; i < strlen(a); i++)
  if(a[i] >= '0' && a[i] <= '9')
    arr[a[i] - '0']++;

for(int i = 0; i < 10; i++)
  printf("%d ", arr[i]);


text:
Q: PHP: Replacing funny character on PHP I'm trying to replace string "Red Dwarf (TV Series 1988â€") - IMDb" to "Red Dwarf (TV Series 1988') - IMDb"
I have a translation table of these funny characters in an array. I tried to replace them using: str_replace but it did not work. Can anybody suggest a workaround on this? This is the snippet of the code:
function replaceFunnyChar( $input ){

$translation = array(
    ''' => "'",
    "â€\"" => '-',
    'é' => 'é',
    'è' => 'è',
    '"' => '"',
    'â€' => '"',
    ''' => "'",
    'â' => 'ã',
    'Ã"' => 'ä',
    'â€"' => '–',
    'Ä«' => 'ī',
    '阴' => '阴',
    'é™°' => '陰',
    "阳" => "阳",
    "陽" => "陽",
    '´' => "'",
    'ü' => 'ü',
    "Ã,Ã'" => "'",
    '•' => '–'
);

foreach( $translation as $find => $replace ){
    $output = str_replace($find, $replace, $input );
    //$output = preg_replace("/" . $find . "/", $replace, $input );
}
return $output;
}

A: It is best to detect the encoding of the data you have (if you are scraping, then it is in the HTTP header, and overridden by the meta tag in the HTML), then you can use something such as Iconv to convert it: http://php.net/manual/en/book.iconv.php
If the data you get is UTF-8, you don't actually need to convert it.  Just store it and make sure your DBMS is set up to support UTF-8.  Then when displaying the data again, make sure you specify UTF-8 on your webpage.
If you are using Windows command line to show the characters, it is a little more complicated as Windows command line doesn't use UTF-8.  Try Ubuntu or Mac OS X.
Also, if you already have the data but cannot download it again, then you need to make sure how you show the characters -- if shown on a webpage, then the web browser can further mess up the characters if it uses a different encoding than what it is supposed to be.  You can also dump the bytes out, and replace the string using the byte sequence instead of quoted string as in the original code.

A: From the Top of my Head, thats an Decoding Error, you can probably get rid of it when you play around with the charsets for a while .
Anyhow, you can also just drop every char over ASCI 127:
function _dropAsciOver127($entity){
    if(($asciCode = ord($entity[0])) > 127){
        return '';
     }else{
        return $entity[0];
     }
 }

$weird = 'Red Dwarf (TV Series 1988â€") - IMDb';
$cool = preg_replace_callback('/[^\w\d ]/i','_dropAsciOver127', $weird);
print $cool; // prints Red Dwarf (TV Series 1988") - IMDb

A: I think your problem is your CHARSET, and a solution is to save the document as a UTF-8 (whitout BOM) in your text editor. Else you can add a header to your page, and it can be done like this:
HTML
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

PHP
header('Content-type: text/html; charset=utf-8');

Remember to set the header on top on top of the page! If you still having problems with charset, then try to change it from UTF-8 to ISO or something like that.

A: Make Sure These Things..
1: Table Collation type is UTF-8

2: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

if still not doing well try this before you add data in database
mysql_set_charset('utf8');


text:
Q: How to "bubble in"/color fill an item counter ((A),(B),(C),...) in an enumerated list I'm trying to make an answer explanation guide for a test where the correct answer is "bubbled in".
I've tried using the enumitem package and tikz as shown in this post (Enumerated list with blue circles and number inside it), but it's messing up the default spacing and the counters of the other answer choices. This is what I have so far:
\documentclass{article}
\usepackage{tikz}

\newcommand*\circled[1]{\tikz[baseline=(char.base)]{%
        \node[shape=circle,fill=blue!20,draw,inner sep=2pt] (char) {#1};}}

\usepackage{enumitem}

\begin{document}
\renewcommand{\labelenumi}{(\Alph{enumi})}
\begin{enumerate}
\item Answer A
\item[label=\circled{(\Alph*)}] Answer B
\item Answer C
\item Answer D
\item Answer E
\end{enumerate}

\end{document}

Ultimately what I want is something like this:

A transparent fill color would be nice. Thanks for any help.

A: You don't have to specify:
[label=\circled{(\Alph*)}]

but only:
[\circled{\Alph{enumi}}]

Moreover, it is also needed to advance the counter.
Therefore:
\documentclass{article}
\usepackage{tikz}

\newcommand*\circled[1]{\tikz[baseline=(char.base)]{%
        \node[circle,fill=blue!20,draw,inner sep=2pt,opacity=0.5,text opacity=1] (char) {#1};}}

\def\cnt{\stepcounter{enumi}\Alph{enumi}}

\usepackage{enumitem}

\begin{document}
\renewcommand{\labelenumi}{(\Alph{enumi})}
\begin{enumerate}
\item Answer A
\item Answer B
\item[\circled{\cnt}] Answer C
\item Answer D
\item Answer E
\end{enumerate}

\end{document}

gives:

A: A different approach. The main problem with this solution is that the placement of the circle is too "manual", and different fonts would require a new manual adjust.
\documentclass{article}
\usepackage{tikz}
\usepackage{enumitem}

\newcommand\correct{%
  \tikz[overlay]\fill[fill=green!50!black, opacity=.2] (-3ex,.6ex) circle (2ex);%
}

\begin{document}
\renewcommand{\labelenumi}{(\Alph{enumi})}
\begin{enumerate}
  \item Answer A
  \item\correct Answer B
  \item Answer C
  \item Answer D
  \item Answer E
\end{enumerate}
\end{document}

A: Another option, defining a dedicated command \citem and using the features provided by enumitem (instead of manually redefining \labelenumi):
\documentclass{article}
\usepackage{enumitem}
\usepackage{tikz}

\newcommand*\circled[1]{\tikz[baseline=(char.base)]{%
        \node[circle,fill=blue!20,draw,inner sep=2pt,opacity=0.5,text opacity=1] (char) {#1};}}

\newcommand\citem{%
  \stepcounter{enumi}\item[\circled{\Alph{enumi}}]}

\begin{document}

\begin{enumerate}[label=(\Alph*)]
\item Answer A
\item Answer B
\citem Answer C
\item Answer D
\item Answer E
\end{enumerate}

\end{document}


text:
Q: Word for "observing something with the purpose of gaining knowledge from it"? And for a long period of time.
Example:

He spent several nights [...] the terrorist's building.

I checked the synonyms of watch (noun lookout), but found nothing that could fit. There's also track, but I think it implies walking:

track
  follow the trail or movements of (someone or something), typically in
  order to find them or note their course.

Maybe to keep vigil?

A:
He spent several nights casing the terrorist's building.

Appropriate if the surveillance is done in anticipation of a crime, especially a robbery.  Also applies specifically to places or locations, not people nor things therein.  (For example, you case a bank, but not a bank manager nor a bank safe.)
From Merriam Webster:

to study or watch (a house, store, etc.) with plans to rob it

From Oxford Dictionaries:

informal Reconnoitre (a place) before carrying out a robbery

A: Most of the good words are taken.
One isn't:
studying [Oxford: verb, sense 2]

to watch or to look at somebody/something carefully in order to find out something

A: He spent several nights surveying the terrorist's building? Perhaps 'analyzing'?
http://www.thesaurus.com/browse/study might help inspire you!

A: To scrutinize may be another option:

*

*to examine or observe with great care; inspect critically.

*to examine carefully or in minute detail.

The Free Dictionary

A: To "monitor" is to continuously observe a defined subject
To "monitor" has for me the strongest implication of continuous attention regarding new knowledge to gain.
In the example, it is about collecting all relevant information, not to work with the infromation instead, which would draw attention from collecting.
So studying it, and investigating - all that comes later, based on the result of monitoring.

A: How about Spying
One who secretly collects information concerning the enemies of a government or group

Apart from the information collection being done secretly, I believe this word would fit in your requirement.

A: Scouting was what came to mind immediately for me.

He spent several nights scouting the terrorist's building.

A: If informal usage would work for you you could use:
stake out as a verb:

they'd staked out Culley's flat for a day (ODO)
He spent several nights staking out the terrorist's building.

A: Surveilling:
verb (transitive)
1. to observe closely the activities of (a person or group)
http://dictionary.reference.com/browse/surveilling?s=t

A: The act of checking out a location, particularly in the context of the military, is called reconnoitering. One can also make a reconnaisance of a place, like before attempting to occupy it. (M-W)

A: Sizing up sounds best to me although slightly colloquial:
He spent several nights sizing up the terrorist's building.
or more formally evaluating at the risk of losing some of the flavour:
He spent several nights evaluating the terrorist's building.

A: grok
verb \ˈgräk\
grokked grok·king
Definition of GROK:

transitive verb: to understand profoundly and intuitively

Examples of GROK

the eternal struggle of the human race to grok its place in the grand scheme of the universe

A: Combing through is an expression that fits your example well.

A: Auditing, like auditing a college course

A: The most reliable knowledge is that acquired by the scientific method.

Four essential elements of the scientific method are iterations,
  recursions, inter-leavings, or orderings of the following:

*

*Characterizations (observations, definitions, and measurements of the subject of inquiry)

*Hypotheses (theoretical, hypothetical explanations of observations and measurements of the subject)

*Predictions (reasoning including logical deduction from the hypothesis or theory)

*Experiments (tests of all of the above)
Wikipedia: Elements of the Scientific Method

So to gain knowledge scientists need to characterize the subject of inquiry.  One possible term for this process might be "data collection" but you'll be hard pressed to find a better term than your own, as @RegDwigнt already commented

observe
transitive verb

*

*1.a. To be or become aware of, especially through careful and directed attention; notice: observed a car leaving the property.

*1.b. To watch attentively: observe a child's behavior.

*1.c. To make a systematic or scientific observation of: observe the orbit of a comet.
TheFreeDictionary

A great example of making observations over a long period of time was

Tycho Brahe, born Tyge Ottesen Brahe (14 December 1546 – 24 October 1601), was a Danish nobleman known for his accurate and
  comprehensive astronomical and planetary observations. He was born in
  Scania, then part of Denmark, now part of modern-day Sweden. Tycho was
  well known in his lifetime as an astronomer, astrologer and alchemist,
  and has been described more recently as "the first competent mind in
  modern astronomy to feel ardently the passion for exact empirical
  facts."
Wikipedia

A: "peruse" - IMHO the best word possible to mean, "observing something with the purpose of gaining knowledge from it".  Although "examine" is pretty near exactly the same.


text:
Q: ROW_NUMBER() OVER (PARTITION BY nick ORDER BY p_time) in R having
x=data.frame(nick=c('a','a','b','b','b','c'), p_time=1:6)
  nick p_time
1    a      1
2    a      2
3    b      3
4    b      4
5    b      5
6    c      6

how can i get this:
  nick p_time flag
1    a      1    1
2    a      2    2
3    b      3    1
4    b      4    2
5    b      5    3
6    c      6    1

i used pgsql ROW_NUMBER() OVER (PARTITION BY nick ORDER BY p_time) to get it,but now need to use R only.
thanks.

A: Try dplyr::row_number() function
x %>%
  group_by(nick) %>%
  mutate(flag = row_number())

# A tibble: 6 x 3
# Groups: nick [3]
  nick  p_time  flag
  <fct>  <int> <int>
1 a          1     1
2 a          2     2
3 b          3     1
4 b          4     2
5 b          5     3
6 c          6     1

more information here

A: It looks like you just want to generate a "serial number" of sorts by group, where your groups are the "nick" column. If that's the case, you can just use ave and seq_along within within:
within(x, {
  flag <- ave(as.character(nick), nick, FUN = seq_along)
})
#   nick p_time flag
# 1    a      1    1
# 2    a      2    2
# 3    b      3    1
# 4    b      4    2
# 5    b      5    3
# 6    c      6    1

A: try this
x$flag<-as.vector(unlist(tapply(x$p_time,x$nick,FUN=function(x){1:length(x)})));


text:
Q: computation, algebra, logic So a really simple way of describing a digital computer is to say that it is a device for performing boolean operations. You feed it a bunch of bit strings, which is a description of the problem and its parameters in binary, the computer performs a bunch of boolean operations like $\wedge$, $\vee$, $\neg$ and gives you back another bit string which hopefully is the encoded version of the answer you were looking for. From this description it is not hard to see the connection of classical computation to discrete dynamical systems and classical logic, the operations provide the dynamics by flipping bits around in a controlled fashion and since we restrict the operations to a certain subset we get classical logic. My question is about analog and quantum computation. Is there a simple description of a quantum computer or an analog computer that makes the connection of that notion of computation to the other branches of mathematics a little more obvious? What is the most basic kind of enconding of a problem that can be fed into a quantum or analog computer and what are the most basic operations performed on this encoding?
Edit: Downvotes should come with comments so I know what to change in order to make my question clearer. Being a novice I'm just trying to piece together some themes about computation, logic and algebra.
Edit: alpheccar provided a link to a paper by John Baez and Mike Stay that pretty much answers my question and even puts it in a much wider context. Here's the link alpheccar provided.

A:
From this description it is not hard to see the connection of classical computation to discrete dynamical systems and classical logic, the operations provide the dynamics by flipping bits around in a controlled fashion and since we restrict the operations to a certain subset we get classical logic.

Careful -- this observation only works for purely finite-state systems! If your idealized model of a digital computer can handle potentially unbounded quantities of input, then the connection to classical logic is lost. Happily, it fails in a way that reveals connections to topology, and explains why topological models of intuitionistic logic exist.
The basic idea is that we view a computer as realizing a function $f$. Then for any input value (from the input set $A$), if it returns an answer in a finite amount of time, it can have observed at most a finite amount of information about the input. This means that we can equip our input set with a topology in the following way: suppose our basic observations are a collection of predicates on $A$. Then we get the topological structure from the following fact: we can only take finite intersections because we can only make finitely many observations, and so can only conclude the conjunction of finitely many predicates. We can take infinite unions (i.e., existentials) because we can "get lucky" and guess the correct branch of the union (i.e., witness to the existential).
Then, amazingly, we can use continuity as a stand-in for computability! This is pretty much the idea Dana Scott had when he invented domain theory (which gets a different name because the topologies that we get this way are "weird" -- e.g., they're typically not Hausdorff -- and so the theorems you want develop a bit differently).

A: The basic step of a quantum computation is the application of a unitary matrix to the qubits. Thus, a quantum computing consists in iterating this unitary matrix.
One can view the quantum computation as built up from gates, not classical logic gates, but rather, quantum gates, each represented by a unitary matrix. One interesting difference with classical computation gates is that these quantum gates are necessarily reversible, and so quantum computations are in principle reversible. (There are also classical reversible gates, such as the Toffoli gate, that suffice for classical computation.)
Solovay and Kitaev provided a set of universal quantum gates.


text:
Q: My cursor appears in wrong position, after adding blockquote with CSS I am using a blockquote for example:

This is an example

And then a custom CSS to have a style like below:
blockquote{
  font-size: 18px;
  //margin: 0 auto;
  quotes: "\201C""\201D""\2018""\2019";
  padding: 10px 20px;
  line-height: 1.4;
}

blockquote:before {
  content: open-quote;
  display: inline;
  height: 0;
  line-height: 0;
  left: -10px;
  position: relative;
  top: 20px;
  color: #ccc;
  font-size: 3em;
}
blockquote:after {
  content: close-quote;
  display: inline;
  height: 0;
  line-height: 0;
  left: 10px;
  position: relative;
  top: 40px;
  color: #ccc;
  font-size: 3em;
}

But I have issus with the appearance of cursor. I have tried something like: cursor: none !important; It looks like I can not hide it.
Please see this video of how it looks like and it is annoying. At this moment you can write on two positions of cursor, please check this video in order to better understand what I mean.


text:
Q: Firestore add data over an object within a document's data REACT.JS I want to add some data on the bookChapters object, like a random id and inside of it the name of the chapters, I tried this but it doesn't work, after I add the previous data I also want to add a new object "takeAways", like the previous one, inside the random id object.

export const createNewChapter = (bookId, inputText) => {
  return async dispatch => {
    dispatch(createNewChapterStart());
    try {
firebase
        .firestore()
        .doc(`Users/${bookId}/bookChapters/${inputText}`)
        .onSnapshot(querySnapshot => {
          //There I want to add the chapters to the firestore database
        });
      dispatch(createNewChapterSuccess(inputText));
    } catch (error) {
      dispatch(createNewChapterFail(error));
      console.log(error);
    }
  };
};

A:
I wanna know how to do add from scratch the bookChapters object

The database screenshot shows that the bookChapters object is a map. So to add (populate) this object you need to generate a simple JavaScript object with some properties as "key: value" pairs.
Something along these lines, making the assumption the chapter titles are in an Array:
  function arrayToObject(arr) {
    var obj = {};
    for (var i = 0; i < arr.length; ++i) {
      obj[i] = arr[i];
    }
    return obj;
  }

  const chapterList = ['Intro', 'Chapter 1', 'Chapter2', 'Conclusion'];
  const bookChaptersObj = arrayToObject(chapterList);

  firebase.firestore().doc(`Users/${bookId}`).update(bookChaptersObj);

Or, if the document does not already exist:
firebase.firestore().doc(`Users/${bookId}`).set(bookChaptersObj, {merge: true});


text:
Q: Can not create Elasticsearch cluster with version 2.3.5 I'm trying to create Elasticsearch cluster (2,3 nodes) with version 2.3.5 on Ubuntu 16.04.
In some articles said that if all nodes in one network, need to specify same cluster name in all nodes then Elasticsearch itself will discover them and will add to cluster. I did it but with no results.
Could you help me, is this feature works on 2.3.5?
or need to specify:
discovery.zen.ping.unicast.hosts: ["10.0.0.1", "10.0.0.2", "10.0.0.3"]

Thanks.

A: If Elasticsearch instances are in the same network they can discover each other and form a cluster. You can specify a cluster name as you say. The default discovery port is 9300. So ensure if that port is reachable between nodes.
Specifying is node address is also an option.
https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-discovery.html


text:
Q: Showing a set is a compact subset of $\mathbb{R}$ Question: Let $$A=\{ x \in \mathbb{R}: x(x^{3}-3x-1)\leq15 \}.$$
Show that A is a compact subset of $\mathbb{R}$.
I am just wondering how to approach this problem. Should I try showing it directly? Or is it enough to show that the set is closed and bounded in $\mathbb{R}$? Thanks

A: This is a cool question and it's probably best to do it using sequences.
First note that the quartic $q(x)=x(x^3-3x-1)-15=x^4+\ldots\,$ goes to $+\infty$ as $x\longrightarrow\pm\infty$, so the set $A$ of all $x\in\mathbb{R}$ with $q(x)\leq 0$ is bounded - this can be easily made rigorous. Instead, you could also use of the fact that $x^3-3x-1=1+(x-2)(x+1)^2$ is $\geq 1$ if and only if $x\geq 2$.
For closedness, I'd use the sequential characterization: Let $(x_n)\subseteq A$ converge to some $x\in\mathbb{R}$. Then $x_n(x_n^3-3x_n-1)$ converges to $x(x^3-3x-1)$ by standard limit theorems. Since $x_n(x_n^3-3x_n-1)\leq 15$ we also get $x(x^3-3x-1)\leq 15$ by an elementary theorem. So $x\in A$.
If you are not comfortable using Heine-Borel here, you could use the fact that $A$ being compact is equivalent to every sequence in $A$ having a convergent subsequence in $A$: Starting with a sequence in $A$, you know it's bounded (as above), so Bolzano-Weierstrass gives you a convergent subsequence $\longrightarrow x\in\mathbb{R}$. Then you show that $x\in A$ by essentially the above closedness argument.

A: I guess a more general solution can be given as follows: Let $p$ be any polynomial, and $a$ be a constant real number. Then, since as $x$ goes to $\infty$ or $-\infty$ we know polynomial won't be bounded, we conclude that the set of $x$ satisfying $p(x)\leq a$ must be bounded. On the other hand, consider the set of $x$ such that $p(x)>a$. For each $x$ from this set, by the continuity of $p$, there will be an open neigborhood of $x$ that $p(x)>a$ remains true, so complement of our  original set is open, so our set is closed. Hence, our set is always compact.


text:
Q: An act of making a citizen work (spy?) against his own country What's the right word to describe an act of making a citizen of one country (by either paying him or, perhaps, setting him up in some way) start getting and sharing some important info about his own country?
For example,

The FBI forces finally ______________(ed) the Russian scientist Ivanov
  in 1957. So, starting from 1957 he's been sending all important
  information about Russian militaries to the White House.

(or something like that)

A: The conventional term is turn, but it does not imply compulsion, as your term "make" does; it may involve payment or principled persuasion as well as blackmail.
And just by the way: the FBI is a domestic agency; it may recruit Russians within the US but would not ordinarily run or recruit agents abroad. That's the job of the CIA.

The CIA turned the Russian scientist Ivanov in 1957.


text:
Q: Rails (PostgreSQL?) implicit sequence/index warning
Possible Duplicate:
NOTICES for sequence after running migration in rails on postgresql Application

Using PostgreSQL for development & test databases (as well as production). When I rake db:test:prepare my PostgreSQL theapp_test database I get these messages for each table:
NOTICE:  CREATE TABLE will create implicit sequence "events_id_seq" for serial column "events.id"
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "events_pkey" for table "events"
NOTICE:  CREATE TABLE will create implicit sequence "users_id_seq" for serial column "users.id"
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "users_pkey" for table "users"
...

I do not get these notices with rake db:migrate on theapp_development. And I haven't noticed them in production. What does it mean and should I work to get rid of them?
FYI - This didn't occur in the past when I have used MySQL (or SQLite3 for that matter) for testing...

A: No. That's just Postgres being awesome and automatically creating stuff for you that you actually want. It's not a warning it's just an FYI

A: You can silence these messages by adding (or uncommenting) a line in config/database.yml:
# config/database.yml
development:
  adapter: postgresql
  min_messages: WARNING  # this line silences those NOTICE messages